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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// PolicyDefinitionsOperations operations. /// </summary> internal partial class PolicyDefinitionsOperations : Microsoft.Rest.IServiceOperations<PolicyClient>, IPolicyDefinitionsOperations { /// <summary> /// Initializes a new instance of the PolicyDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PolicyDefinitionsOperations(PolicyClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the PolicyClient /// </summary> public PolicyClient Client { get; private set; } /// <summary> /// Creates or updates a policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to create. /// </param> /// <param name='parameters'> /// The policy definition properties. /// </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<PolicyDefinition>> CreateOrUpdateWithHttpMessagesAsync(string policyDefinitionName, PolicyDefinition parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (policyDefinitionName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName"); } 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("policyDefinitionName", policyDefinitionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName)); _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 += (_url.Contains("?") ? "&" : "?") + 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<PolicyDefinition>(); _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<PolicyDefinition>(_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 a policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to delete. /// </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 policyDefinitionName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (policyDefinitionName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName"); } 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("policyDefinitionName", policyDefinitionName); 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}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName)); _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 += (_url.Contains("?") ? "&" : "?") + 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 && (int)_statusCode != 200) { 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 the policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The name of the policy definition to get. /// </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<PolicyDefinition>> GetWithHttpMessagesAsync(string policyDefinitionName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (policyDefinitionName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyDefinitionName"); } 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("policyDefinitionName", policyDefinitionName); 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}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", System.Uri.EscapeDataString(policyDefinitionName)); _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 += (_url.Contains("?") ? "&" : "?") + 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<PolicyDefinition>(); _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<PolicyDefinition>(_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> /// Gets all the policy definitions for a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <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<PolicyDefinition>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<PolicyDefinition> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyDefinition>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { 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("odataQuery", odataQuery); 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}/providers/Microsoft.Authorization/policydefinitions").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + 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<PolicyDefinition>>(); _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<PolicyDefinition>>(_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> /// Gets all the policy definitions for a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="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<PolicyDefinition>>> 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 += (_url.Contains("?") ? "&" : "?") + 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<PolicyDefinition>>(); _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<PolicyDefinition>>(_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; } } }
//----------------------------------------------------------------------- // <copyright file="DataPortal.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the client-side DataPortal.</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using Csla.Reflection; using Csla.Properties; using Csla.Server; using Csla.Serialization.Mobile; using System.Threading.Tasks; namespace Csla { /// <summary> /// This is the client-side DataPortal. /// </summary> public static class DataPortal { private static readonly EmptyCriteria EmptyCriteria = new EmptyCriteria(); /// <summary> /// Raised by DataPortal before it starts /// setting up to call a server-side /// DataPortal method. /// </summary> public static event Action<System.Object> DataPortalInitInvoke; /// <summary> /// Raised by DataPortal prior to calling the /// requested server-side DataPortal method. /// </summary> public static event Action<DataPortalEventArgs> DataPortalInvoke; /// <summary> /// Raised by DataPortal after the requested /// server-side DataPortal method call is complete. /// </summary> public static event Action<DataPortalEventArgs> DataPortalInvokeComplete; internal static void OnDataPortalInitInvoke(object e) { DataPortalInitInvoke?.Invoke(e); } internal static void OnDataPortalInvoke(DataPortalEventArgs e) { DataPortalInvoke?.Invoke(e); } internal static void OnDataPortalInvokeComplete(DataPortalEventArgs e) { DataPortalInvokeComplete?.Invoke(e); } /// <summary> /// Called by a factory method in a business class to create /// a new object, which is loaded with default /// values from the database. /// </summary> /// <typeparam name="T">Specific type of the business object.</typeparam> /// <param name="criteria">Object-specific criteria.</param> /// <returns>A new object, populated with default values.</returns> public static T Create<T>(object criteria) { var dp = new DataPortal<T>(); return dp.Create(criteria); } /// <summary> /// Called by a factory method in a business class to create /// a new object, which is loaded with default /// values from the database. /// </summary> /// <typeparam name="T">Specific type of the business object.</typeparam> /// <returns>A new object, populated with default values.</returns> public static T Create<T>() { return Create<T>(EmptyCriteria); } /// <summary> /// Called by a factory method in a business class to create /// a new object, which is loaded with default /// values from the database. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Object-specific criteria.</param> /// <returns>A new object, populated with default values.</returns> public static object Create(Type objectType, object criteria) { return DataPortal<object>.Create(objectType, criteria); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginCreate<T>(EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginCreate<T>(DataPortal<T>.EmptyCriteria, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginCreate<T>(EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { BeginCreate<T>(DataPortal<T>.EmptyCriteria, callback, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to create. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginCreate<T>(object criteria, EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginCreate<T>(criteria, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to create. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginCreate<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { DataPortal<T> dp = new DataPortal<T>(); dp.CreateCompleted += callback; dp.BeginCreate(criteria, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> public static async Task<T> CreateAsync<T>() { DataPortal<T> dp = new DataPortal<T>(); return await dp.CreateAsync(); } /// <summary> /// Starts an asynchronous data portal operation to /// create a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to create. /// </param> public static async Task<T> CreateAsync<T>(object criteria) { DataPortal<T> dp = new DataPortal<T>(); return await dp.CreateAsync(criteria); } /// <summary> /// Called by a factory method in a business class to retrieve /// an object, which is loaded with values from the database. /// </summary> /// <typeparam name="T">Specific type of the business object.</typeparam> /// <param name="criteria">Object-specific criteria.</param> /// <returns>An object populated with values from the database.</returns> public static T Fetch<T>(object criteria) { var dp = new DataPortal<T>(); return dp.Fetch(criteria); } /// <summary> /// Called by a factory method in a business class to retrieve /// an object, which is loaded with values from the database. /// </summary> /// <typeparam name="T">Specific type of the business object.</typeparam> /// <returns>An object populated with values from the database.</returns> public static T Fetch<T>() { return Fetch<T>(EmptyCriteria); } internal static object Fetch(Type objectType, object criteria) { return DataPortal<object>.Fetch(objectType, criteria); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginFetch<T>(EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginFetch<T>(DataPortal<T>.EmptyCriteria, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginFetch<T>(EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { BeginFetch<T>(DataPortal<T>.EmptyCriteria, callback, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to fetch. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginFetch<T>(object criteria, EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginFetch<T>(criteria, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to fetch. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginFetch<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { var dp = new DataPortal<T>(); dp.FetchCompleted += callback; dp.BeginFetch(criteria, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> public static async Task<T> FetchAsync<T>() where T : IMobileObject { var dp = new DataPortal<T>(); return await dp.FetchAsync(); } /// <summary> /// Starts an asynchronous data portal operation to /// fetch a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to fetch. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to fetch. /// </param> public static async Task<T> FetchAsync<T>(object criteria) where T : IMobileObject { var dp = new DataPortal<T>(); return await dp.FetchAsync(criteria); } /// <summary> /// Called by the business object's Save() method to /// insert, update or delete an object in the database. /// </summary> /// <remarks> /// Note that this method returns a reference to the updated business object. /// If the server-side DataPortal is running remotely, this will be a new and /// different object from the original, and all object references MUST be updated /// to use this new object. /// </remarks> /// <typeparam name="T">Specific type of the business object.</typeparam> /// <param name="obj">A reference to the business object to be updated.</param> /// <returns>A reference to the updated business object.</returns> public static T Update<T>(T obj) { var dp = new DataPortal<T>(); return dp.Update(obj); } /// <summary> /// Starts an asynchronous data portal operation to /// update a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to update. /// </typeparam> /// <param name="obj"> /// Business object to update. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginUpdate<T>(T obj, EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginUpdate<T>(obj, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// update a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to update. /// </typeparam> /// <param name="obj"> /// Business object to update. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginUpdate<T>(T obj, EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { DataPortal<T> dp = new DataPortal<T>(); dp.UpdateCompleted += callback; dp.BeginUpdate(obj, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// update a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to update. /// </typeparam> /// <param name="obj"> /// Business object to update. /// </param> public static async Task<T> UpdateAsync<T>(T obj) where T : IMobileObject { DataPortal<T> dp = new DataPortal<T>(); return await dp.UpdateAsync(obj); } /// <summary> /// Called by a Shared (static in C#) method in the business class to cause /// immediate deletion of a specific object from the database. /// </summary> /// <param name="criteria">Object-specific criteria.</param> public static void Delete<T>(object criteria) { var dp = new DataPortal<T>(); dp.Delete(criteria); } internal static void Delete(Type objectType, object criteria) { DataPortal<object>.Delete(objectType, criteria); } /// <summary> /// Starts an asynchronous data portal operation to /// delete a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to delete. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to delete. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginDelete<T>(object criteria, EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginDelete<T>(criteria, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// delete a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to delete. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to delete. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginDelete<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { var dp = new DataPortal<T>(); dp.DeleteCompleted += callback; dp.BeginDelete(criteria, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// delete a business object. /// </summary> /// <typeparam name="T"> /// Type of business object to delete. /// </typeparam> /// <param name="criteria"> /// Criteria describing the object to delete. /// </param> public static async Task DeleteAsync<T>(object criteria) where T : IMobileObject { var dp = new DataPortal<T>(); await dp.DeleteAsync(criteria); } /// <summary> /// Called to execute a Command object on the server. /// </summary> /// <remarks> /// <para> /// To be a Command object, the object must inherit from /// CommandBase. /// </para><para> /// Note that this method returns a reference to the updated business object. /// If the server-side DataPortal is running remotely, this will be a new and /// different object from the original, and all object references MUST be updated /// to use this new object. /// </para><para> /// On the server, the Command object's DataPortal_Execute() method will /// be invoked and on an ObjectFactory the Execute method will be invoked. /// Write any server-side code in that method. /// </para> /// </remarks> /// <typeparam name="T">Specific type of the Command object.</typeparam> /// <param name="obj">A reference to the Command object to be executed.</param> /// <returns>A reference to the updated Command object.</returns> public static T Execute<T>(T obj) { return Update(obj); } /// <summary> /// Starts an asynchronous data portal operation to /// execute a command object. /// </summary> /// <typeparam name="T"> /// Type of object to execute. /// </typeparam> /// <param name="obj"> /// Reference to the object to execute. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> [Obsolete] public static void BeginExecute<T>(T obj, EventHandler<DataPortalResult<T>> callback) where T : IMobileObject { BeginExecute<T>(obj, callback, null); } /// <summary> /// Starts an asynchronous data portal operation to /// execute a command object. /// </summary> /// <typeparam name="T"> /// Type of object to execute. /// </typeparam> /// <param name="obj"> /// Reference to the object to execute. /// </param> /// <param name="callback"> /// Reference to method that will handle the /// asynchronous callback when the operation /// is complete. /// </param> /// <param name="userState">User state object.</param> [Obsolete] public static void BeginExecute<T>(T obj, EventHandler<DataPortalResult<T>> callback, object userState) where T : IMobileObject { var dp = new DataPortal<T>(); dp.ExecuteCompleted += callback; dp.BeginExecute(obj, userState); } /// <summary> /// Starts an asynchronous data portal operation to /// execute a command object. /// </summary> /// <typeparam name="T"> /// Type of object to execute. /// </typeparam> /// <param name="command"> /// Reference to the object to execute. /// </param> public static async Task<T> ExecuteAsync<T>(T command) where T : IMobileObject { var dp = new DataPortal<T>(); return await dp.ExecuteAsync(command); } /// <summary> /// Creates and initializes a new /// child business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> public static T CreateChild<T>() { Server.ChildDataPortal portal = new Server.ChildDataPortal(); return (T)(portal.Create(typeof(T))); } /// <summary> /// Creates and initializes a new /// child business object. /// </summary> /// <typeparam name="T"> /// Type of business object to create. /// </typeparam> /// <param name="parameters"> /// Parameters passed to child create method. /// </param> public static T CreateChild<T>(params object[] parameters) { Server.ChildDataPortal portal = new Server.ChildDataPortal(); return (T)(portal.Create(typeof(T), parameters)); } /// <summary> /// Creates and loads an existing /// child business object. /// </summary> /// <typeparam name="T"> /// Type of business object to retrieve. /// </typeparam> public static T FetchChild<T>() { Server.ChildDataPortal portal = new Server.ChildDataPortal(); return (T)(portal.Fetch(typeof(T))); } /// <summary> /// Creates and loads an existing /// child business object. /// </summary> /// <typeparam name="T"> /// Type of business object to retrieve. /// </typeparam> /// <param name="parameters"> /// Parameters passed to child fetch method. /// </param> public static T FetchChild<T>(params object[] parameters) { Server.ChildDataPortal portal = new Server.ChildDataPortal(); return (T)(portal.Fetch(typeof(T), parameters)); } /// <summary> /// Inserts, updates or deletes an existing /// child business object. /// </summary> /// <param name="child"> /// Business object to update. /// </param> public static void UpdateChild(object child) { Server.ChildDataPortal portal = new Server.ChildDataPortal(); portal.Update(child); } /// <summary> /// Inserts, updates or deletes an existing /// child business object. /// </summary> /// <param name="child"> /// Business object to update. /// </param> /// <param name="parameters"> /// Parameters passed to child update method. /// </param> public static void UpdateChild(object child, params object[] parameters) { Server.ChildDataPortal portal = new Server.ChildDataPortal(); portal.Update(child, parameters); } private static DataPortalClient.IDataPortalProxyFactory _dataProxyFactory; /// <summary> /// Loads the data portal factory. /// </summary> internal static void LoadDataPortalProxyFactory() { if (_dataProxyFactory == null) { if (String.IsNullOrEmpty(ApplicationContext.DataPortalProxyFactory) || ApplicationContext.DataPortalProxyFactory == "Default") { _dataProxyFactory = new DataPortalClient.DataPortalProxyFactory(); } else { var proxyFactoryType = Type.GetType(ApplicationContext.DataPortalProxyFactory) ?? throw new InvalidOperationException( string.Format(Resources.UnableToLoadDataPortalProxyFactory, ApplicationContext.DataPortalProxyFactory)); _dataProxyFactory = (DataPortalClient.IDataPortalProxyFactory)MethodCaller.CreateInstance(proxyFactoryType); } } } /// <summary> /// Gets or sets a reference to a ProxyFactory object /// that is used to create an instance of the data /// portal proxy object. /// </summary> public static DataPortalClient.IDataPortalProxyFactory ProxyFactory { get { if (_dataProxyFactory == null) LoadDataPortalProxyFactory(); return _dataProxyFactory; } set { _dataProxyFactory = value; } } /// <summary> /// Gets or sets the assembly qualified type /// name of the proxy object to be loaded /// by the data portal. "Local" is a special /// value used to indicate that the data /// portal should run in local mode. /// </summary> /// <remarks> /// Deprecated: use ApplicationContext.DataPortalProxy /// </remarks> public static string ProxyTypeName { get { return ApplicationContext.DataPortalProxy; } set { ApplicationContext.DataPortalProxy = value; } } /// <summary> /// Resets the data portal proxy type, so the /// next data portal call will reload the proxy /// type based on current configuration values. /// </summary> public static void ResetProxyFactory() { _dataProxyFactory = null; } /// <summary> /// Resets the data portal proxy type, so the /// next data portal call will reload the proxy /// type based on current configuration values. /// </summary> public static void ResetProxyType() { if (_dataProxyFactory != null) { _dataProxyFactory.ResetProxyType(); } } /// <summary> /// Releases any remote data portal proxy object, so /// the next data portal call will create a new /// proxy instance. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Proxies no longer cached")] public static void ReleaseProxy() { } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using dnlib.DotNet.Emit; namespace dnlib.DotNet { /// <summary> /// Finds types, fields, methods, etc in a module. If nothing has been added to the module, it's /// faster to call ResolveMethodDef(), ResolveTypeRef() etc. /// </summary> public class MemberFinder { enum ObjectType { Unknown, EventDef, FieldDef, GenericParam, MemberRef, MethodDef, MethodSpec, PropertyDef, TypeDef, TypeRef, TypeSig, TypeSpec, ExportedType, } /// <summary> /// All found <see cref="CustomAttribute"/>s /// </summary> public readonly Dictionary<CustomAttribute, bool> CustomAttributes = new Dictionary<CustomAttribute, bool>(); /// <summary> /// All found <see cref="EventDef"/>s /// </summary> public readonly Dictionary<EventDef, bool> EventDefs = new Dictionary<EventDef, bool>(); /// <summary> /// All found <see cref="FieldDef"/>s /// </summary> public readonly Dictionary<FieldDef, bool> FieldDefs = new Dictionary<FieldDef, bool>(); /// <summary> /// All found <see cref="GenericParam"/>s /// </summary> public readonly Dictionary<GenericParam, bool> GenericParams = new Dictionary<GenericParam, bool>(); /// <summary> /// All found <see cref="MemberRef"/>s /// </summary> public readonly Dictionary<MemberRef, bool> MemberRefs = new Dictionary<MemberRef, bool>(); /// <summary> /// All found <see cref="MethodDef"/>s /// </summary> public readonly Dictionary<MethodDef, bool> MethodDefs = new Dictionary<MethodDef, bool>(); /// <summary> /// All found <see cref="MethodSpec"/>s /// </summary> public readonly Dictionary<MethodSpec, bool> MethodSpecs = new Dictionary<MethodSpec, bool>(); /// <summary> /// All found <see cref="PropertyDef"/>s /// </summary> public readonly Dictionary<PropertyDef, bool> PropertyDefs = new Dictionary<PropertyDef, bool>(); /// <summary> /// All found <see cref="TypeDef"/>s /// </summary> public readonly Dictionary<TypeDef, bool> TypeDefs = new Dictionary<TypeDef, bool>(); /// <summary> /// All found <see cref="TypeRef"/>s /// </summary> public readonly Dictionary<TypeRef, bool> TypeRefs = new Dictionary<TypeRef, bool>(); /// <summary> /// All found <see cref="TypeSig"/>s /// </summary> public readonly Dictionary<TypeSig, bool> TypeSigs = new Dictionary<TypeSig, bool>(); /// <summary> /// All found <see cref="TypeSpec"/>s /// </summary> public readonly Dictionary<TypeSpec, bool> TypeSpecs = new Dictionary<TypeSpec, bool>(); /// <summary> /// All found <see cref="ExportedType"/>s /// </summary> public readonly Dictionary<ExportedType, bool> ExportedTypes = new Dictionary<ExportedType, bool>(); Stack<object> objectStack; ModuleDef validModule; /// <summary> /// Finds all types, fields, etc /// </summary> /// <param name="module">The module to scan</param> /// <returns>Itself</returns> public MemberFinder FindAll(ModuleDef module) { validModule = module; // This needs to be big. About 2048 entries should be enough for most though... objectStack = new Stack<object>(0x1000); Add(module); ProcessAll(); objectStack = null; return this; } void Push(object mr) { if (mr is null) return; objectStack.Push(mr); } void ProcessAll() { while (objectStack.Count > 0) { var o = objectStack.Pop(); switch (GetObjectType(o)) { case ObjectType.Unknown: break; case ObjectType.EventDef: Add((EventDef)o); break; case ObjectType.FieldDef: Add((FieldDef)o); break; case ObjectType.GenericParam: Add((GenericParam)o); break; case ObjectType.MemberRef: Add((MemberRef)o); break; case ObjectType.MethodDef: Add((MethodDef)o); break; case ObjectType.MethodSpec: Add((MethodSpec)o); break; case ObjectType.PropertyDef: Add((PropertyDef)o); break; case ObjectType.TypeDef: Add((TypeDef)o); break; case ObjectType.TypeRef: Add((TypeRef)o); break; case ObjectType.TypeSig: Add((TypeSig)o); break; case ObjectType.TypeSpec: Add((TypeSpec)o); break; case ObjectType.ExportedType: Add((ExportedType)o); break; default: throw new InvalidOperationException($"Unknown type: {o.GetType()}"); } } } readonly Dictionary<Type, ObjectType> toObjectType = new Dictionary<Type, ObjectType>(); ObjectType GetObjectType(object o) { if (o is null) return ObjectType.Unknown; var type = o.GetType(); if (toObjectType.TryGetValue(type, out var mrType)) return mrType; mrType = GetObjectType2(o); toObjectType[type] = mrType; return mrType; } static ObjectType GetObjectType2(object o) { if (o is EventDef) return ObjectType.EventDef; if (o is FieldDef) return ObjectType.FieldDef; if (o is GenericParam) return ObjectType.GenericParam; if (o is MemberRef) return ObjectType.MemberRef; if (o is MethodDef) return ObjectType.MethodDef; if (o is MethodSpec) return ObjectType.MethodSpec; if (o is PropertyDef) return ObjectType.PropertyDef; if (o is TypeDef) return ObjectType.TypeDef; if (o is TypeRef) return ObjectType.TypeRef; if (o is TypeSig) return ObjectType.TypeSig; if (o is TypeSpec) return ObjectType.TypeSpec; if (o is ExportedType) return ObjectType.ExportedType; return ObjectType.Unknown; } void Add(ModuleDef mod) { Push(mod.ManagedEntryPoint); Add(mod.CustomAttributes); Add(mod.Types); Add(mod.ExportedTypes); if (mod.IsManifestModule) Add(mod.Assembly); Add(mod.VTableFixups); Add(mod.Resources); } void Add(VTableFixups fixups) { if (fixups is null) return; foreach (var fixup in fixups) { foreach (var method in fixup) Push(method); } } void Add(ResourceCollection resources) { foreach (var resource in resources) { Add(resource.CustomAttributes); } } void Add(AssemblyDef asm) { if (asm is null) return; Add(asm.DeclSecurities); Add(asm.CustomAttributes); } void Add(CallingConventionSig sig) { if (sig is null) return; if (sig is FieldSig fs) { Add(fs); return; } if (sig is MethodBaseSig mbs) { Add(mbs); return; } if (sig is LocalSig ls) { Add(ls); return; } if (sig is GenericInstMethodSig gims) { Add(gims); return; } } void Add(FieldSig sig) { if (sig is null) return; Add(sig.Type); } void Add(MethodBaseSig sig) { if (sig is null) return; Add(sig.RetType); Add(sig.Params); Add(sig.ParamsAfterSentinel); } void Add(LocalSig sig) { if (sig is null) return; Add(sig.Locals); } void Add(GenericInstMethodSig sig) { if (sig is null) return; Add(sig.GenericArguments); } void Add(IEnumerable<CustomAttribute> cas) { if (cas is null) return; foreach (var ca in cas) Add(ca); } void Add(CustomAttribute ca) { if (ca is null || CustomAttributes.ContainsKey(ca)) return; CustomAttributes[ca] = true; Push(ca.Constructor); Add(ca.ConstructorArguments); Add(ca.NamedArguments); } void Add(IEnumerable<CAArgument> args) { if (args is null) return; foreach (var arg in args) Add(arg); } void Add(CAArgument arg) { // It's a struct so can't be null Add(arg.Type); if (arg.Value is TypeSig typeSig) Add(typeSig); else if (arg.Value is IList<CAArgument> args) Add(args); } void Add(IEnumerable<CANamedArgument> args) { if (args is null) return; foreach (var arg in args) Add(arg); } void Add(CANamedArgument arg) { if (arg is null) return; Add(arg.Type); Add(arg.Argument); } void Add(IEnumerable<DeclSecurity> decls) { if (decls is null) return; foreach (var decl in decls) Add(decl); } void Add(DeclSecurity decl) { if (decl is null) return; Add(decl.SecurityAttributes); Add(decl.CustomAttributes); } void Add(IEnumerable<SecurityAttribute> secAttrs) { if (secAttrs is null) return; foreach (var secAttr in secAttrs) Add(secAttr); } void Add(SecurityAttribute secAttr) { if (secAttr is null) return; Add(secAttr.AttributeType); Add(secAttr.NamedArguments); } void Add(ITypeDefOrRef tdr) { if (tdr is TypeDef td) { Add(td); return; } if (tdr is TypeRef tr) { Add(tr); return; } if (tdr is TypeSpec ts) { Add(ts); return; } } void Add(IEnumerable<EventDef> eds) { if (eds is null) return; foreach (var ed in eds) Add(ed); } void Add(EventDef ed) { if (ed is null || EventDefs.ContainsKey(ed)) return; if (ed.DeclaringType is not null && ed.DeclaringType.Module != validModule) return; EventDefs[ed] = true; Push(ed.EventType); Add(ed.CustomAttributes); Add(ed.AddMethod); Add(ed.InvokeMethod); Add(ed.RemoveMethod); Add(ed.OtherMethods); Add(ed.DeclaringType); } void Add(IEnumerable<FieldDef> fds) { if (fds is null) return; foreach (var fd in fds) Add(fd); } void Add(FieldDef fd) { if (fd is null || FieldDefs.ContainsKey(fd)) return; if (fd.DeclaringType is not null && fd.DeclaringType.Module != validModule) return; FieldDefs[fd] = true; Add(fd.CustomAttributes); Add(fd.Signature); Add(fd.DeclaringType); Add(fd.MarshalType); } void Add(IEnumerable<GenericParam> gps) { if (gps is null) return; foreach (var gp in gps) Add(gp); } void Add(GenericParam gp) { if (gp is null || GenericParams.ContainsKey(gp)) return; GenericParams[gp] = true; Push(gp.Owner); Push(gp.Kind); Add(gp.GenericParamConstraints); Add(gp.CustomAttributes); } void Add(IEnumerable<GenericParamConstraint> gpcs) { if (gpcs is null) return; foreach (var gpc in gpcs) Add(gpc); } void Add(GenericParamConstraint gpc) { if (gpc is null) return; Add(gpc.Owner); Push(gpc.Constraint); Add(gpc.CustomAttributes); } void Add(MemberRef mr) { if (mr is null || MemberRefs.ContainsKey(mr)) return; if (mr.Module != validModule) return; MemberRefs[mr] = true; Push(mr.Class); Add(mr.Signature); Add(mr.CustomAttributes); } void Add(IEnumerable<MethodDef> methods) { if (methods is null) return; foreach (var m in methods) Add(m); } void Add(MethodDef md) { if (md is null || MethodDefs.ContainsKey(md)) return; if (md.DeclaringType is not null && md.DeclaringType.Module != validModule) return; MethodDefs[md] = true; Add(md.Signature); Add(md.ParamDefs); Add(md.GenericParameters); Add(md.DeclSecurities); Add(md.MethodBody); Add(md.CustomAttributes); Add(md.Overrides); Add(md.DeclaringType); } void Add(MethodBody mb) { if (mb is CilBody cb) Add(cb); } void Add(CilBody cb) { if (cb is null) return; Add(cb.Instructions); Add(cb.ExceptionHandlers); Add(cb.Variables); } void Add(IEnumerable<Instruction> instrs) { if (instrs is null) return; foreach (var instr in instrs) { if (instr is null) continue; switch (instr.OpCode.OperandType) { case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: Push(instr.Operand); break; case OperandType.InlineSig: Add(instr.Operand as CallingConventionSig); break; case OperandType.InlineVar: case OperandType.ShortInlineVar: var local = instr.Operand as Local; if (local is not null) { Add(local); break; } var arg = instr.Operand as Parameter; if (arg is not null) { Add(arg); break; } break; } } } void Add(IEnumerable<ExceptionHandler> ehs) { if (ehs is null) return; foreach (var eh in ehs) Push(eh.CatchType); } void Add(IEnumerable<Local> locals) { if (locals is null) return; foreach (var local in locals) Add(local); } void Add(Local local) { if (local is null) return; Add(local.Type); } void Add(IEnumerable<Parameter> ps) { if (ps is null) return; foreach (var p in ps) Add(p); } void Add(Parameter param) { if (param is null) return; Add(param.Type); Add(param.Method); } void Add(IEnumerable<ParamDef> pds) { if (pds is null) return; foreach (var pd in pds) Add(pd); } void Add(ParamDef pd) { if (pd is null) return; Add(pd.DeclaringMethod); Add(pd.CustomAttributes); Add(pd.MarshalType); } void Add(MarshalType mt) { if (mt is null) return; switch (mt.NativeType) { case NativeType.SafeArray: Add(((SafeArrayMarshalType)mt).UserDefinedSubType); break; case NativeType.CustomMarshaler: Add(((CustomMarshalType)mt).CustomMarshaler); break; } } void Add(IEnumerable<MethodOverride> mos) { if (mos is null) return; foreach (var mo in mos) Add(mo); } void Add(MethodOverride mo) { // It's a struct so can't be null Push(mo.MethodBody); Push(mo.MethodDeclaration); } void Add(MethodSpec ms) { if (ms is null || MethodSpecs.ContainsKey(ms)) return; if (ms.Method is not null && ms.Method.DeclaringType is not null && ms.Method.DeclaringType.Module != validModule) return; MethodSpecs[ms] = true; Push(ms.Method); Add(ms.Instantiation); Add(ms.CustomAttributes); } void Add(IEnumerable<PropertyDef> pds) { if (pds is null) return; foreach (var pd in pds) Add(pd); } void Add(PropertyDef pd) { if (pd is null || PropertyDefs.ContainsKey(pd)) return; if (pd.DeclaringType is not null && pd.DeclaringType.Module != validModule) return; PropertyDefs[pd] = true; Add(pd.Type); Add(pd.CustomAttributes); Add(pd.GetMethods); Add(pd.SetMethods); Add(pd.OtherMethods); Add(pd.DeclaringType); } void Add(IEnumerable<TypeDef> tds) { if (tds is null) return; foreach (var td in tds) Add(td); } void Add(TypeDef td) { if (td is null || TypeDefs.ContainsKey(td)) return; if (td.Module != validModule) return; TypeDefs[td] = true; Push(td.BaseType); Add(td.Fields); Add(td.Methods); Add(td.GenericParameters); Add(td.Interfaces); Add(td.DeclSecurities); Add(td.DeclaringType); Add(td.Events); Add(td.Properties); Add(td.NestedTypes); Add(td.CustomAttributes); } void Add(IEnumerable<InterfaceImpl> iis) { if (iis is null) return; foreach (var ii in iis) Add(ii); } void Add(InterfaceImpl ii) { if (ii is null) return; Push(ii.Interface); Add(ii.CustomAttributes); } void Add(TypeRef tr) { if (tr is null || TypeRefs.ContainsKey(tr)) return; if (tr.Module != validModule) return; TypeRefs[tr] = true; Push(tr.ResolutionScope); Add(tr.CustomAttributes); } void Add(IEnumerable<TypeSig> tss) { if (tss is null) return; foreach (var ts in tss) Add(ts); } void Add(TypeSig ts) { if (ts is null || TypeSigs.ContainsKey(ts)) return; if (ts.Module != validModule) return; TypeSigs[ts] = true; for (; ts is not null; ts = ts.Next) { switch (ts.ElementType) { case ElementType.Void: case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.String: case ElementType.ValueType: case ElementType.Class: case ElementType.TypedByRef: case ElementType.I: case ElementType.U: case ElementType.Object: var tdrs = (TypeDefOrRefSig)ts; Push(tdrs.TypeDefOrRef); break; case ElementType.FnPtr: var fps = (FnPtrSig)ts; Add(fps.Signature); break; case ElementType.GenericInst: var gis = (GenericInstSig)ts; Add(gis.GenericType); Add(gis.GenericArguments); break; case ElementType.CModReqd: case ElementType.CModOpt: var ms = (ModifierSig)ts; Push(ms.Modifier); break; case ElementType.End: case ElementType.Ptr: case ElementType.ByRef: case ElementType.Var: case ElementType.Array: case ElementType.ValueArray: case ElementType.R: case ElementType.SZArray: case ElementType.MVar: case ElementType.Internal: case ElementType.Module: case ElementType.Sentinel: case ElementType.Pinned: default: break; } } } void Add(TypeSpec ts) { if (ts is null || TypeSpecs.ContainsKey(ts)) return; if (ts.Module != validModule) return; TypeSpecs[ts] = true; Add(ts.TypeSig); Add(ts.CustomAttributes); } void Add(IEnumerable<ExportedType> ets) { if (ets is null) return; foreach (var et in ets) Add(et); } void Add(ExportedType et) { if (et is null || ExportedTypes.ContainsKey(et)) return; if (et.Module != validModule) return; ExportedTypes[et] = true; Add(et.CustomAttributes); Push(et.Implementation); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /// <remarks>A class that provides a basic DES engine.</remarks> public class DesEngine : IBlockCipher { internal const int BLOCK_SIZE = 8; private int[] workingKey; public virtual int[] GetWorkingKey() { return workingKey; } /** * initialise a DES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to DES init - " + parameters.GetType().ToString()); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } public virtual string AlgorithmName { get { return "DES"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("DES engine not initialised"); Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); DesFunc(workingKey, input, inOff, output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } /** * what follows is mainly taken from "Applied Cryptography", by * Bruce Schneier, however it also bears great resemblance to Richard * Outerbridge's D3DES... */ // private static readonly short[] Df_Key = // { // 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, // 0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10, // 0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67 // }; private static readonly short[] bytebit = { 128, 64, 32, 16, 8, 4, 2, 1 }; private static readonly int[] bigbyte = { 0x800000, 0x400000, 0x200000, 0x100000, 0x80000, 0x40000, 0x20000, 0x10000, 0x8000, 0x4000, 0x2000, 0x1000, 0x800, 0x400, 0x200, 0x100, 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 }; /* * Use the key schedule specified in the Standard (ANSI X3.92-1981). */ private static readonly byte[] pc1 = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 }; private static readonly byte[] totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 }; private static readonly byte[] pc2 = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 }; private static readonly uint[] SP1 = { 0x01010400, 0x00000000, 0x00010000, 0x01010404, 0x01010004, 0x00010404, 0x00000004, 0x00010000, 0x00000400, 0x01010400, 0x01010404, 0x00000400, 0x01000404, 0x01010004, 0x01000000, 0x00000004, 0x00000404, 0x01000400, 0x01000400, 0x00010400, 0x00010400, 0x01010000, 0x01010000, 0x01000404, 0x00010004, 0x01000004, 0x01000004, 0x00010004, 0x00000000, 0x00000404, 0x00010404, 0x01000000, 0x00010000, 0x01010404, 0x00000004, 0x01010000, 0x01010400, 0x01000000, 0x01000000, 0x00000400, 0x01010004, 0x00010000, 0x00010400, 0x01000004, 0x00000400, 0x00000004, 0x01000404, 0x00010404, 0x01010404, 0x00010004, 0x01010000, 0x01000404, 0x01000004, 0x00000404, 0x00010404, 0x01010400, 0x00000404, 0x01000400, 0x01000400, 0x00000000, 0x00010004, 0x00010400, 0x00000000, 0x01010004 }; private static readonly uint[] SP2 = { 0x80108020, 0x80008000, 0x00008000, 0x00108020, 0x00100000, 0x00000020, 0x80100020, 0x80008020, 0x80000020, 0x80108020, 0x80108000, 0x80000000, 0x80008000, 0x00100000, 0x00000020, 0x80100020, 0x00108000, 0x00100020, 0x80008020, 0x00000000, 0x80000000, 0x00008000, 0x00108020, 0x80100000, 0x00100020, 0x80000020, 0x00000000, 0x00108000, 0x00008020, 0x80108000, 0x80100000, 0x00008020, 0x00000000, 0x00108020, 0x80100020, 0x00100000, 0x80008020, 0x80100000, 0x80108000, 0x00008000, 0x80100000, 0x80008000, 0x00000020, 0x80108020, 0x00108020, 0x00000020, 0x00008000, 0x80000000, 0x00008020, 0x80108000, 0x00100000, 0x80000020, 0x00100020, 0x80008020, 0x80000020, 0x00100020, 0x00108000, 0x00000000, 0x80008000, 0x00008020, 0x80000000, 0x80100020, 0x80108020, 0x00108000 }; private static readonly uint[] SP3 = { 0x00000208, 0x08020200, 0x00000000, 0x08020008, 0x08000200, 0x00000000, 0x00020208, 0x08000200, 0x00020008, 0x08000008, 0x08000008, 0x00020000, 0x08020208, 0x00020008, 0x08020000, 0x00000208, 0x08000000, 0x00000008, 0x08020200, 0x00000200, 0x00020200, 0x08020000, 0x08020008, 0x00020208, 0x08000208, 0x00020200, 0x00020000, 0x08000208, 0x00000008, 0x08020208, 0x00000200, 0x08000000, 0x08020200, 0x08000000, 0x00020008, 0x00000208, 0x00020000, 0x08020200, 0x08000200, 0x00000000, 0x00000200, 0x00020008, 0x08020208, 0x08000200, 0x08000008, 0x00000200, 0x00000000, 0x08020008, 0x08000208, 0x00020000, 0x08000000, 0x08020208, 0x00000008, 0x00020208, 0x00020200, 0x08000008, 0x08020000, 0x08000208, 0x00000208, 0x08020000, 0x00020208, 0x00000008, 0x08020008, 0x00020200 }; private static readonly uint[] SP4 = { 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802080, 0x00800081, 0x00800001, 0x00002001, 0x00000000, 0x00802000, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00800080, 0x00800001, 0x00000001, 0x00002000, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002001, 0x00002080, 0x00800081, 0x00000001, 0x00002080, 0x00800080, 0x00002000, 0x00802080, 0x00802081, 0x00000081, 0x00800080, 0x00800001, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00000000, 0x00802000, 0x00002080, 0x00800080, 0x00800081, 0x00000001, 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802081, 0x00000081, 0x00000001, 0x00002000, 0x00800001, 0x00002001, 0x00802080, 0x00800081, 0x00002001, 0x00002080, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002000, 0x00802080 }; private static readonly uint[] SP5 = { 0x00000100, 0x02080100, 0x02080000, 0x42000100, 0x00080000, 0x00000100, 0x40000000, 0x02080000, 0x40080100, 0x00080000, 0x02000100, 0x40080100, 0x42000100, 0x42080000, 0x00080100, 0x40000000, 0x02000000, 0x40080000, 0x40080000, 0x00000000, 0x40000100, 0x42080100, 0x42080100, 0x02000100, 0x42080000, 0x40000100, 0x00000000, 0x42000000, 0x02080100, 0x02000000, 0x42000000, 0x00080100, 0x00080000, 0x42000100, 0x00000100, 0x02000000, 0x40000000, 0x02080000, 0x42000100, 0x40080100, 0x02000100, 0x40000000, 0x42080000, 0x02080100, 0x40080100, 0x00000100, 0x02000000, 0x42080000, 0x42080100, 0x00080100, 0x42000000, 0x42080100, 0x02080000, 0x00000000, 0x40080000, 0x42000000, 0x00080100, 0x02000100, 0x40000100, 0x00080000, 0x00000000, 0x40080000, 0x02080100, 0x40000100 }; private static readonly uint[] SP6 = { 0x20000010, 0x20400000, 0x00004000, 0x20404010, 0x20400000, 0x00000010, 0x20404010, 0x00400000, 0x20004000, 0x00404010, 0x00400000, 0x20000010, 0x00400010, 0x20004000, 0x20000000, 0x00004010, 0x00000000, 0x00400010, 0x20004010, 0x00004000, 0x00404000, 0x20004010, 0x00000010, 0x20400010, 0x20400010, 0x00000000, 0x00404010, 0x20404000, 0x00004010, 0x00404000, 0x20404000, 0x20000000, 0x20004000, 0x00000010, 0x20400010, 0x00404000, 0x20404010, 0x00400000, 0x00004010, 0x20000010, 0x00400000, 0x20004000, 0x20000000, 0x00004010, 0x20000010, 0x20404010, 0x00404000, 0x20400000, 0x00404010, 0x20404000, 0x00000000, 0x20400010, 0x00000010, 0x00004000, 0x20400000, 0x00404010, 0x00004000, 0x00400010, 0x20004010, 0x00000000, 0x20404000, 0x20000000, 0x00400010, 0x20004010 }; private static readonly uint[] SP7 = { 0x00200000, 0x04200002, 0x04000802, 0x00000000, 0x00000800, 0x04000802, 0x00200802, 0x04200800, 0x04200802, 0x00200000, 0x00000000, 0x04000002, 0x00000002, 0x04000000, 0x04200002, 0x00000802, 0x04000800, 0x00200802, 0x00200002, 0x04000800, 0x04000002, 0x04200000, 0x04200800, 0x00200002, 0x04200000, 0x00000800, 0x00000802, 0x04200802, 0x00200800, 0x00000002, 0x04000000, 0x00200800, 0x04000000, 0x00200800, 0x00200000, 0x04000802, 0x04000802, 0x04200002, 0x04200002, 0x00000002, 0x00200002, 0x04000000, 0x04000800, 0x00200000, 0x04200800, 0x00000802, 0x00200802, 0x04200800, 0x00000802, 0x04000002, 0x04200802, 0x04200000, 0x00200800, 0x00000000, 0x00000002, 0x04200802, 0x00000000, 0x00200802, 0x04200000, 0x00000800, 0x04000002, 0x04000800, 0x00000800, 0x00200002 }; private static readonly uint[] SP8 = { 0x10001040, 0x00001000, 0x00040000, 0x10041040, 0x10000000, 0x10001040, 0x00000040, 0x10000000, 0x00040040, 0x10040000, 0x10041040, 0x00041000, 0x10041000, 0x00041040, 0x00001000, 0x00000040, 0x10040000, 0x10000040, 0x10001000, 0x00001040, 0x00041000, 0x00040040, 0x10040040, 0x10041000, 0x00001040, 0x00000000, 0x00000000, 0x10040040, 0x10000040, 0x10001000, 0x00041040, 0x00040000, 0x00041040, 0x00040000, 0x10041000, 0x00001000, 0x00000040, 0x10040040, 0x00001000, 0x00041040, 0x10001000, 0x00000040, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x00040000, 0x10001040, 0x00000000, 0x10041040, 0x00040040, 0x10000040, 0x10040000, 0x10001000, 0x10001040, 0x00000000, 0x10041040, 0x00041000, 0x00041000, 0x00001040, 0x00001040, 0x00040040, 0x10000000, 0x10041000 }; /** * Generate an integer based working key based on our secret key * and what we processing we are planning to do. * * Acknowledgements for this routine go to James Gillogly and Phil Karn. * (whoever, and wherever they are!). */ protected static int[] GenerateWorkingKey( bool encrypting, byte[] key) { int[] newKey = new int[32]; bool[] pc1m = new bool[56]; bool[] pcr = new bool[56]; for (int j = 0; j < 56; j++ ) { int l = pc1[j]; pc1m[j] = ((key[(uint) l >> 3] & bytebit[l & 07]) != 0); } for (int i = 0; i < 16; i++) { int l, m, n; if (encrypting) { m = i << 1; } else { m = (15 - i) << 1; } n = m + 1; newKey[m] = newKey[n] = 0; for (int j = 0; j < 28; j++) { l = j + totrot[i]; if ( l < 28 ) { pcr[j] = pc1m[l]; } else { pcr[j] = pc1m[l - 28]; } } for (int j = 28; j < 56; j++) { l = j + totrot[i]; if (l < 56 ) { pcr[j] = pc1m[l]; } else { pcr[j] = pc1m[l - 28]; } } for (int j = 0; j < 24; j++) { if (pcr[pc2[j]]) { newKey[m] |= bigbyte[j]; } if (pcr[pc2[j + 24]]) { newKey[n] |= bigbyte[j]; } } } // // store the processed key // for (int i = 0; i != 32; i += 2) { int i1, i2; i1 = newKey[i]; i2 = newKey[i + 1]; newKey[i] = (int) ( (uint) ((i1 & 0x00fc0000) << 6) | (uint) ((i1 & 0x00000fc0) << 10) | ((uint) (i2 & 0x00fc0000) >> 10) | ((uint) (i2 & 0x00000fc0) >> 6)); newKey[i + 1] = (int) ( (uint) ((i1 & 0x0003f000) << 12) | (uint) ((i1 & 0x0000003f) << 16) | ((uint) (i2 & 0x0003f000) >> 4) | (uint) (i2 & 0x0000003f)); } return newKey; } /** * the DES engine. */ internal static void DesFunc( int[] wKey, byte[] input, int inOff, byte[] outBytes, int outOff) { uint left = Pack.BE_To_UInt32(input, inOff); uint right = Pack.BE_To_UInt32(input, inOff + 4); uint work; work = ((left >> 4) ^ right) & 0x0f0f0f0f; right ^= work; left ^= (work << 4); work = ((left >> 16) ^ right) & 0x0000ffff; right ^= work; left ^= (work << 16); work = ((right >> 2) ^ left) & 0x33333333; left ^= work; right ^= (work << 2); work = ((right >> 8) ^ left) & 0x00ff00ff; left ^= work; right ^= (work << 8); right = (right << 1) | (right >> 31); work = (left ^ right) & 0xaaaaaaaa; left ^= work; right ^= work; left = (left << 1) | (left >> 31); for (int round = 0; round < 8; round++) { uint fval; work = (right << 28) | (right >> 4); work ^= (uint)wKey[round * 4 + 0]; fval = SP7[work & 0x3f]; fval |= SP5[(work >> 8) & 0x3f]; fval |= SP3[(work >> 16) & 0x3f]; fval |= SP1[(work >> 24) & 0x3f]; work = right ^ (uint)wKey[round * 4 + 1]; fval |= SP8[ work & 0x3f]; fval |= SP6[(work >> 8) & 0x3f]; fval |= SP4[(work >> 16) & 0x3f]; fval |= SP2[(work >> 24) & 0x3f]; left ^= fval; work = (left << 28) | (left >> 4); work ^= (uint)wKey[round * 4 + 2]; fval = SP7[ work & 0x3f]; fval |= SP5[(work >> 8) & 0x3f]; fval |= SP3[(work >> 16) & 0x3f]; fval |= SP1[(work >> 24) & 0x3f]; work = left ^ (uint)wKey[round * 4 + 3]; fval |= SP8[ work & 0x3f]; fval |= SP6[(work >> 8) & 0x3f]; fval |= SP4[(work >> 16) & 0x3f]; fval |= SP2[(work >> 24) & 0x3f]; right ^= fval; } right = (right << 31) | (right >> 1); work = (left ^ right) & 0xaaaaaaaa; left ^= work; right ^= work; left = (left << 31) | (left >> 1); work = ((left >> 8) ^ right) & 0x00ff00ff; right ^= work; left ^= (work << 8); work = ((left >> 2) ^ right) & 0x33333333; right ^= work; left ^= (work << 2); work = ((right >> 16) ^ left) & 0x0000ffff; left ^= work; right ^= (work << 16); work = ((right >> 4) ^ left) & 0x0f0f0f0f; left ^= work; right ^= (work << 4); Pack.UInt32_To_BE(right, outBytes, outOff); Pack.UInt32_To_BE(left, outBytes, outOff + 4); } } } #endif
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Iso7816; using SDKTemplate; using System; using System.Collections.Generic; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Devices.SmartCards; using Windows.Security.Cryptography; using Windows.Security.Cryptography.DataProtection; using Windows.Storage.Streams; using Windows.UI.Xaml.Controls; using static NfcSample.NfcUtils; namespace NfcSample { public sealed partial class SetCardDataScenario : Page { private static readonly byte[] AID_PPSE = { // File name "2PAY.SYS.DDF01" (14 bytes) (byte)'2', (byte)'P', (byte)'A', (byte)'Y', (byte)'.', (byte)'S', (byte)'Y', (byte)'S', (byte)'.', (byte)'D', (byte)'D', (byte)'F', (byte)'0', (byte)'1' }; private static readonly byte[] AID_V = { 0xA0, 0x00, 0x00, 0x00, 0x03, 0x10, 0x10 }; private static readonly byte[] AID_MC = { 0xA0, 0x00, 0x00, 0x00, 0x04, 0x10, 0x10 }; private static readonly byte[] AID_NONPAYMENT = { 0x12, 0x34, 0x56, 0x78, 0x90 }; public SetCardDataScenario() { this.InitializeComponent(); } public async Task<IBuffer> ProtectDataAsync( byte[] data, String strDescriptor) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor); // Encrypt the message. return await Provider.ProtectAsync(CryptographicBuffer.CreateFromByteArray(data)); } private byte[] BuildReadRecordResponseV(string track2, string cardholderName, string track1Discretionary) { if (track2.Length % 2 != 0) { track2 += "F"; } return new TlvEntry(0x70, new TlvEntry[] { new TlvEntry(0x57, NfcUtils.HexStringToBytes(track2)), new TlvEntry(0x5F20, cardholderName), new TlvEntry(0x9F1F, track1Discretionary), }).GetData(0x9000); } private byte[] BuildReadRecordResponseMC(string pan, string exp, string serviceCode, string cardholderName, string track1Discretionary, string track2Discretionary) { var track1 = "B" + pan + "^" + cardholderName + "^" + exp + serviceCode + track1Discretionary; var track2 = pan + "D" + exp + serviceCode + track2Discretionary; if (track2.Length % 2 != 0) { track2 += "F"; } return new TlvEntry(0x70, new TlvEntry[] { // Magstripe version new TlvEntry(0x9F6C, new byte[] { 0x00, 0x01 }), // Track 1 data new TlvEntry(0x56, System.Text.Encoding.UTF8.GetBytes(track1)), // Track 1 bit map for CVC3 new TlvEntry(0x9F62, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E }), // Track 1 bit map for UN and ATC new TlvEntry(0x9F63, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }), // Track 1 number of ATC digits new TlvEntry(0x9F64, new byte[] { 0x00 }), // Track 2 data new TlvEntry(0x9F6B, NfcUtils.HexStringToBytes(track2)), // Track 2 bit map for CVC3 new TlvEntry(0x9F65, new byte[] { 0x00, 0x0E }), // Track 2 bit map for UN and ATC new TlvEntry(0x9F66, new byte[] { 0x00, 0x00 }), // Track 2 number of ATC digits new TlvEntry(0x9F67, new byte[] { 0x00 }), // Magstripe CVM list new TlvEntry(0x9F68, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5E, 0x03, 0x42, 0x03, 0x1F, 0x03 }), }).GetData(0x9000); } private void btnCancel_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { this.Frame.GoBack(); } private async void btnAddCard_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Clear the messages MainPage.Current.NotifyUser(String.Empty, NotifyType.StatusMessage, true); // Register the AID/applet IDs that this application will handle for our particular card(s) SmartCardAppletIdGroupRegistration reg; if (optUICC.IsChecked ?? false) { reg = await NfcUtils.RegisterAidGroup( txtDisplayName.Text, new[] { AID_PPSE.AsBuffer(), AID_V.AsBuffer(), AID_MC.AsBuffer() }, SmartCardEmulationCategory.Payment, SmartCardEmulationType.Uicc, (chkAutomaticEnablement.IsChecked ?? false)); } else if (optNonPayment.IsChecked ?? false) { reg = await NfcUtils.RegisterAidGroup( txtDisplayName.Text, new[] { AID_NONPAYMENT.AsBuffer() }, SmartCardEmulationCategory.Other, SmartCardEmulationType.Host, (chkAutomaticEnablement.IsChecked ?? false)); var rule1 = new SmartCardAutomaticResponseApdu(NfcUtils.HexStringToBytes("0012AABB").AsBuffer(), NfcUtils.HexStringToBytes("AABBCCDDEE9000").AsBuffer()); rule1.AppletId = AID_NONPAYMENT.AsBuffer(); await reg.SetAutomaticResponseApdusAsync(new List<SmartCardAutomaticResponseApdu>() { rule1 }); } else { var aid = (optV.IsChecked ?? false) ? AID_V : AID_MC; var aidBuffer = aid.AsBuffer(); reg = await NfcUtils.RegisterAidGroup( txtDisplayName.Text, new[] { AID_PPSE.AsBuffer(), aidBuffer }, SmartCardEmulationCategory.Payment, SmartCardEmulationType.Host, (chkAutomaticEnablement.IsChecked ?? false)); var rules = new List<SmartCardAutomaticResponseApdu>(); // Construct SELECT PPSE response and set as auto responder rules.Add(new SmartCardAutomaticResponseApdu( new SelectCommand(AID_PPSE, 0x00).GetBuffer(), new TlvEntry(0x6F, new TlvEntry[] { new TlvEntry(0x84, "2PAY.SYS.DDF01"), new TlvEntry(0xA5, new TlvEntry[] { new TlvEntry(0xBF0C, new TlvEntry(0x61, new TlvEntry[] { new TlvEntry(0x4F, aidBuffer), new TlvEntry(0x87, new byte[] { 0x01 }) })) }) }).GetData(0x9000).AsBuffer())); if (optV.IsChecked ?? false) { rules.Add(new SmartCardAutomaticResponseApdu( new SelectCommand(aid, 0x00).GetBuffer(), new TlvEntry(0x6F, new TlvEntry[] { new TlvEntry(0x84, aidBuffer), new TlvEntry(0xA5, new TlvEntry[] { new TlvEntry(0x50, "CREDIT CARD"), new TlvEntry(0x9F38, new byte[] { 0x9F, 0x66, 0x02 }) }) }).GetData(0x9000).AsBuffer())); var ruleGpo = new SmartCardAutomaticResponseApdu( NfcUtils.HexStringToBytes("80A80000").AsBuffer(), new TlvEntry(0x80, new byte[] { 0x00, 0x80, 0x08, 0x01, 0x01, 0x00 }).GetData(0x9000).AsBuffer()); ruleGpo.AppletId = aidBuffer; ruleGpo.ShouldMatchLength = false; rules.Add(ruleGpo); } else { rules.Add(new SmartCardAutomaticResponseApdu( new SelectCommand(aid, 0x00).GetBuffer(), new TlvEntry(0x6F, new TlvEntry[] { new TlvEntry(0x84, aidBuffer), new TlvEntry(0xA5, new TlvEntry[] { new TlvEntry(0x50, "CREDIT CARD") }) }).GetData(0x9000).AsBuffer())); var ruleGpo = new SmartCardAutomaticResponseApdu( NfcUtils.HexStringToBytes("80A80000").AsBuffer(), new TlvEntry(0x77, new TlvEntry[] { new TlvEntry(0x82, new byte[] { 0x00, 0x00 }), new TlvEntry(0x94, new byte[] { 0x08, 0x01, 0x01, 0x00 }), new TlvEntry(0xD7, new byte[] { 0x00, 0x00, 0x80 }) }).GetData(0x9000).AsBuffer()); ruleGpo.AppletId = aidBuffer; ruleGpo.ShouldMatchLength = false; rules.Add(ruleGpo); } byte[] record; if (optV.IsChecked ?? false) { var track2 = txtPAN.Text + "D" + txtExpiryYear.Text + txtExpiryMonth.Text + txtServiceCode.Text + txtTrack2Discretionary.Text; record = BuildReadRecordResponseV(track2, txtCardholderName.Text, txtTrack1Discretionary.Text); } else { record = BuildReadRecordResponseMC(txtPAN.Text, txtExpiryYear.Text + txtExpiryMonth.Text, txtServiceCode.Text, txtCardholderName.Text, txtTrack1Discretionary.Text, txtTrack2Discretionary.Text); } var encryptedRecord = await ProtectDataAsync(record, "LOCAL=user"); var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("ReadRecordResponse-" + reg.Id.ToString("B") + ".dat", Windows.Storage.CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteBufferAsync(file, encryptedRecord); await reg.SetAutomaticResponseApdusAsync(rules); } LogMessage("Card data saved", NotifyType.StatusMessage); this.Frame.GoBack(); } private void optCardTypeGroup_CheckedUnchecked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { if (stackPayment != null) { if (optNonPayment != null && (optNonPayment.IsChecked ?? false)) { txtDisplayName.Text = "Sample Other/Non-Payment Card"; stackPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } else if (optUICC != null && (optUICC.IsChecked ?? false)) { txtDisplayName.Text = "Sample UICC Payment Card"; stackPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } else { txtDisplayName.Text = "Sample Payment Card"; stackPayment.Visibility = Windows.UI.Xaml.Visibility.Visible; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order1.order1 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order1.order1; // <Area>variance</Area> // <Title> Order of Basic covariance on interfaces</Title> // <Description> basic coavariance on interfaces with many parameters. Order does not matter</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<S, out T, U, V> { T Boo(); } public class Variance<S, T, U, V> : iVariance<S, T, U, V> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v11 = new Variance<int, Tiger, string, long>(); iVariance<int, Animal, string, long> v12 = v11; var x1 = v12.Boo(); Variance<int, Tiger, string, long> v21 = new Variance<int, Tiger, string, long>(); dynamic v22 = (iVariance<int, Animal, string, long>)v21; var x2 = v22.Boo(); dynamic v31 = new Variance<int, Tiger, string, long>(); dynamic v32 = (iVariance<int, Animal, string, long>)v31; var x3 = v32.Boo(); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order2.order2 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order2.order2; // <Area>variance</Area> // <Title> Order of Basic covariance on interfaces</Title> // <Description> basic coavariance on interfaces with many parameters. // A second parameter is also used in a covariant way but is not covariant itself. this should fail //</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<S, out T, U, V> { T Boo(); } public class Variance<S, T, U, V> : iVariance<S, T, U, V> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0, count = 0; dynamic v11 = new Variance<int, Tiger, string, Tiger>(); try { result++; iVariance<int, Animal, string, Animal> v12 = v11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<int,Tiger,string,Tiger>", "iVariance<int,Animal,string,Animal>"); if (ret) { result--; } } Variance<int, Tiger, string, Tiger> v21 = new Variance<int, Tiger, string, Tiger>(); try { result++; dynamic v22 = (iVariance<int, Animal, string, Animal>)v21; } catch (System.InvalidCastException) { result--; } dynamic v31 = new Variance<int, Tiger, string, Tiger>(); try { result++; dynamic v32 = (iVariance<int, Animal, string, Animal>)v31; } catch (System.InvalidCastException) { result--; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order3.order3 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order3.order3; // <Area>variance</Area> // <Title> Order of Basic covariance on delegates</Title> // <Description> basic coavariance on delegates with many parameters. Order does not matter</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate T Foo<S, out T, U, V>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f11 = (Foo<int, Tiger, string, long>)(() => { return new Tiger(); } ); Foo<int, Animal, string, long> f12 = f11; Tiger t1 = f11(); Foo<int, Tiger, string, long> f21 = () => { return new Tiger(); } ; dynamic f22 = (Foo<int, Animal, string, long>)f21; Tiger t2 = f22(); dynamic f31 = (Foo<int, Tiger, string, long>)(() => { return new Tiger(); } ); dynamic f32 = (Foo<int, Animal, string, long>)f31; Tiger t3 = f31(); return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order4.order4 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order4.order4; // <Area>variance</Area> // <Title> Order of Basic covariance on delegates</Title> // <Description> basic coavariance on delegates with many parameters. only one type param is variant</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate T Foo<S, out T, U, V>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0; bool ret = true; dynamic f11 = (Foo<int, Tiger, string, Tiger>)(() => { return new Tiger(); } ); try { result++; Foo<int, Animal, string, Animal> f12 = f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { result--; ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>"); if (!ret) result++; } Foo<int, Tiger, string, Tiger> f21 = () => { return new Tiger(); } ; try { result++; dynamic f22 = (Foo<int, Animal, string, Animal>)f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { result--; ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>"); if (!ret) result++; } dynamic f31 = (Foo<int, Tiger, string, Tiger>)(() => { return new Tiger(); } ); try { result++; dynamic f32 = (Foo<int, Animal, string, Animal>)f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { result--; ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>"); if (!ret) result++; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.partial01.partial01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.partial01.partial01; // <Area>variance</Area> // <Title> Basic covariance on delegate types </Title> // <Description> Having a covariant delegate and assigning it to a bigger type in a partial public class </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public partial class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Tiger> f1 = () => { return new Tiger(); } ; Foo<Animal> f2 = f1; Animal t = f2(); return 0; } } public partial class C { private delegate T Foo<out T>(); } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype01.valtype01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype01.valtype01; // <Area>variance</Area> // <Title> Value types</Title> // <Description> basic coavariance on interfaces with value types </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> { public T Boo() { return default(T); } } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int count = 0, result = 0; dynamic v11 = new Variance<uint>(); try { result++; iVariance<int> v12 = v11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<uint>", "iVariance<int>"); if (ret) { result--; } } Variance<uint> v21 = new Variance<uint>(); try { result++; dynamic v22 = (iVariance<int>)v21; } catch (System.InvalidCastException) { result--; } dynamic v31 = new Variance<uint>(); try { result++; dynamic v32 = (iVariance<int>)v31; } catch (System.InvalidCastException) { result--; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype02.valtype02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype02.valtype02; // <Area>variance</Area> // <Title> Value types</Title> // <Description> basic coavariance on dynamic with value types </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int count = 0, result = 0; bool ret = true; dynamic f11 = (Foo<uint>)(() => { return 0; } ); try { count++; result++; Foo<int> f12 = f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<int>"); if (ret) { result--; } } //Foo<uint> f21 = () => { return 0; }; //try //{ // result++; // dynamic f22 = (Foo<int>)f21; //} //catch (System.InvalidCastException) //{ // result--; // System.Console.WriteLine("Scenario {0} passed. ", ++count); //} dynamic f31 = (Foo<uint>)(() => { return 0; } ); try { count++; result++; dynamic f32 = (Foo<int>)f31; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<int>"); if (ret) { result--; } } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype03.valtype03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype03.valtype03; // <Area>variance</Area> // <Title> Value types</Title> // <Description> basic coavariance on interfaces with nullable value types </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> { public T Boo() { return default(T); } } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int result = 0; dynamic v11 = new Variance<uint>(); try { result++; iVariance<uint?> v12 = v11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<uint>", "iVariance<uint?>"); if (ret) { result--; } } Variance<uint> v21 = new Variance<uint>(); try { result++; dynamic v22 = (iVariance<uint?>)v21; } catch (System.InvalidCastException) { result--; } dynamic v31 = new Variance<uint>(); try { result++; dynamic v32 = (iVariance<uint?>)v31; } catch (System.InvalidCastException) { result--; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype04.valtype04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype04.valtype04; // <Area>variance</Area> // <Title> Value types</Title> // <Description> basic coavariance on delegate with null value types </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int count = 0, result = 0; bool ret = true; dynamic f11 = (Foo<uint>)(() => { return 0; } ); try { count++; result++; Foo<uint?> f12 = f11; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<uint?>"); if (ret) { result--; } } //Foo<uint> f21 = () => { return 0; }; //try //{ // result++; // dynamic f22 = (Foo<uint?>)f21; //} //catch (System.InvalidCastException) //{ // result--; // System.Console.WriteLine("Scenario {0} passed. ", ++count); //} dynamic f31 = (Foo<uint>)(() => { return 0; } ); try { count++; result++; dynamic f32 = (Foo<uint?>)f31; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<uint?>"); if (ret) { result--; } } return result; } } //</Code> }
using System; using System.Collections; using System.Data.SqlClient; using System.IO; using System.Web.UI.WebControls; using Rainbow.Framework; using Rainbow.Framework.Content.Data; using Rainbow.Framework.Content.Security; using Rainbow.Framework.Data; using Rainbow.Framework.DataTypes; using Rainbow.Framework.Helpers; using Rainbow.Framework.Web.UI.WebControls; using HyperLink=Rainbow.Framework.Web.UI.WebControls.HyperLink; using ImageButton=Rainbow.Framework.Web.UI.WebControls.ImageButton; using Label=Rainbow.Framework.Web.UI.WebControls.Label; namespace Rainbow.Content.Web.Modules { /// <summary> /// The discussion module allwos for simple threaded discussion /// with full HTML support in the discussion. /// </summary> public partial class Discussion : PortalModuleControl { /// <summary> /// details of thread list /// </summary> protected DataList DetailList; /// <summary> /// Searchable module /// </summary> /// <value></value> public override bool Searchable { get { return true; } } /// <summary> /// On the first invocation of Page_Load, the data is bound using BindList(); /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { /*if (Page.IsPostBack == false) { BindList(); }*/ BindList(); } /// <summary> /// The BindList method obtains the list of top-level messages /// from the Discussion table and then databinds them against /// the "TopLevelList" asp:datalist server control. It uses /// the Rainbow.DiscussionDB() data component to encapsulate /// all data access functionality. /// </summary> private void BindList() { // Obtain a list of discussion messages for the module and bind to datalist DiscussionDB discuss = new DiscussionDB(); TopLevelList.DataSource = discuss.GetTopLevelMessages(ModuleID); TopLevelList.DataBind(); } /// <summary> /// The GetThreadMessages method is used to obtain the list /// of messages contained within a sub-topic of the /// a top-level discussion message thread. This method is /// used to populate the "DetailList" asp:datalist server control /// in the SelectedItemTemplate of "TopLevelList". /// </summary> /// <returns>returns a SqlDataReader object</returns> protected SqlDataReader GetThreadMessages() { DiscussionDB discuss = new DiscussionDB(); int itemID = Int32.Parse(TopLevelList.DataKeys[TopLevelList.SelectedIndex].ToString()); SqlDataReader dr = discuss.GetThreadMessages(itemID, 'N'); return dr; } /// <summary> /// The TopLevelList_Select server event handler is used to /// expand/collapse a selected discussion topic and delte individual items /// </summary> /// <param name="Sender">The source of the event.</param> /// <param name="e">DataListCommandEventAargs e</param> public void TopLevelListOrDetailList_Select(object Sender, DataListCommandEventArgs e) { // Determine the command of the button string command = ((CommandEventArgs) (e)).CommandName; // Update asp:datalist selection index depending upon the type of command // and then rebind the asp:datalist with content switch (command) { case "CollapseThread": { TopLevelList.SelectedIndex = -1; // nothing is selected break; } case "ExpandThread": { TopLevelList.SelectedIndex = e.Item.ItemIndex; DiscussionDB discuss = new DiscussionDB(); int ItemID = Int32.Parse(e.CommandArgument.ToString()); discuss.IncrementViewCount(ItemID); break; } case "ShowThreadNewWindow": // open up the entire thread in a new window { TopLevelList.SelectedIndex = e.Item.ItemIndex; DiscussionDB discuss = new DiscussionDB(); int ItemID = Int32.Parse(e.CommandArgument.ToString()); discuss.IncrementViewCount(ItemID); Response.Redirect(FormatUrlShowThread(ItemID)); break; } /* case "SelectTitle": TopLevelList.SelectedIndex = e.Item.ItemIndex; Response.Redirect(FormatUrlShowThread((int)DataBinder.Eval(Container.DataItem, "ItemID"))); break; */ case "delete": // the "delete" command can come from the TopLevelList or the DetailList { DiscussionDB discuss = new DiscussionDB(); int ItemID = Int32.Parse(e.CommandArgument.ToString()); discuss.DeleteChildren(ItemID); // DetailList.DataBind(); // synchronize the control and database after deletion break; } default: break; } BindList(); } /// <summary> /// set up a client-side javascript dialog to confirm deletions /// the 'confirm' dialog is called when onClick is triggered /// if the dialog returns false the server never gets the delete request /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataListItemEventArgs"/> instance containing the event data.</param> protected void OnItemDataBound(object sender, DataListItemEventArgs e) { // 13/7/2004 Added Localization Mario Endara mario@softworks.com.uy if (e.Item.FindControl("deleteBtn") != null) { ((ImageButton) e.Item.FindControl("deleteBtn")).Attributes.Add("onClick", "return confirm('" + General.GetString( "DISCUSSION_DELETE_RESPONSE", "Are you sure you want to delete the selected response message and ALL of its children ?") + "');"); ((ImageButton) e.Item.FindControl("deleteBtn")).Attributes.Add("title", General.GetString("DELETE", "Delete this thread")); } if (e.Item.FindControl("deleteBtnExpanded") != null) { ((ImageButton) e.Item.FindControl("deleteBtnExpanded")).Attributes.Add("onClick", "return confirm('" + General.GetString( "DISCUSSION_DELETE_RESPONSE", "Are you sure you want to delete the selected response message and ALL of its children ?") + "');"); ((ImageButton) e.Item.FindControl("deleteBtnExpanded")).Attributes.Add("title", General.GetString("DELETE", "Delete this thread")); } // 15/7/2004 added localization by Mario Endara mario@softworks.com.uy if (e.Item.FindControl("Label4") != null) { if (((Label) e.Item.FindControl("Label4")).Text == "unknown") { ((Label) e.Item.FindControl("Label4")).Text = General.GetString("UNKNOWN", "unknown"); } } if (e.Item.FindControl("Label10") != null) { if (((Label) e.Item.FindControl("Label10")).Text == "unknown") { ((Label) e.Item.FindControl("Label10")).Text = General.GetString("UNKNOWN", "unknown"); } } if (e.Item.FindControl("Label6") != null) { ((Label) e.Item.FindControl("Label6")).ToolTip = General.GetString("DISCUSSION_REPLYS", "Number of replys to this topic"); } if (e.Item.FindControl("Label5") != null) { ((Label) e.Item.FindControl("Label5")).ToolTip = General.GetString("DISCUSSION_VIEWED", "Number of times this topic has been viewed"); } if (e.Item.FindControl("Label1") != null) { ((Label) e.Item.FindControl("Label1")).ToolTip = General.GetString("DISCUSSION_REPLYS", "Number of replys to this topic"); } if (e.Item.FindControl("Label2") != null) { ((Label) e.Item.FindControl("Label2")).ToolTip = General.GetString("DISCUSSION_VIEWED", "Number of times this topic has been viewed"); } if (e.Item.FindControl("btnCollapse") != null) { ((ImageButton) e.Item.FindControl("btnCollapse")).ToolTip = General.GetString("DISCUSSION_MSGCOLLAPSE", "Collapse the thread of this topic"); } if (e.Item.FindControl("btnSelect") != null) { ((ImageButton) e.Item.FindControl("btnSelect")).ToolTip = General.GetString("DISCUSSION_MSGEXPAND", "Expand the thread of this topic inside this browser page"); } if (e.Item.FindControl("btnNewWindow") != null) { ((ImageButton) e.Item.FindControl("btnNewWindow")).ToolTip = General.GetString("DISCUSSION_MSGSELECT", "Open the thread of this topic in a new browser page"); } // jminond - add tooltip support for firefox // Relpy if (e.Item.FindControl("HyperLink2") != null) { ((HyperLink) e.Item.FindControl("HyperLink2")).Attributes.Add("title", General.GetString("DS_REPLYTHISMSG", "Reply to this message")); } if (e.Item.FindControl("HyperLink1") != null) { ((HyperLink) e.Item.FindControl("HyperLink1")).ToolTip = General.GetString("EDIT", "Edit this message"); } // End FireFox Tooltip Support } /// <summary> /// GetReplyImage /// </summary> /// <returns></returns> protected string GetReplyImage() { if (DiscussionPermissions.HasAddPermissions(ModuleID) == true) return getLocalImage("reply.png"); else return getLocalImage("1x1.gif"); } /// <summary> /// GetEditImage /// </summary> /// <param name="itemUserEmail">The item user email.</param> /// <returns></returns> protected string GetEditImage(string itemUserEmail) { if (DiscussionPermissions.HasEditPermissions(ModuleID, itemUserEmail)) return getLocalImage("edit.png"); else return getLocalImage("1x1.gif"); } /// <summary> /// GetDeleteImage /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="itemUserEmail">The item user email.</param> /// <returns></returns> protected string GetDeleteImage(int itemID, string itemUserEmail) { if (DiscussionPermissions.HasDeletePermissions(ModuleID, itemID, itemUserEmail) == true) return getLocalImage("delete.png"); else return getLocalImage("1x1.gif"); } /// <summary> /// The FormatUrl method is a helper messages called by a /// databinding statement within the &lt;asp:DataList&gt; server /// control template. It is defined as a helper method here /// (as opposed to inline within the template) to improve /// code organization and avoid embedding logic within the /// content template. /// </summary> /// <param name="itemID">ID of the currently selected topic</param> /// <param name="mode">The mode.</param> /// <returns> /// Returns a properly formatted URL to call the DiscussionEdit page /// </returns> protected string FormatUrlEditItem(int itemID, string mode) { return (HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Discussion/DiscussionEdit.aspx", "ItemID=" + itemID + "&Mode=" + mode + "&mID=" + ModuleID + "&edit=1")); } /// <summary> /// FormatUrlShowThread /// </summary> /// <param name="itemID">The item ID.</param> /// <returns></returns> protected string FormatUrlShowThread(int itemID) { return (HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Discussion/DiscussionViewThread.aspx", "ItemID=" + itemID + "&mID=" + ModuleID)); } /// <summary> /// The NodeImage method is a helper method called by a /// databinding statement within the &lt;asp:datalist&gt; server /// control template. It controls whether or not an item /// in the list should be rendered as an expandable topic /// or just as a single node within the list. /// </summary> /// <param name="count">Number of replys to the selected topic</param> /// <returns></returns> protected string NodeImage(int count) { return getLocalImage("Thread.png"); } /// <summary> /// Gets the local image. /// </summary> /// <param name="img">The img.</param> /// <returns></returns> protected string getLocalImage(string img) { return CurrentTheme.GetModuleImageSRC(img); } /// <summary> /// Module GUID /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{2D86166C-4BDC-4A6F-A028-D17C2BB177C8}"); } } /// <summary> /// Searchable module implementation /// </summary> /// <param name="portalID">The portal ID</param> /// <param name="userID">ID of the user is searching</param> /// <param name="searchString">The text to search</param> /// <param name="searchField">The fields where perfoming the search</param> /// <returns> /// The SELECT sql to perform a search on the current module /// </returns> public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField) { SearchDefinition s = new SearchDefinition("rb_Discussion", "Title", "Body", "CreatedByUser", "CreatedDate", searchField); return s.SearchSqlSelect(portalID, userID, searchString); } /// <summary> /// Public constructor. Sets base settings for module. /// </summary> public Discussion() { // Jminond - added editor support HtmlEditorDataType.HtmlEditorSettings(_baseSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS); /* * SettingItem setSortField = new SettingItem(new ListDataType("CreatedDate;Title")); setSortField.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; setSortField.Required = true; setSortField.Value = "DueDate"; this._baseSettings.Add("DISCUSSION_SORT_FIELD", setSortField); */ } #region Web Form Designer generated code /// <summary> /// Raises Init event /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { this.TopLevelList.ItemCommand += new DataListCommandEventHandler(this.TopLevelListOrDetailList_Select); // this.DetailList.ItemCommand += new System.Web.UI.WebControls.DataListCommandEventHandler(this.TopLevelListOrDetailList_Select); this.Load += new EventHandler(this.Page_Load); if (!this.Page.IsCssFileRegistered("Mod_Discussion")) this.Page.RegisterCssFile("Mod_Discussion"); this.AddText = "DS_NEWTHREAD"; this.AddUrl = "~/DesktopModules/CommunityModules/Discussion/DiscussionEdit.aspx"; base.OnInit(e); } #endregion # region Install / Uninstall Implementation /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Install(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Uninstall(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } # endregion } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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 NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Menu; using NakedFramework.Architecture.Spec; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Error; using static NakedFramework.Core.Util.ToStringHelpers; namespace NakedFramework.Core.Spec; public abstract class TypeSpec : ITypeSpec { // cached values private string description; private bool? hasNoIdentity; private bool? hasSubclasses; private ITypeSpec[] interfaces; private bool? isAbstract; private bool? isAggregated; private bool? isASet; private bool? isCollection; private bool? isInterface; private bool? isParseable; private bool? isQueryable; private bool? isStatic; private bool? isViewModel; private bool? isVoid; private IActionSpec[] objectActions; private PersistableType? persistable; private string pluralName; private string shortName; private string singularName; private ITypeSpec[] subclasses; private ITypeSpec superclass; private string untitledName; protected TypeSpec(SpecFactory memberFactory, ITypeSpecImmutable innerSpec, INakedFramework framework) { MemberFactory = memberFactory ?? throw new InitialisationException($"{nameof(memberFactory)} is null"); InnerSpec = innerSpec ?? throw new InitialisationException($"{nameof(innerSpec)} is null"); Framework = framework; } private Type Type => InnerSpec.Type; protected IActionSpec[] ObjectActions => objectActions ??= MemberFactory.CreateActionSpecs(InnerSpec.OrderedObjectActions); protected SpecFactory MemberFactory { get; } private string TypeNameFor => IsCollection ? "Collection" : "Object"; private string DefaultTitle() => InnerSpec is IServiceSpecImmutable ? SingularName : UntitledName; protected abstract PersistableType GetPersistable(); public override string ToString() => $"{NameAndHashCode(this)} [class={FullName},type={TypeNameFor},persistable={Persistable},superclass={SuperClass(InnerSpec)}]"; protected bool Equals(TypeSpec other) => Equals(InnerSpec, other.InnerSpec); public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((TypeSpec)obj); } public override int GetHashCode() => InnerSpec != null ? InnerSpec.GetHashCode() : 0; #region ITypeSpec Members public ITypeSpecImmutable InnerSpec { get; } public INakedFramework Framework { get; } public virtual string FullName => InnerSpec.FullName; public virtual object DefaultValue => null; public Type[] FacetTypes => InnerSpec.FacetTypes; public IIdentifier Identifier => InnerSpec.Identifier; public bool ContainsFacet(Type facetType) => InnerSpec.ContainsFacet(facetType); public bool ContainsFacet<T>() where T : IFacet => InnerSpec.ContainsFacet<T>(); public IFacet GetFacet(Type type) => InnerSpec.GetFacet(type); public T GetFacet<T>() where T : IFacet => InnerSpec.GetFacet<T>(); public IEnumerable<IFacet> GetFacets() => InnerSpec.GetFacets(); public virtual bool IsParseable { get { isParseable ??= InnerSpec.ContainsFacet(typeof(IParseableFacet)); return isParseable.Value; } } public virtual bool IsAggregated { get { isAggregated ??= InnerSpec.ContainsFacet(typeof(IAggregatedFacet)); return isAggregated.Value; } } public virtual bool IsCollection { get { isCollection ??= InnerSpec.ContainsFacet(typeof(ICollectionFacet)); return isCollection.Value; } } public virtual bool IsViewModel { get { isViewModel ??= InnerSpec.ContainsFacet(typeof(IViewModelFacet)); return isViewModel.Value; } } public virtual bool IsObject => !IsCollection; public virtual ITypeSpec Superclass { get { if (superclass is null && InnerSpec.Superclass is not null) { superclass = Framework.MetamodelManager.GetSpecification(InnerSpec.Superclass); } return superclass; } } public abstract IActionSpec[] GetActions(); public IMenuImmutable Menu => InnerSpec.ObjectMenu; public bool IsASet { get { if (!isASet.HasValue) { var collectionFacet = InnerSpec.GetFacet<ICollectionFacet>(); isASet = collectionFacet is { IsASet: true }; } return isASet.Value; } } public bool HasSubclasses { get { hasSubclasses ??= InnerSpec.Subclasses.Any(); return hasSubclasses.Value; } } public ITypeSpec[] Interfaces { get { return interfaces ??= InnerSpec.Interfaces.Select(i => Framework.MetamodelManager.GetSpecification(i)).ToArray(); } } public ITypeSpec[] Subclasses { get { return subclasses ??= InnerSpec.Subclasses.Select(i => Framework.MetamodelManager.GetSpecification(i)).ToArray(); } } public bool IsAbstract { get { isAbstract ??= InnerSpec.GetFacet<ITypeIsAbstractFacet>().Flag; return isAbstract.Value; } } public bool IsInterface { get { isInterface ??= InnerSpec.GetFacet<ITypeIsInterfaceFacet>().Flag; return isInterface.Value; } } public string ShortName { get { if (shortName is null) { var postfix = ""; if (Type.IsGenericType && !IsCollection) { postfix = Type.GetGenericArguments().Aggregate(string.Empty, (x, y) => $"{x}-{Framework.MetamodelManager.GetSpecification(y).ShortName}"); } shortName = InnerSpec.ShortName + postfix; } return shortName; } } public string SingularName => singularName ??= InnerSpec.GetFacet<INamedFacet>().FriendlyName; public string UntitledName => untitledName ??= NakedObjects.Resources.NakedObjects.Untitled + SingularName; public string PluralName => pluralName ??= InnerSpec.GetFacet<IPluralFacet>().Value; public string Description(INakedObjectAdapter nakedObjectAdapter) => description ??= InnerSpec.GetFacet<IDescribedAsFacet>().Description(nakedObjectAdapter, Framework) ?? ""; public bool HasNoIdentity { get { hasNoIdentity ??= InnerSpec.GetFacet<ICollectionFacet>() != null || InnerSpec.GetFacet<IParseableFacet>() != null; return hasNoIdentity.Value; } } public bool IsQueryable { get { isQueryable ??= InnerSpec.IsQueryable; return isQueryable.Value; } } public bool IsVoid { get { isVoid ??= InnerSpec.GetFacet<ITypeIsVoidFacet>().Flag; return isVoid.Value; } } public bool IsStatic { get { isStatic ??= InnerSpec.GetFacet<ITypeIsStaticFacet>().Flag; return isStatic.Value; } } public PersistableType Persistable { get { persistable ??= GetPersistable(); return persistable.Value; } } /// <summary> /// Determines if this class represents the same class, or a subclass, of the specified class. /// </summary> public bool IsOfType(ITypeSpec spec) => InnerSpec.IsOfType(spec.InnerSpec); public string GetTitle(INakedObjectAdapter nakedObjectAdapter) { var titleFacet = GetFacet<ITitleFacet>(); var title = titleFacet?.GetTitle(nakedObjectAdapter, Framework); return title ?? DefaultTitle(); } #endregion } // Copyright (c) Naked Objects Group Ltd.
using System; using System.Collections.Generic; using System.Linq.Expressions; using AutoMapper.Configuration; using AutoMapper.Features; namespace AutoMapper { /// <summary> /// Common mapping configuration options between generic and non-generic mapping configuration /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <typeparam name="TMappingExpression">Concrete return type for fluent interface</typeparam> public interface IMappingExpressionBase<TSource, TDestination, out TMappingExpression> where TMappingExpression : IMappingExpressionBase<TSource, TDestination, TMappingExpression> { Features<IMappingFeature> Features { get; } /// <summary> /// Construct the destination object using the service locator /// </summary> /// <returns>Itself</returns> TMappingExpression ConstructUsingServiceLocator(); /// <summary> /// For self-referential types, limit recurse depth. /// Enables PreserveReferences. /// </summary> /// <param name="depth">Number of levels to limit to</param> /// <returns>Itself</returns> TMappingExpression MaxDepth(int depth); /// <summary> /// Preserve object identity. Useful for circular references. /// </summary> /// <returns>Itself</returns> TMappingExpression PreserveReferences(); /// <summary> /// Disable constructor validation. During mapping this map is used against an existing destination object and never constructed itself. /// </summary> /// <returns>Itself</returns> TMappingExpression DisableCtorValidation(); /// <summary> /// Value transformers, typically configured through explicit or extenstion methods. /// </summary> IList<ValueTransformerConfiguration> ValueTransformers { get; } /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> TMappingExpression BeforeMap(Action<TSource, TDestination> beforeFunction); /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> TMappingExpression BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction); /// <summary> /// Execute a custom mapping action before member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> TMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> TMappingExpression AfterMap(Action<TSource, TDestination> afterFunction); /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> TMappingExpression AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction); /// <summary> /// Execute a custom mapping action after member mapping /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> TMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Specify which member list to validate /// </summary> /// <param name="memberList">Member list to validate</param> /// <returns>Itself</returns> TMappingExpression ValidateMemberList(MemberList memberList); /// <summary> /// Include this configuration in all derived types' maps. Works by scanning all type maps for matches during configuration. /// </summary> /// <returns>Itself</returns> TMappingExpression IncludeAllDerived(); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <param name="derivedSourceType">Derived source type</param> /// <param name="derivedDestinationType">Derived destination type</param> /// <returns>Itself</returns> TMappingExpression Include(Type derivedSourceType, Type derivedDestinationType); /// <summary> /// Include the base type map's configuration in this map /// </summary> /// <param name="sourceBase">Base source type</param> /// <param name="destinationBase">Base destination type</param> /// <returns></returns> TMappingExpression IncludeBase(Type sourceBase, Type destinationBase); /// <summary> /// Customize configuration for an individual source member. Member name not known until runtime /// </summary> /// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> TMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter) /// </summary> /// <returns>Itself</returns> TMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter(); /// <summary> /// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used) /// </summary> /// <returns>Itself</returns> TMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); /// <summary> /// Supply a custom instantiation expression for the destination type /// </summary> /// <param name="ctor">Expression to create the destination type given the source object</param> /// <returns>Itself</returns> TMappingExpression ConstructUsing(Expression<Func<TSource, TDestination>> ctor); /// <summary> /// Supply a custom instantiation function for the destination type, based on the entire resolution context /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="ctor">Callback to create the destination type given the current resolution context</param> /// <returns>Itself</returns> TMappingExpression ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor); /// <summary> /// Customize configuration for individual constructor parameter /// </summary> /// <param name="ctorParamName">Constructor parameter name</param> /// <param name="paramOptions">Options</param> /// <returns>Itself</returns> TMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions); /// <summary> /// Override the destination type mapping for looking up configuration and instantiation /// </summary> /// <param name="typeOverride"></param> void As(Type typeOverride); /// <summary> /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping /// Use this method if you need to specify the converter type at runtime /// </summary> /// <param name="typeConverterType">Type converter type</param> void ConvertUsing(Type typeConverterType); /// <summary> /// Skip member mapping and use a custom expression to convert to the destination type /// </summary> /// <param name="mappingExpression">Callback to convert from source type to destination type</param> void ConvertUsing(Expression<Func<TSource, TDestination>> mappingExpression); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="mappingFunction">Callback to convert from source type to destination type, including destination object</param> void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="mappingFunction">Callback to convert from source type to destination type, with source, destination and context</param> void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="converter">Type converter instance</param> void ConvertUsing(ITypeConverter<TSource, TDestination> converter); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TTypeConverter">Type converter type</typeparam> void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>; } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteCollectionEditor { public class SettingsView { public bool show = false; Vector2 settingsScrollbar = Vector2.zero; int[] padAmountValues = null; string[] padAmountLabels = null; IEditorHost host; public SettingsView(IEditorHost host) { this.host = host; } SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } } Material DuplicateMaterial(Material source) { string sourcePath = AssetDatabase.GetAssetPath(source); string targetPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath); AssetDatabase.CopyAsset(sourcePath, targetPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return AssetDatabase.LoadAssetAtPath(targetPath, typeof(Material)) as Material; } void DrawMaterialEditor() { // Upgrade int numAltMaterials = 0; foreach (var v in SpriteCollection.altMaterials) if (v != null) numAltMaterials++; if ((SpriteCollection.altMaterials.Length == 0 || numAltMaterials == 0) && SpriteCollection.atlasMaterials.Length != 0) SpriteCollection.altMaterials = new Material[1] { SpriteCollection.atlasMaterials[0] }; if (SpriteCollection.altMaterials.Length > 0) { GUILayout.BeginHorizontal(); DrawHeaderLabel("Materials"); GUILayout.FlexibleSpace(); if (GUILayout.Button("+", EditorStyles.miniButton)) { int sourceIndex = -1; int i; for (i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] != null) { sourceIndex = i; break; } } for (i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] == null) break; } if (i == SpriteCollection.altMaterials.Length) System.Array.Resize(ref SpriteCollection.altMaterials, SpriteCollection.altMaterials.Length + 1); Material mtl = null; if (sourceIndex == -1) { Debug.LogError("Sprite collection has null materials. Fix this in the debug inspector."); } else { mtl = DuplicateMaterial(SpriteCollection.altMaterials[sourceIndex]); } SpriteCollection.altMaterials[i] = mtl; SpriteCollection.Trim(); if (SpriteCollection.platforms.Count > 1) { SpriteCollection.platforms[0].spriteCollection.altMaterials = SpriteCollection.altMaterials; EditorUtility.SetDirty(SpriteCollection.platforms[0].spriteCollection); for (int j = 1; j < SpriteCollection.platforms.Count; ++j) { if (!SpriteCollection.platforms[j].Valid) continue; tk2dSpriteCollection data = SpriteCollection.platforms[j].spriteCollection; System.Array.Resize(ref data.altMaterials, SpriteCollection.altMaterials.Length); data.altMaterials[i] = DuplicateMaterial(data.altMaterials[sourceIndex]); EditorUtility.SetDirty(data); } } host.Commit(); } GUILayout.EndHorizontal(); if (SpriteCollection.altMaterials != null) { EditorGUI.indentLevel++; for (int i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] == null) continue; bool deleteMaterial = false; Material newMaterial = EditorGUILayout.ObjectField(SpriteCollection.altMaterials[i], typeof(Material), false) as Material; if (newMaterial == null) { // Can't delete the last one if (numAltMaterials > 1) { bool inUse = false; foreach (var v in SpriteCollection.textureParams) { if (v.materialId == i) { inUse = true; break; } } foreach (var v in SpriteCollection.fonts) { if (v.materialId == i) { inUse = true; break; } } if (inUse) { if (EditorUtility.DisplayDialog("Delete material", "This material is in use. Deleting it will reset materials on " + "sprites that use this material.\n" + "Do you wish to proceed?", "Yes", "Cancel")) { deleteMaterial = true; } } else { deleteMaterial = true; } } } else { SpriteCollection.altMaterials[i] = newMaterial; } if (deleteMaterial) { SpriteCollection.altMaterials[i] = null; // fix up all existing materials int targetMaterialId; for (targetMaterialId = 0; targetMaterialId < SpriteCollection.altMaterials.Length; ++targetMaterialId) if (SpriteCollection.altMaterials[targetMaterialId] != null) break; foreach (var sprite in SpriteCollection.textureParams) { if (sprite.materialId == i) sprite.materialId = targetMaterialId; } foreach (var font in SpriteCollection.fonts) { if (font.materialId == i) font.materialId = targetMaterialId; } SpriteCollection.Trim(); // Do the same on inherited sprite collections for (int j = 0; j < SpriteCollection.platforms.Count; ++j) { if (!SpriteCollection.platforms[j].Valid) continue; tk2dSpriteCollection data = SpriteCollection.platforms[j].spriteCollection; data.altMaterials[i] = null; for (int lastIndex = data.altMaterials.Length - 1; lastIndex >= 0; --lastIndex) { if (data.altMaterials[lastIndex] != null) { int count = data.altMaterials.Length - 1 - lastIndex; if (count > 0) System.Array.Resize(ref data.altMaterials, lastIndex + 1); break; } } EditorUtility.SetDirty(data); } host.Commit(); } } EditorGUI.indentLevel--; } } } void DrawHeaderLabel(string name) { GUILayout.Label(name, EditorStyles.boldLabel); } void BeginHeader(string name) { DrawHeaderLabel(name); GUILayout.Space(2); EditorGUI.indentLevel++; } void EndHeader() { EditorGUI.indentLevel--; GUILayout.Space(8); } void DrawSystemSettings() { BeginHeader("System"); // Loadable bool allowSwitch = SpriteCollection.spriteCollection != null; bool loadable = SpriteCollection.spriteCollection?SpriteCollection.loadable:false; bool newLoadable = EditorGUILayout.Toggle("Loadable asset", loadable); if (newLoadable != loadable) { if (!allowSwitch) { EditorUtility.DisplayDialog("Please commit the sprite collection before attempting to make it loadable.", "Make loadable.", "Ok"); } else { if (newLoadable) { if (SpriteCollection.assetName.Length == 0) SpriteCollection.assetName = SpriteCollection.spriteCollection.spriteCollectionName; // guess something tk2dSystemUtility.MakeLoadableAsset(SpriteCollection.spriteCollection, SpriteCollection.assetName); } else { if (tk2dSystemUtility.IsLoadableAsset(SpriteCollection.spriteCollection)) tk2dSystemUtility.UnmakeLoadableAsset(SpriteCollection.spriteCollection); } loadable = newLoadable; SpriteCollection.loadable = loadable; } } if (loadable) { SpriteCollection.assetName = EditorGUILayout.TextField("Asset Name/Path", SpriteCollection.assetName); } // Clear data GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("References"); if (GUILayout.Button("Clear References", EditorStyles.miniButton)) { if (EditorUtility.DisplayDialog("Clear references", "Clearing references will clear references to data (atlases, materials) owned by this sprite collection. " + "This will only remove references, and will not delete the data or textures. " + "Use after duplicating a sprite collection to sever links with the original.\n\n" + "Are you sure you want to do this?" , "Yes", "No")) { SpriteCollection.ClearReferences(); foreach (tk2dSpriteCollectionPlatform plat in SpriteCollection.platforms) plat.spriteCollection = null; } } GUILayout.EndHorizontal(); EndHeader(); } void DrawPlatforms() { // Asset Platform BeginHeader("Platforms"); tk2dSystem system = tk2dSystem.inst_NoCreate; if (system == null && GUILayout.Button("Add Platform Support")) system = tk2dSystem.inst; // force creation if (system) { int toDelete = -1; for (int i = 0; i < SpriteCollection.platforms.Count; ++i) { tk2dSpriteCollectionPlatform currentPlatform = SpriteCollection.platforms[i]; GUILayout.BeginHorizontal(); string label = (i==0)?"Current platform":"Platform"; currentPlatform.name = tk2dGuiUtility.PlatformPopup(system, label, currentPlatform.name); bool displayDelete = ((SpriteCollection.platforms.Count == 1 && SpriteCollection.platforms[0].name.Length > 0) || (SpriteCollection.platforms.Count > 1 && i > 0)); if (displayDelete && GUILayout.Button("Delete", EditorStyles.miniButton, GUILayout.MaxWidth(50))) toDelete = i; GUILayout.EndHorizontal(); } if (toDelete != -1) { tk2dSpriteCollection deletedSpriteCollection = null; if (SpriteCollection.platforms.Count == 1) { if (SpriteCollection.platforms[0].spriteCollection != null && SpriteCollection.platforms[0].spriteCollection.spriteCollection != null) deletedSpriteCollection = SpriteCollection.platforms[0].spriteCollection; SpriteCollection.platforms[0].name = ""; SpriteCollection.platforms[0].spriteCollection = null; } else { if (SpriteCollection.platforms[toDelete].spriteCollection != null && SpriteCollection.platforms[toDelete].spriteCollection.spriteCollection != null) deletedSpriteCollection = SpriteCollection.platforms[toDelete].spriteCollection; SpriteCollection.platforms.RemoveAt(toDelete); } if (deletedSpriteCollection != null) { foreach (tk2dSpriteCollectionFont f in deletedSpriteCollection.fonts) tk2dSystemUtility.UnmakeLoadableAsset(f.data); tk2dSystemUtility.UnmakeLoadableAsset(deletedSpriteCollection.spriteCollection); } } if (SpriteCollection.platforms.Count > 1 || (SpriteCollection.platforms.Count == 1 && SpriteCollection.platforms[0].name.Length > 0)) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); if (GUILayout.Button("Add new platform", EditorStyles.miniButton)) SpriteCollection.platforms.Add(new tk2dSpriteCollectionPlatform()); GUILayout.EndHorizontal(); } } EndHeader(); } void DrawTextureSettings() { BeginHeader("Texture Settings"); SpriteCollection.atlasFormat = (tk2dSpriteCollection.AtlasFormat)EditorGUILayout.EnumPopup("Atlas Format", SpriteCollection.atlasFormat); if (SpriteCollection.atlasFormat == tk2dSpriteCollection.AtlasFormat.UnityTexture) { SpriteCollection.filterMode = (FilterMode)EditorGUILayout.EnumPopup("Filter Mode", SpriteCollection.filterMode); SpriteCollection.textureCompression = (tk2dSpriteCollection.TextureCompression)EditorGUILayout.EnumPopup("Compression", SpriteCollection.textureCompression); SpriteCollection.userDefinedTextureSettings = EditorGUILayout.Toggle("User Defined", SpriteCollection.userDefinedTextureSettings); if (SpriteCollection.userDefinedTextureSettings) GUI.enabled = false; EditorGUI.indentLevel++; SpriteCollection.wrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup("Wrap Mode", SpriteCollection.wrapMode); SpriteCollection.anisoLevel = (int)EditorGUILayout.IntSlider("Aniso Level", SpriteCollection.anisoLevel, 0, 9); SpriteCollection.mipmapEnabled = EditorGUILayout.Toggle("Mip Maps", SpriteCollection.mipmapEnabled); EditorGUI.indentLevel--; GUI.enabled = true; } else if (SpriteCollection.atlasFormat == tk2dSpriteCollection.AtlasFormat.Png) { tk2dGuiUtility.InfoBox("Png atlases will decrease on disk game asset sizes, at the expense of increased load times.", tk2dGuiUtility.WarningLevel.Warning); SpriteCollection.textureCompression = (tk2dSpriteCollection.TextureCompression)EditorGUILayout.EnumPopup("Compression", SpriteCollection.textureCompression); SpriteCollection.filterMode = (FilterMode)EditorGUILayout.EnumPopup("Filter Mode", SpriteCollection.filterMode); SpriteCollection.mipmapEnabled = EditorGUILayout.Toggle("Mip Maps", SpriteCollection.mipmapEnabled); } int curRescaleSelection = 0; if (SpriteCollection.globalTextureRescale > 0.4 && SpriteCollection.globalTextureRescale < 0.6) curRescaleSelection = 1; if (SpriteCollection.globalTextureRescale > 0.2 && SpriteCollection.globalTextureRescale < 0.3) curRescaleSelection = 2; int newRescaleSelection = EditorGUILayout.Popup("Rescale", curRescaleSelection, new string[] {"1", "0.5", "0.25"}); switch (newRescaleSelection) { case 0: SpriteCollection.globalTextureRescale = 1.0f; break; case 1: SpriteCollection.globalTextureRescale = 0.5f; break; case 2: SpriteCollection.globalTextureRescale = 0.25f; break; } EndHeader(); } void DrawSpriteCollectionSettings() { BeginHeader("Sprite Collection Settings"); tk2dGuiUtility.SpriteCollectionSize( SpriteCollection.sizeDef ); GUILayout.Space(4); SpriteCollection.padAmount = EditorGUILayout.IntPopup("Pad Amount", SpriteCollection.padAmount, padAmountLabels, padAmountValues); if (SpriteCollection.padAmount == 0 && SpriteCollection.filterMode != FilterMode.Point) { tk2dGuiUtility.InfoBox("Filter mode is not set to Point." + " Some bleeding will occur at sprite edges.", tk2dGuiUtility.WarningLevel.Info); } SpriteCollection.premultipliedAlpha = EditorGUILayout.Toggle("Premultiplied Alpha", SpriteCollection.premultipliedAlpha); SpriteCollection.disableTrimming = EditorGUILayout.Toggle("Disable Trimming", SpriteCollection.disableTrimming); GUIContent gc = new GUIContent("Disable rotation", "Disable rotation of sprites in atlas. Use this if you need consistent UV direction for shader special effects."); SpriteCollection.disableRotation = EditorGUILayout.Toggle(gc, SpriteCollection.disableRotation); SpriteCollection.normalGenerationMode = (tk2dSpriteCollection.NormalGenerationMode)EditorGUILayout.EnumPopup("Normal Generation", SpriteCollection.normalGenerationMode); EndHeader(); } void DrawPhysicsSettings() { BeginHeader("Physics Settings"); #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) GUI.enabled = false; SpriteCollection.physicsEngine = tk2dSpriteDefinition.PhysicsEngine.Physics3D; #endif SpriteCollection.physicsEngine = (tk2dSpriteDefinition.PhysicsEngine)EditorGUILayout.EnumPopup("Physics Engine", SpriteCollection.physicsEngine); #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) GUI.enabled = false; #endif GUI.enabled = SpriteCollection.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D; SpriteCollection.physicsDepth = EditorGUILayout.FloatField("Collider depth", SpriteCollection.physicsDepth); GUI.enabled = true; EndHeader(); } void DrawAtlasSettings() { BeginHeader("Atlas Settings"); int[] allowedAtlasSizes = { 64, 128, 256, 512, 1024, 2048, 4096 }; string[] allowedAtlasSizesString = new string[allowedAtlasSizes.Length]; for (int i = 0; i < allowedAtlasSizes.Length; ++i) allowedAtlasSizesString[i] = allowedAtlasSizes[i].ToString(); SpriteCollection.forceTextureSize = EditorGUILayout.Toggle("Force Atlas Size", SpriteCollection.forceTextureSize); EditorGUI.indentLevel++; if (SpriteCollection.forceTextureSize) { SpriteCollection.forcedTextureWidth = EditorGUILayout.IntPopup("Width", SpriteCollection.forcedTextureWidth, allowedAtlasSizesString, allowedAtlasSizes); SpriteCollection.forcedTextureHeight = EditorGUILayout.IntPopup("Height", SpriteCollection.forcedTextureHeight, allowedAtlasSizesString, allowedAtlasSizes); } else { SpriteCollection.maxTextureSize = EditorGUILayout.IntPopup("Max Size", SpriteCollection.maxTextureSize, allowedAtlasSizesString, allowedAtlasSizes); SpriteCollection.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", SpriteCollection.forceSquareAtlas); } EditorGUI.indentLevel--; bool allowMultipleAtlases = EditorGUILayout.Toggle("Multiple Atlases", SpriteCollection.allowMultipleAtlases); if (allowMultipleAtlases != SpriteCollection.allowMultipleAtlases) { // Disallow switching if using unsupported features if (allowMultipleAtlases == true) { bool hasDicing = false; for (int i = 0; i < SpriteCollection.textureParams.Count; ++i) { if (SpriteCollection.textureParams[i].texture != null & SpriteCollection.textureParams[i].dice) { hasDicing = true; break; } } if (SpriteCollection.fonts.Count > 0 || hasDicing) { EditorUtility.DisplayDialog("Multiple atlases", "Multiple atlases not allowed. This sprite collection contains fonts and/or " + "contains diced sprites.", "Ok"); allowMultipleAtlases = false; } } SpriteCollection.allowMultipleAtlases = allowMultipleAtlases; } if (SpriteCollection.allowMultipleAtlases) { tk2dGuiUtility.InfoBox("Sprite collections with multiple atlas spanning enabled cannot be used with the Static Sprite" + " Batcher, Fonts, the TileMap Editor and doesn't support Sprite Dicing and material level optimizations.\n\n" + "Avoid using it unless you are simply importing a" + " large sequence of sprites for an animation.", tk2dGuiUtility.WarningLevel.Info); } if (SpriteCollection.allowMultipleAtlases) { EditorGUILayout.LabelField("Num Atlases", SpriteCollection.atlasTextures.Length.ToString()); } else { EditorGUILayout.LabelField("Atlas Width", SpriteCollection.atlasWidth.ToString()); EditorGUILayout.LabelField("Atlas Height", SpriteCollection.atlasHeight.ToString()); EditorGUILayout.LabelField("Atlas Wastage", SpriteCollection.atlasWastage.ToString("0.00") + "%"); } if (SpriteCollection.atlasFormat == tk2dSpriteCollection.AtlasFormat.Png) { int totalAtlasSize = 0; foreach (TextAsset ta in SpriteCollection.atlasTextureFiles) { if (ta != null) { totalAtlasSize += ta.bytes.Length; } } EditorGUILayout.LabelField("Atlas File Size", EditorUtility.FormatBytes(totalAtlasSize)); } GUIContent remDuplicates = new GUIContent("Remove Duplicates", "Remove duplicate textures after trimming and other processing."); SpriteCollection.removeDuplicates = EditorGUILayout.Toggle(remDuplicates, SpriteCollection.removeDuplicates); EndHeader(); } public void Draw() { if (SpriteCollection == null) return; // initialize internal stuff if (padAmountValues == null || padAmountValues.Length == 0) { int MAX_PAD_AMOUNT = 18; padAmountValues = new int[MAX_PAD_AMOUNT]; padAmountLabels = new string[MAX_PAD_AMOUNT]; for (int i = 0; i < MAX_PAD_AMOUNT; ++i) { padAmountValues[i] = -1 + i; padAmountLabels[i] = (i==0)?"Default":((i-1).ToString()); } } GUILayout.BeginHorizontal(); GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true)); GUILayout.EndVertical(); Rect rect = GUILayoutUtility.GetLastRect(); tk2dGrid.Draw(rect); int inspectorWidth = host.InspectorWidth; tk2dGuiUtility.LookLikeControls(130.0f, 40.0f); settingsScrollbar = GUILayout.BeginScrollView(settingsScrollbar, GUILayout.ExpandHeight(true), GUILayout.Width(inspectorWidth)); GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG, GUILayout.ExpandWidth(true)); GUILayout.Label("Settings", EditorStyles.largeLabel); SpriteCollection.spriteCollection = EditorGUILayout.ObjectField("Data object", SpriteCollection.spriteCollection, typeof(tk2dSpriteCollectionData), false) as tk2dSpriteCollectionData; GUILayout.EndVertical(); GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); DrawSpriteCollectionSettings(); DrawPhysicsSettings(); DrawTextureSettings(); DrawAtlasSettings(); DrawSystemSettings(); DrawPlatforms(); // Materials if (!SpriteCollection.allowMultipleAtlases) { DrawMaterialEditor(); } GUILayout.Space(8); GUILayout.EndVertical(); GUILayout.EndScrollView(); // make dragable tk2dPreferences.inst.spriteCollectionInspectorWidth -= (int)tk2dGuiUtility.DragableHandle(4819284, GUILayoutUtility.GetLastRect(), 0, tk2dGuiUtility.DragDirection.Horizontal); GUILayout.EndHorizontal(); } } }
using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeFixes; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; using System.Threading; using ICSharpCode.NRefactory6.CSharp.Refactoring; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Linq; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.FindSymbols; namespace ICSharpCode.NRefactory6.CSharp.Diagnostics { [DiagnosticAnalyzer] [ExportDiagnosticAnalyzer("", LanguageNames.CSharp)] [NRefactoryCodeDiagnosticAnalyzer(Description = "", AnalysisDisableKeyword = "")] [IssueDescription("Old-style asynchronous function can be converted to C# 5 async", Description = "Detects usage of old-style TaskCompletionSource/ContinueWith and suggests using async/await instead", Category = IssueCategories.Opportunities, Severity = Severity.Hint)] public class AutoAsyncDiagnosticAnalyzer : GatherVisitorCodeIssueProvider { static readonly ReturnStatement ReturnTaskCompletionSourcePattern = new ReturnStatement { Expression = new MemberReferenceExpression { Target = new IdentifierExpression(Pattern.AnyString).WithName("target"), MemberName = "Task" } }; sealed class OriginalNodeAnnotation { internal readonly AstNode sourceNode; internal OriginalNodeAnnotation(AstNode sourceNode) { this.sourceNode = sourceNode; } } static void AddOriginalNodeAnnotations(AstNode currentFunction) { foreach (var nodeToAnnotate in currentFunction .DescendantNodesAndSelf(MayHaveChildrenToAnnotate) .Where(ShouldAnnotate)) { nodeToAnnotate.AddAnnotation(new OriginalNodeAnnotation(nodeToAnnotate)); } } static void RemoveOriginalNodeAnnotations(AstNode currentFunction) { foreach (var nodeToAnnotate in currentFunction .DescendantNodesAndSelf(MayHaveChildrenToAnnotate) .Where(ShouldAnnotate)) { nodeToAnnotate.RemoveAnnotations<OriginalNodeAnnotation>(); } } static bool MayHaveChildrenToAnnotate(AstNode node) { return node is Statement || node is Expression || node is MethodDeclaration; } static bool ShouldAnnotate(AstNode node) { return node is InvocationExpression; } internal const string DiagnosticId = ""; const string Description = ""; const string MessageFormat = ""; const string Category = IssueCategories.CodeQualityIssues; static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } protected override CSharpSyntaxWalker CreateVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { return new GatherVisitor(semanticModel, addDiagnostic, cancellationToken); } protected override IGatherVisitor CreateVisitor(BaseSemanticModel context) { if (!context.Supports(new Version(5, 0))) { //Old C# version -- async/await are not available return null; } return new GatherVisitor(context); } class GatherVisitor : GatherVisitorBase<AutoAsyncIssue> { public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) : base(semanticModel, addDiagnostic, cancellationToken) { } public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) { AddDiagnosticAnalyzerFor(methodDeclaration); base.VisitMethodDeclaration(methodDeclaration); } public override void VisitLambdaExpression(LambdaExpression lambdaExpression) { AddDiagnosticAnalyzerFor(lambdaExpression); base.VisitLambdaExpression(lambdaExpression); } public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression) { AddDiagnosticAnalyzerFor(anonymousMethodExpression); base.VisitAnonymousMethodExpression(anonymousMethodExpression); } void AddDiagnosticAnalyzerFor(AstNode currentFunction) { if (IsAsync(currentFunction)) return; //Only suggest modifying functions that return void, Task or Task<T>. IType returnType = GetReturnType(ctx, currentFunction); if (returnType == null) { return; } bool isVoid = false; IType resultType = null; switch (returnType.FullName) { case "System.Void": isVoid = true; break; case "System.Threading.Tasks.Task": resultType = returnType.IsParameterized ? returnType.TypeArguments.FirstOrDefault() : null; break; default: return; } var functionBody = currentFunction.GetChildByRole(Roles.Body); var statements = GetStatements(functionBody).ToList(); var returnStatements = statements.OfType<ReturnStatement>().ToList(); var invocations = new List<InvocationExpression>(); var nextInChain = new Dictionary<InvocationExpression, InvocationExpression>(); foreach (var invocation in currentFunction.Descendants.OfType<InvocationExpression>()) { if (invocation.Arguments.Count != 1) continue; var lambdaOrDelegate = invocation.Arguments.Single(); Statement lambdaBody; if (lambdaOrDelegate is LambdaExpression) { lambdaBody = lambdaOrDelegate.GetChildByRole(LambdaExpression.BodyRole) as BlockStatement; if (lambdaBody == null) { continue; } } else if (lambdaOrDelegate is AnonymousMethodExpression) { lambdaBody = lambdaOrDelegate.GetChildByRole(Roles.Body); } else { continue; } var resolveResult = ctx.Resolve(invocation) as MemberResolveResult; if (resolveResult == null) { continue; } if (resolveResult.Member.FullName != "System.Threading.Tasks.Task.ContinueWith") continue; var parentExpression = invocation.Parent as Expression; if (parentExpression != null) { var mreParent = parentExpression as MemberReferenceExpression; if (mreParent == null || mreParent.MemberName != "ContinueWith") { continue; } var parentInvocation = mreParent.Parent as InvocationExpression; if (parentInvocation == null || parentInvocation.Arguments.Count != 1) { continue; } nextInChain[invocation] = parentInvocation; } invocations.Add(invocation); } if (isVoid && invocations.Count == 0) { //Prevent functions like void Foo() {} from being accepted return; } string taskCompletionSourceIdentifier = null; InvocationExpression returnedContinuation = null; if (isVoid) { if (returnStatements.Any()) return; } else if (!isVoid) { if (returnStatements.Count() != 1) return; var returnStatement = returnStatements.Single(); if (functionBody.Statements.Last() != returnStatement) return; var match = ReturnTaskCompletionSourcePattern.Match(returnStatement); if (match.Success) { var taskCompletionSource = match.Get<IdentifierExpression>("target").Single(); var taskCompletionSourceResolveResult = ctx.Resolve(taskCompletionSource); //Make sure the TaskCompletionSource is a local variable if (!(taskCompletionSourceResolveResult is LocalResolveResult) || taskCompletionSourceResolveResult.Type.FullName != "System.Threading.Tasks.TaskCompletionSource") { return; } taskCompletionSourceIdentifier = taskCompletionSource.Identifier; var cfgBuilder = new ControlFlowGraphBuilder(); var cachedControlFlowGraphs = new Dictionary<BlockStatement, IList<ControlFlowNode>>(); //Make sure there are no unsupported uses of the task completion source foreach (var identifier in functionBody.Descendants.OfType<Identifier>()) { if (identifier.Name != taskCompletionSourceIdentifier) continue; var statement = identifier.GetParent<Statement>(); var variableStatement = statement as VariableDeclarationStatement; if (variableStatement != null) { if (functionBody.Statements.First() != variableStatement || variableStatement.Variables.Count != 1) { //This may actually be valid, but it would add even more complexity to this action return; } var initializer = variableStatement.Variables.First().Initializer as ObjectCreateExpression; if (initializer == null || initializer.Arguments.Count != 0 || !initializer.Initializer.IsNull) { return; } var constructedType = ctx.ResolveType(initializer.Type); if (constructedType.FullName != "System.Threading.Tasks.TaskCompletionSource") { return; } continue; } if (statement == returnStatement) continue; if (identifier.Parent is MemberReferenceExpression) { //Right side of the member. //We don't care about this case since it's not a reference to the variable. continue; } //The method's taskCompletionSource can only be used on the left side of a member //reference expression (specifically tcs.SetResult). var identifierExpressionParent = identifier.Parent as IdentifierExpression; if (identifierExpressionParent == null) { return; } var memberReferenceExpression = identifierExpressionParent.Parent as MemberReferenceExpression; if (memberReferenceExpression == null) { return; } if (memberReferenceExpression.MemberName != "SetResult") { //Aside from the final return statement, the only member of task completion source //that can be used is SetResult. //Perhaps future versions could also include SetException and SetCancelled. return; } //We found a SetResult -- we will now find out if it is in a proper context AstNode node = memberReferenceExpression; for (; ;) { node = node.Parent; if (node == null) { //Abort since this is unexpected (it should never happen) return; } if (node is MethodDeclaration) { //Ok -- tcs.SetResult is in method declaration break; } if (node is LambdaExpression || node is AnonymousMethodExpression) { //It's time to verify if the lambda is supported var lambdaParent = node.Parent as InvocationExpression; if (lambdaParent == null || !invocations.Contains(lambdaParent)) { return; } break; } } var containingContinueWith = node.Parent as InvocationExpression; if (containingContinueWith != null) { if (nextInChain.ContainsKey(containingContinueWith)) { //Unsupported: ContinueWith has a SetResult //but it's not the last in the chain return; } } var containingFunctionBlock = node is LambdaExpression ? (BlockStatement)node.GetChildByRole(LambdaExpression.BodyRole) : node.GetChildByRole(Roles.Body); //Finally, tcs.SetResult must be at the end of its method IList<ControlFlowNode> nodes; if (!cachedControlFlowGraphs.TryGetValue(containingFunctionBlock, out nodes)) { nodes = cfgBuilder.BuildControlFlowGraph(containingFunctionBlock, ctx.CancellationToken); cachedControlFlowGraphs[containingFunctionBlock] = nodes; } var setResultNode = nodes.FirstOrDefault(candidateNode => candidateNode.PreviousStatement == statement); if (setResultNode != null && HasReachableNonReturnNodes(setResultNode)) { //The only allowed outgoing nodes are return statements return; } } } else { //Not TaskCompletionSource-based //Perhaps it is return Task.ContinueWith(foo); if (!invocations.Any()) { return; } var outerMostInvocations = new List<InvocationExpression>(); InvocationExpression currentInvocation = invocations.First(); do { outerMostInvocations.Add(currentInvocation); } while (nextInChain.TryGetValue(currentInvocation, out currentInvocation)); var lastInvocation = outerMostInvocations.Last(); if (returnStatement.Expression != lastInvocation) { return; } //Found return <1>.ContinueWith(<2>); returnedContinuation = lastInvocation; } } //We do not support "return expr" in continuations //The only exception is when the outer method returns that continuation. invocations.RemoveAll(invocation => invocation != returnedContinuation && invocation.Arguments.First().Children.OfType<Statement>().First().DescendantNodesAndSelf(node => node is Statement).OfType<ReturnStatement>().Any(returnStatement => !returnStatement.Expression.IsNull)); AddDiagnosticAnalyzer(new CodeIssue(GetFunctionToken(currentFunction), ctx.TranslateString("Function can be converted to C# 5-style async function"), ctx.TranslateString("Convert to C# 5-style async function"), script => { AddOriginalNodeAnnotations(currentFunction); var newFunction = currentFunction.Clone(); RemoveOriginalNodeAnnotations(currentFunction); //Set async var lambda = newFunction as LambdaExpression; if (lambda != null) lambda.IsAsync = true; var anonymousMethod = newFunction as AnonymousMethodExpression; if (anonymousMethod != null) anonymousMethod.IsAsync = true; var methodDeclaration = newFunction as MethodDeclaration; if (methodDeclaration != null) methodDeclaration.Modifiers |= Modifiers.Async; TransformBody(invocations, isVoid, resultType != null, returnedContinuation, taskCompletionSourceIdentifier, newFunction.GetChildByRole(Roles.Body)); script.Replace(currentFunction, newFunction); })); } void TransformBody(List<InvocationExpression> validInvocations, bool isVoid, bool isParameterizedTask, InvocationExpression returnedContinuation, string taskCompletionSourceIdentifier, BlockStatement blockStatement) { if (!isVoid) { if (returnedContinuation == null) { //Is TaskCompletionSource-based blockStatement.Statements.First().Remove(); //Remove task completion source declaration blockStatement.Statements.Last().Remove(); //Remove final return } //We use ToList() because we will be modifying the original collection foreach (var expressionStatement in blockStatement.Descendants.OfType<ExpressionStatement>().ToList()) { var invocationExpression = expressionStatement.Expression as InvocationExpression; if (invocationExpression == null || invocationExpression.Arguments.Count != 1) continue; var target = invocationExpression.Target as MemberReferenceExpression; if (target == null || target.MemberName != "SetResult") { continue; } var targetExpression = target.Target as IdentifierExpression; if (targetExpression == null || targetExpression.Identifier != taskCompletionSourceIdentifier) { continue; } var returnedExpression = invocationExpression.Arguments.Single(); returnedExpression.Remove(); var originalInvocation = (InvocationExpression)invocationExpression.Annotation<OriginalNodeAnnotation>().sourceNode; var originalReturnedExpression = originalInvocation.Arguments.Single(); var argumentType = ctx.Resolve(originalReturnedExpression).Type; if (!isParameterizedTask) { var parent = expressionStatement.Parent; var resultIdentifier = CreateVariableName(blockStatement, "result"); var blockParent = parent as BlockStatement; var resultDeclarationType = argumentType == SpecialType.NullType ? new PrimitiveType("object") : CreateShortType(originalInvocation, argumentType); var declaration = new VariableDeclarationStatement(resultDeclarationType, resultIdentifier, returnedExpression); if (blockParent == null) { var newStatement = new BlockStatement(); newStatement.Add(declaration); newStatement.Add(new ReturnStatement()); expressionStatement.ReplaceWith(newStatement); } else { blockParent.Statements.InsertAfter(expressionStatement, new ReturnStatement()); expressionStatement.ReplaceWith(declaration); } } else { var newStatement = new ReturnStatement(returnedExpression); expressionStatement.ReplaceWith(newStatement); } } } //Find all instances of ContinueWith to replace and associated var continuations = new List<Tuple<InvocationExpression, InvocationExpression, string>>(); foreach (var invocation in blockStatement.Descendants.OfType<InvocationExpression>()) { if (invocation.Arguments.Count != 1) continue; var originalInvocation = (InvocationExpression)invocation.Annotation<OriginalNodeAnnotation>().sourceNode; if (!validInvocations.Contains(originalInvocation)) continue; var lambda = invocation.Arguments.Single(); string associatedTaskName = null; var lambdaParameters = lambda.GetChildrenByRole(Roles.Parameter).Select(p => p.Name).ToList(); var lambdaTaskParameterName = lambdaParameters.FirstOrDefault(); if (lambdaTaskParameterName != null) { associatedTaskName = lambdaTaskParameterName; } continuations.Add(Tuple.Create(invocation, originalInvocation, associatedTaskName)); } foreach (var continuationTuple in continuations) { string taskName = continuationTuple.Item3 ?? "task"; string effectiveTaskName = CreateVariableName(blockStatement, taskName); string resultName = CreateVariableName(blockStatement, taskName + "Result"); var continuation = continuationTuple.Item1; var originalInvocation = continuationTuple.Item2; var target = continuation.Target.GetChildByRole(Roles.TargetExpression).Detach(); var awaitedExpression = new UnaryOperatorExpression(UnaryOperatorType.Await, target); var replacements = new List<Statement>(); var lambdaExpression = originalInvocation.Arguments.First(); var continuationLambdaResolveResult = (LambdaResolveResult)ctx.Resolve(lambdaExpression); if (!continuationLambdaResolveResult.HasParameterList) { //Lambda has no parameter, so creating a variable for the argument is not needed // (since you can't use an argument that doesn't exist). replacements.Add(new ExpressionStatement(awaitedExpression)); } else { //Lambda has a parameter, which can either be a Task or a Task<T>. var lambdaParameter = continuationLambdaResolveResult.Parameters[0]; bool isTaskIdentifierUsed = lambdaExpression.Descendants.OfType<IdentifierExpression>().Any(identifier => { if (identifier.Identifier != lambdaParameter.Name) return false; var identifierMre = identifier.Parent as MemberReferenceExpression; return identifierMre == null || identifierMre.MemberName != "Result"; }); var precedentTaskType = lambdaParameter.Type; //We might need to separate the task creation and awaiting if (isTaskIdentifierUsed) { //Create new task variable var taskExpression = awaitedExpression.Expression; taskExpression.Detach(); replacements.Add(new VariableDeclarationStatement(CreateShortType(lambdaExpression, precedentTaskType), effectiveTaskName, taskExpression)); awaitedExpression.Expression = new IdentifierExpression(effectiveTaskName); } if (precedentTaskType.IsParameterized) { //precedent is Task<T> var precedentResultType = precedentTaskType.TypeArguments.First(); replacements.Add(new VariableDeclarationStatement(CreateShortType(originalInvocation, precedentResultType), resultName, awaitedExpression)); } else { //precedent is Task replacements.Add(awaitedExpression); } } var parentStatement = continuation.GetParent<Statement>(); var grandParentStatement = parentStatement.Parent; var block = grandParentStatement as BlockStatement; if (block == null) { block = new BlockStatement(); block.Statements.AddRange(replacements); parentStatement.ReplaceWith(block); } else { foreach (var replacement in replacements) { block.Statements.InsertBefore(parentStatement, replacement); } parentStatement.Remove(); } var lambdaOrDelegate = continuation.Arguments.Single(); Statement lambdaContent; if (lambdaOrDelegate is LambdaExpression) { lambdaContent = (Statement)lambdaOrDelegate.GetChildByRole(LambdaExpression.BodyRole); } else { lambdaContent = lambdaOrDelegate.GetChildByRole(Roles.Body); } foreach (var identifierExpression in lambdaContent.Descendants.OfType<IdentifierExpression>()) { if (continuationTuple.Item3 != identifierExpression.Identifier) { continue; } var memberReference = identifierExpression.Parent as MemberReferenceExpression; if (memberReference == null || memberReference.MemberName != "Result") { identifierExpression.ReplaceWith(new IdentifierExpression(effectiveTaskName)); continue; } memberReference.ReplaceWith(new IdentifierExpression(resultName)); } if (lambdaContent is BlockStatement) { Statement previousStatement = replacements.Last(); foreach (var statementInContinuation in lambdaContent.GetChildrenByRole(BlockStatement.StatementRole)) { statementInContinuation.Detach(); block.Statements.InsertAfter(previousStatement, statementInContinuation); previousStatement = statementInContinuation; } } else { lambdaContent.Detach(); block.Statements.InsertAfter(replacements.Last(), lambdaContent); } } } AstType CreateShortType(AstNode node, IType type) { return ctx.CreateTypeSystemAstBuilder(node).ConvertType(type); } } static string CreateVariableName(AstNode currentRootNode, string proposedName) { var identifiers = currentRootNode.Descendants.OfType<Identifier>() .Select(identifier => identifier.Name).Where(identifier => identifier.StartsWith(proposedName, StringComparison.InvariantCulture)).ToList(); for (int i = 0; ; ++i) { string name = proposedName + (i == 0 ? string.Empty : i.ToString()); if (!identifiers.Contains(name)) { return name; } } } static bool HasReachableNonReturnNodes(ControlFlowNode firstNode) { var visitedNodes = new List<ControlFlowNode>(); var nodesToVisit = new HashSet<ControlFlowNode>(); nodesToVisit.Add(firstNode); while (nodesToVisit.Any()) { var node = nodesToVisit.First(); nodesToVisit.Remove(node); visitedNodes.Add(node); if (node.Type == ControlFlowNodeType.LoopCondition) return true; var nextStatement = node.NextStatement; if (nextStatement != null) { if (!(nextStatement is ReturnStatement || nextStatement is GotoStatement || nextStatement is GotoCaseStatement || nextStatement is GotoDefaultStatement || nextStatement is ContinueStatement || nextStatement is BreakStatement)) { return true; } } } return false; } static IType GetReturnType(BaseSemanticModel context, AstNode currentFunction) { var resolveResult = context.Resolve(currentFunction); return resolveResult.IsError ? null : resolveResult.Type; } static IEnumerable<Statement> GetStatements(Statement statement) { return statement.DescendantNodesAndSelf(stmt => stmt is Statement).OfType<Statement>(); } static AstNode GetFunctionToken(AstNode currentFunction) { return (AstNode)currentFunction.GetChildByRole(Roles.Identifier) ?? currentFunction.GetChildByRole(LambdaExpression.ArrowRole) ?? currentFunction.GetChildByRole(AnonymousMethodExpression.DelegateKeywordRole); } static bool IsAsync(AstNode currentFunction) { var method = currentFunction as MethodDeclaration; if (method != null) { return method.HasModifier(Modifiers.Async); } return !currentFunction.GetChildByRole(LambdaExpression.AsyncModifierRole).IsNull; } } [ExportCodeFixProvider(.DiagnosticId, LanguageNames.CSharp)] public class FixProvider : ICodeFixProvider { public IEnumerable<string> GetFixableDiagnosticIds() { yield return .DiagnosticId; } public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var result = new List<CodeAction>(); foreach (var diagonstic in diagnostics) { var node = root.FindNode(diagonstic.Location.SourceSpan); //if (!node.IsKind(SyntaxKind.BaseList)) // continue; var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); result.Add(CodeActionFactory.Create(node.Span, diagonstic.Severity, diagonstic.GetMessage(), document.WithSyntaxRoot(newRoot))); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #define ENABLE #define MINBUFFERS using System; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Runtime.CompilerServices; using System.Diagnostics; #if PINNABLEBUFFERCACHE_MSCORLIB namespace System.Threading #else namespace System #endif { internal sealed class PinnableBufferCache { /// <summary> /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData) /// This is only used in mscorlib. /// </summary> internal PinnableBufferCache(string cacheName, Func<object> factory) { m_NotGen2 = new List<object>(DefaultNumberOfBuffers); m_factory = factory; #if ENABLE // Check to see if we should disable the cache. string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled"; try { string envVar = Environment.GetEnvironmentVariable(envVarName); if (envVar != null) { PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar); int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase); if (0 <= index) { // The cache is disabled because we haven't set the cache name. PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName); return; } } } catch { // Ignore failures when reading the environment variable. } #endif #if MINBUFFERS // Allow the environment to specify a minimum buffer count. string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount"; try { string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName); if (minEnvVar != null) { if (int.TryParse(minEnvVar, out m_minBufferCount)) CreateNewBuffers(); } } catch { // Ignore failures when reading the environment variable. } #endif PinnableBufferCacheEventSource.Log.Create(cacheName); m_CacheName = cacheName; } /// <summary> /// Get a object from the buffer manager. If no buffers exist, allocate a new one. /// </summary> internal object Allocate() { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return m_factory(); #endif // Fast path, get it from our Gen2 aged m_FreeList. object returnBuffer; if (!m_FreeList.TryPop(out returnBuffer)) Restock(out returnBuffer); // Computing free count is expensive enough that we don't want to compute it unless logging is on. if (PinnableBufferCacheEventSource.Log.IsEnabled()) { int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls); if (numAllocCalls >= 1024) { lock (this) { int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0); if (previousNumAllocCalls >= 1024) { int nonGen2Count = 0; foreach (object o in m_FreeList) { if (GC.GetGeneration(o) < GC.MaxGeneration) { nonGen2Count++; } } PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count); } } } PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count); } return returnBuffer; } /// <summary> /// Return a buffer back to the buffer manager. /// </summary> internal void Free(object buffer) { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return; #endif if (PinnableBufferCacheEventSource.Log.IsEnabled()) PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count); // After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path. if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1)) { lock (this) { if (GC.GetGeneration(buffer) < GC.MaxGeneration) { // The buffer is not aged, so put it in the non-aged free list. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count); m_NotGen2.Add(buffer); m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); return; } } } // If we discovered that it is indeed Gen2, great, put it in the Gen2 list. m_FreeList.Push(buffer); } #region Private /// <summary> /// Called when we don't have any buffers in our free list to give out. /// </summary> /// <returns></returns> private void Restock(out object returnBuffer) { lock (this) { // Try again after getting the lock as another thread could have just filled the free list. If we don't check // then we unnecessarily grab a new set of buffers because we think we are out. if (m_FreeList.TryPop(out returnBuffer)) return; // Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC. if (m_restockSize == 0) Gen2GcCallback.Register(Gen2GcCallbackFunc, this); // Indicate to the trimming policy that the free list is insufficent. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count); // Get more buffers if needed. if (m_NotGen2.Count == 0) CreateNewBuffers(); // We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one. // Debug.Assert(m_NotGen2.Count != 0); int idx = m_NotGen2.Count - 1; if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration) idx = 0; returnBuffer = m_NotGen2[idx]; m_NotGen2.RemoveAt(idx); // Remember any sub-optimial buffer so we don't put it on the free list when it gets freed. if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration) { PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count); } // If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list. if (!AgePendingBuffers()) { // Before we could age at set of buffers, we have handed out half of them. // This implies we should be proactive about allocating more (since we will trim them if we over-allocate). if (m_NotGen2.Count == m_restockSize / 2) { PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool"); CreateNewBuffers(); } } } } /// <summary> /// See if we can promote the buffers to the free list. Returns true if successful. /// </summary> private bool AgePendingBuffers() { if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1)) { // Allocate a temp list of buffers that are not actually in gen2, and swap it in once // we're done scanning all buffers. int promotedCount = 0; List<object> notInGen2 = new List<object>(); PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count); for (int i = 0; i < m_NotGen2.Count; i++) { // We actually check every object to ensure that we aren't putting non-aged buffers into the free list. object currentBuffer = m_NotGen2[i]; if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration) { m_FreeList.Push(currentBuffer); promotedCount++; } else { notInGen2.Add(currentBuffer); } } PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count); m_NotGen2 = notInGen2; return true; } return false; } /// <summary> /// Generates some buffers to age into Gen2. /// </summary> private void CreateNewBuffers() { // We choose a very modest number of buffers initially because for the client case. This is often enough. if (m_restockSize == 0) m_restockSize = 4; else if (m_restockSize < DefaultNumberOfBuffers) m_restockSize = DefaultNumberOfBuffers; else if (m_restockSize < 256) m_restockSize = m_restockSize * 2; // Grow quickly at small sizes else if (m_restockSize < 4096) m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones else m_restockSize = 4096; // Cap how agressive we are // Ensure we hit our minimums if (m_minBufferCount > m_buffersUnderManagement) m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement); PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize); for (int i = 0; i < m_restockSize; i++) { // Make a new buffer. object newBuffer = m_factory(); // Create space between the objects. We do this because otherwise it forms a single plug (group of objects) // and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them // we ensure that object get a chance to move independently (even if some are pinned). var dummyObject = new object(); m_NotGen2.Add(newBuffer); } m_buffersUnderManagement += m_restockSize; m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); } /// <summary> /// This is the static function that is called from the gen2 GC callback. /// The input object is the cache itself. /// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when /// the application no longer needs it. /// </summary> private static bool Gen2GcCallbackFunc(object targetObj) { return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded(); } /// <summary> /// This is called on every gen2 GC to see if we need to trim the free list. /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE). /// If you register a non-static function as a callback, then this object will be leaked. /// </summary> private bool TrimFreeListIfNeeded() { int curMSec = Environment.TickCount; int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime; PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec); // If we needed more than just the set of aged buffers since the last time we were called, // we obviously should not be trimming any memory, so do nothing except reset the flag if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } // We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time // is larger than the typical buffer hold time. if (0 <= deltaMSec && deltaMSec < 10000) return true; // If we got here we have spend the last few second without needing to lengthen the free list. Thus // we have 'enough' buffers, but maybe we have too many. // See if we can trim lock (this) { // Hit a race, try again later. if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once. // If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable. if (m_NotGen2.Count > 0) { // If we are not performing an experiment and we have stuff that is waiting to go into the // free list but has not made it there, it could be becasue the 'slow path' of restocking // has not happened, so force this (which should flush the list) and start over. if (!m_trimmingExperimentInProgress) { PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); AgePendingBuffers(); m_trimmingExperimentInProgress = true; return true; } PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); m_buffersUnderManagement -= m_NotGen2.Count; // Possibly revise the restocking down. We don't want to grow agressively if we are trimming. var newRestockSize = m_buffersUnderManagement / 4; if (newRestockSize < m_restockSize) m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers); m_NotGen2.Clear(); m_trimmingExperimentInProgress = false; return true; } // Set up an experiment where we use 25% less buffers in our free list. We put them in // m_NotGen2, and if they are needed they will be put back in the free list again. var trimSize = freeCount / 4 + 1; // We are OK with a 15% overhead, do nothing in that case. if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount) { PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount); return true; } // Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them. PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize); object buffer; for (int i = 0; i < trimSize; i++) { if (m_FreeList.TryPop(out buffer)) m_NotGen2.Add(buffer); } m_msecNoUseBeyondFreeListSinceThisTime = curMSec; m_trimmingExperimentInProgress = true; } // Indicate that we want to be called back on the next Gen 2 GC. return true; } private const int DefaultNumberOfBuffers = 16; private string m_CacheName; private Func<object> m_factory; /// <summary> /// Contains 'good' buffers to reuse. They are guaranteed to be Gen 2 ENFORCED! /// </summary> private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>(); /// <summary> /// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to. /// To implement trimming we sometimes put aged buffers in here as a place to 'park' them /// before true deletion. /// </summary> private List<object> m_NotGen2; /// <summary> /// What was the gen 1 count the last time re restocked? If it is now greater, then /// we know that all objects are in Gen 2 so we don't have to check. Should be updated /// every time something gets added to the m_NotGen2 list. /// </summary> private int m_gen1CountAtLastRestock; /// <summary> /// Used to ensure we have a minimum time between trimmings. /// </summary> private int m_msecNoUseBeyondFreeListSinceThisTime; /// <summary> /// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom' /// This flag indicates that we hit bottom (we really needed a bigger free list). /// </summary> private bool m_moreThanFreeListNeeded; /// <summary> /// The total number of buffers that this cache has ever allocated. /// Used in trimming heuristics. /// </summary> private int m_buffersUnderManagement; /// <summary> /// The number of buffers we added the last time we restocked. /// </summary> private int m_restockSize; /// <summary> /// Did we put some buffers into m_NotGen2 to see if we can trim? /// </summary> private bool m_trimmingExperimentInProgress; /// <summary> /// A forced minimum number of buffers. /// </summary> private int m_minBufferCount; /// <summary> /// The number of calls to Allocate. /// </summary> private int m_numAllocCalls; #endregion } /// <summary> /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once) /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care) /// </summary> internal sealed class Gen2GcCallback : CriticalFinalizerObject { public Gen2GcCallback() : base() { } /// <summary> /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. /// /// NOTE: This callback will be kept alive until either the callback function returns false, /// or the target object dies. /// </summary> public static void Register(Func<object, bool> callback, object targetObj) { // Create a unreachable object that remembers the callback function and target object. Gen2GcCallback gcCallback = new Gen2GcCallback(); gcCallback.Setup(callback, targetObj); } #region Private private Func<object, bool> m_callback; private GCHandle m_weakTargetObj; private void Setup(Func<object, bool> callback, object targetObj) { m_callback = callback; m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } ~Gen2GcCallback() { // Check to see if the target object is still alive. object targetObj = m_weakTargetObj.Target; if (targetObj == null) { // The target object is dead, so this callback object is no longer needed. m_weakTargetObj.Free(); return; } // Execute the callback method. try { if (!m_callback(targetObj)) { // If the callback returns false, this callback object is no longer needed. return; } } catch { // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. } // Resurrect ourselves by re-registering for finalization. if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { GC.ReRegisterForFinalize(this); } } #endregion } internal sealed class PinnableBufferCacheEventSource { public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource(); public bool IsEnabled() { return false; } public void DebugMessage(string message) { } public void Create(string cacheName) { } public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { } public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { } public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { } public void AllocateBufferAged(string cacheName, int agedCount) { } public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { } public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { } public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { } public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { } public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { } public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { } public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { } public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { } public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { } public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { } static internal ulong AddressOf(object obj) { return 0; } } }
using System; using System.Reflection; using System.Collections; using Server; using Server.Commands.Generic; using Server.Network; using Server.Menus; using Server.Menus.Questions; using Server.Targeting; using CPA = Server.CommandPropertyAttribute; namespace Server.Gumps { public class PropertiesGump : Gump { private ArrayList m_List; private int m_Page; private Mobile m_Mobile; private object m_Object; private Type m_Type; private Stack m_Stack; public static readonly bool OldStyle = PropsConfig.OldStyle; public static readonly int GumpOffsetX = PropsConfig.GumpOffsetX; public static readonly int GumpOffsetY = PropsConfig.GumpOffsetY; public static readonly int TextHue = PropsConfig.TextHue; public static readonly int TextOffsetX = PropsConfig.TextOffsetX; public static readonly int OffsetGumpID = PropsConfig.OffsetGumpID; public static readonly int HeaderGumpID = PropsConfig.HeaderGumpID; public static readonly int EntryGumpID = PropsConfig.EntryGumpID; public static readonly int BackGumpID = PropsConfig.BackGumpID; public static readonly int SetGumpID = PropsConfig.SetGumpID; public static readonly int SetWidth = PropsConfig.SetWidth; public static readonly int SetOffsetX = PropsConfig.SetOffsetX, SetOffsetY = PropsConfig.SetOffsetY; public static readonly int SetButtonID1 = PropsConfig.SetButtonID1; public static readonly int SetButtonID2 = PropsConfig.SetButtonID2; public static readonly int PrevWidth = PropsConfig.PrevWidth; public static readonly int PrevOffsetX = PropsConfig.PrevOffsetX, PrevOffsetY = PropsConfig.PrevOffsetY; public static readonly int PrevButtonID1 = PropsConfig.PrevButtonID1; public static readonly int PrevButtonID2 = PropsConfig.PrevButtonID2; public static readonly int NextWidth = PropsConfig.NextWidth; public static readonly int NextOffsetX = PropsConfig.NextOffsetX, NextOffsetY = PropsConfig.NextOffsetY; public static readonly int NextButtonID1 = PropsConfig.NextButtonID1; public static readonly int NextButtonID2 = PropsConfig.NextButtonID2; public static readonly int OffsetSize = PropsConfig.OffsetSize; public static readonly int EntryHeight = PropsConfig.EntryHeight; public static readonly int BorderSize = PropsConfig.BorderSize; private static bool PrevLabel = OldStyle, NextLabel = OldStyle; private static bool TypeLabel = !OldStyle; private static readonly int PrevLabelOffsetX = PrevWidth + 1; private static readonly int PrevLabelOffsetY = 0; private static readonly int NextLabelOffsetX = -29; private static readonly int NextLabelOffsetY = 0; private static readonly int NameWidth = 107; private static readonly int ValueWidth = 128; private static readonly int EntryCount = 15; private static readonly int TypeWidth = NameWidth + OffsetSize + ValueWidth; private static readonly int TotalWidth = OffsetSize + NameWidth + OffsetSize + ValueWidth + OffsetSize + SetWidth + OffsetSize; private static readonly int TotalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (EntryCount + 1)); private static readonly int BackWidth = BorderSize + TotalWidth + BorderSize; private static readonly int BackHeight = BorderSize + TotalHeight + BorderSize; public PropertiesGump(Mobile mobile, object o) : base(GumpOffsetX, GumpOffsetY) { m_Mobile = mobile; m_Object = o; m_Type = o.GetType(); m_List = BuildList(); Initialize(0); } public PropertiesGump(Mobile mobile, object o, Stack stack, StackEntry parent) : base(GumpOffsetX, GumpOffsetY) { m_Mobile = mobile; m_Object = o; m_Type = o.GetType(); m_Stack = stack; m_List = BuildList(); if (parent != null) { if (m_Stack == null) m_Stack = new Stack(); m_Stack.Push(parent); } Initialize(0); } public PropertiesGump(Mobile mobile, object o, Stack stack, ArrayList list, int page) : base(GumpOffsetX, GumpOffsetY) { m_Mobile = mobile; m_Object = o; if (o != null) m_Type = o.GetType(); m_List = list; m_Stack = stack; Initialize(page); } private void Initialize(int page) { m_Page = page; int count = m_List.Count - (page * EntryCount); if (count < 0) count = 0; else if (count > EntryCount) count = EntryCount; int lastIndex = (page * EntryCount) + count - 1; if (lastIndex >= 0 && lastIndex < m_List.Count && m_List[lastIndex] == null) --count; int totalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (count + 1)); AddPage(0); AddBackground(0, 0, BackWidth, BorderSize + totalHeight + BorderSize, BackGumpID); AddImageTiled(BorderSize, BorderSize, TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0), totalHeight, OffsetGumpID); int x = BorderSize + OffsetSize; int y = BorderSize + OffsetSize; int emptyWidth = TotalWidth - PrevWidth - NextWidth - (OffsetSize * 4) - (OldStyle ? SetWidth + OffsetSize : 0); if (OldStyle) AddImageTiled(x, y, TotalWidth - (OffsetSize * 3) - SetWidth, EntryHeight, HeaderGumpID); else AddImageTiled(x, y, PrevWidth, EntryHeight, HeaderGumpID); if (page > 0) { AddButton(x + PrevOffsetX, y + PrevOffsetY, PrevButtonID1, PrevButtonID2, 1, GumpButtonType.Reply, 0); if (PrevLabel) AddLabel(x + PrevLabelOffsetX, y + PrevLabelOffsetY, TextHue, "Previous"); } x += PrevWidth + OffsetSize; if (!OldStyle) AddImageTiled(x, y, emptyWidth, EntryHeight, HeaderGumpID); if (TypeLabel && m_Type != null) AddHtml(x, y, emptyWidth, EntryHeight, String.Format("<BASEFONT COLOR=#FAFAFA><CENTER>{0}</CENTER></BASEFONT>", m_Type.Name), false, false); x += emptyWidth + OffsetSize; if (!OldStyle) AddImageTiled(x, y, NextWidth, EntryHeight, HeaderGumpID); if ((page + 1) * EntryCount < m_List.Count) { AddButton(x + NextOffsetX, y + NextOffsetY, NextButtonID1, NextButtonID2, 2, GumpButtonType.Reply, 1); if (NextLabel) AddLabel(x + NextLabelOffsetX, y + NextLabelOffsetY, TextHue, "Next"); } for (int i = 0, index = page * EntryCount; i < count && index < m_List.Count; ++i, ++index) { x = BorderSize + OffsetSize; y += EntryHeight + OffsetSize; object o = m_List[index]; if (o == null) { AddImageTiled(x - OffsetSize, y, TotalWidth, EntryHeight, BackGumpID + 4); } else if (o is Type) { Type type = (Type)o; AddImageTiled(x, y, TypeWidth, EntryHeight, EntryGumpID); AddLabelCropped(x + TextOffsetX, y, TypeWidth - TextOffsetX, EntryHeight, TextHue, type.Name); x += TypeWidth + OffsetSize; if (SetGumpID != 0) AddImageTiled(x, y, SetWidth, EntryHeight, SetGumpID); } else if (o is PropertyInfo) { PropertyInfo prop = (PropertyInfo)o; AddImageTiled(x, y, NameWidth, EntryHeight, EntryGumpID); AddLabelCropped(x + TextOffsetX, y, NameWidth - TextOffsetX, EntryHeight, TextHue, prop.Name); x += NameWidth + OffsetSize; AddImageTiled(x, y, ValueWidth, EntryHeight, EntryGumpID); AddLabelCropped(x + TextOffsetX, y, ValueWidth - TextOffsetX, EntryHeight, TextHue, ValueToString(prop)); x += ValueWidth + OffsetSize; if (SetGumpID != 0) AddImageTiled(x, y, SetWidth, EntryHeight, SetGumpID); CPA cpa = GetCPA(prop); if (prop.CanWrite && cpa != null && m_Mobile.AccessLevel >= cpa.WriteLevel && !cpa.ReadOnly) AddButton(x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, i + 3, GumpButtonType.Reply, 0); } } } public static string[] m_BoolNames = new string[] { "True", "False" }; public static object[] m_BoolValues = new object[] { true, false }; public static string[] m_PoisonNames = new string[] { "None", "Lesser", "Regular", "Greater", "Deadly", "Lethal" }; public static object[] m_PoisonValues = new object[] { null, Poison.Lesser, Poison.Regular, Poison.Greater, Poison.Deadly, Poison.Lethal }; public class StackEntry { public object m_Object; public PropertyInfo m_Property; public StackEntry(object obj, PropertyInfo prop) { m_Object = obj; m_Property = prop; } } public override void OnResponse(NetState state, RelayInfo info) { Mobile from = state.Mobile; if (!BaseCommand.IsAccessible(from, m_Object)) { from.SendMessage("You may no longer access their properties."); return; } switch (info.ButtonID) { case 0: // Closed { if (m_Stack != null && m_Stack.Count > 0) { StackEntry entry = (StackEntry)m_Stack.Pop(); from.SendGump(new PropertiesGump(from, entry.m_Object, m_Stack, null)); } break; } case 1: // Previous { if (m_Page > 0) from.SendGump(new PropertiesGump(from, m_Object, m_Stack, m_List, m_Page - 1)); break; } case 2: // Next { if ((m_Page + 1) * EntryCount < m_List.Count) from.SendGump(new PropertiesGump(from, m_Object, m_Stack, m_List, m_Page + 1)); break; } default: { int index = (m_Page * EntryCount) + (info.ButtonID - 3); if (index >= 0 && index < m_List.Count) { PropertyInfo prop = m_List[index] as PropertyInfo; if (prop == null) return; CPA attr = GetCPA(prop); if (!prop.CanWrite || attr == null || from.AccessLevel < attr.WriteLevel || attr.ReadOnly) return; Type type = prop.PropertyType; if (IsType(type, typeofMobile) || IsType(type, typeofItem)) from.SendGump(new SetObjectGump(prop, from, m_Object, m_Stack, type, m_Page, m_List)); else if (IsType(type, typeofType)) from.Target = new SetObjectTarget(prop, from, m_Object, m_Stack, type, m_Page, m_List); else if (IsType(type, typeofPoint3D)) from.SendGump(new SetPoint3DGump(prop, from, m_Object, m_Stack, m_Page, m_List)); else if (IsType(type, typeofPoint2D)) from.SendGump(new SetPoint2DGump(prop, from, m_Object, m_Stack, m_Page, m_List)); else if (IsType(type, typeofTimeSpan)) from.SendGump(new SetTimeSpanGump(prop, from, m_Object, m_Stack, m_Page, m_List)); else if (IsCustomEnum(type)) from.SendGump(new SetCustomEnumGump(prop, from, m_Object, m_Stack, m_Page, m_List, GetCustomEnumNames(type))); else if (IsType(type, typeofEnum)) from.SendGump(new SetListOptionGump(prop, from, m_Object, m_Stack, m_Page, m_List, Enum.GetNames(type), GetObjects(Enum.GetValues(type)))); else if (IsType(type, typeofBool)) from.SendGump(new SetListOptionGump(prop, from, m_Object, m_Stack, m_Page, m_List, m_BoolNames, m_BoolValues)); else if (IsType(type, typeofString) || IsType(type, typeofReal) || IsType(type, typeofNumeric) || IsType(type, typeofText)) from.SendGump(new SetGump(prop, from, m_Object, m_Stack, m_Page, m_List)); else if (IsType(type, typeofPoison)) from.SendGump(new SetListOptionGump(prop, from, m_Object, m_Stack, m_Page, m_List, m_PoisonNames, m_PoisonValues)); else if (IsType(type, typeofMap)) from.SendGump(new SetListOptionGump(prop, from, m_Object, m_Stack, m_Page, m_List, Map.GetMapNames(), Map.GetMapValues())); else if (IsType(type, typeofSkills) && m_Object is Mobile) { from.SendGump(new PropertiesGump(from, m_Object, m_Stack, m_List, m_Page)); from.SendGump(new SkillsGump(from, (Mobile)m_Object)); } else if (HasAttribute(type, typeofPropertyObject, true)) { object obj = prop.GetValue(m_Object, null); if (obj != null) from.SendGump(new PropertiesGump(from, obj, m_Stack, new StackEntry(m_Object, prop))); else from.SendGump(new PropertiesGump(from, m_Object, m_Stack, m_List, m_Page)); } } break; } } } private static object[] GetObjects(Array a) { object[] list = new object[a.Length]; for (int i = 0; i < list.Length; ++i) list[i] = a.GetValue(i); return list; } private static bool IsCustomEnum(Type type) { return type.IsDefined(typeofCustomEnum, false); } public static void OnValueChanged(object obj, PropertyInfo prop, Stack stack) { if (stack == null || stack.Count == 0) return; if (!prop.PropertyType.IsValueType) return; StackEntry peek = (StackEntry)stack.Peek(); if (peek.m_Property.CanWrite) peek.m_Property.SetValue(peek.m_Object, obj, null); } private static string[] GetCustomEnumNames(Type type) { object[] attrs = type.GetCustomAttributes(typeofCustomEnum, false); if (attrs.Length == 0) return new string[0]; CustomEnumAttribute ce = attrs[0] as CustomEnumAttribute; if (ce == null) return new string[0]; return ce.Names; } private static bool HasAttribute(Type type, Type check, bool inherit) { object[] objs = type.GetCustomAttributes(check, inherit); return (objs != null && objs.Length > 0); } private static bool IsType(Type type, Type check) { return type == check || type.IsSubclassOf(check); } private static bool IsType(Type type, Type[] check) { for (int i = 0; i < check.Length; ++i) if (IsType(type, check[i])) return true; return false; } private static Type typeofMobile = typeof(Mobile); private static Type typeofItem = typeof(Item); private static Type typeofType = typeof(Type); private static Type typeofPoint3D = typeof(Point3D); private static Type typeofPoint2D = typeof(Point2D); private static Type typeofTimeSpan = typeof(TimeSpan); private static Type typeofCustomEnum = typeof(CustomEnumAttribute); private static Type typeofEnum = typeof(Enum); private static Type typeofBool = typeof(Boolean); private static Type typeofString = typeof(String); private static Type typeofText = typeof(TextDefinition); private static Type typeofPoison = typeof(Poison); private static Type typeofMap = typeof(Map); private static Type typeofSkills = typeof(Skills); private static Type typeofPropertyObject = typeof(PropertyObjectAttribute); private static Type typeofNoSort = typeof(NoSortAttribute); private static Type[] typeofReal = new Type[] { typeof( Single ), typeof( Double ) }; private static Type[] typeofNumeric = new Type[] { typeof( Byte ), typeof( Int16 ), typeof( Int32 ), typeof( Int64 ), typeof( SByte ), typeof( UInt16 ), typeof( UInt32 ), typeof( UInt64 ) }; private string ValueToString(PropertyInfo prop) { return ValueToString(m_Object, prop); } public static string ValueToString(object obj, PropertyInfo prop) { try { return ValueToString(prop.GetValue(obj, null)); } catch (Exception e) { return String.Format("!{0}!", e.GetType()); } } public static string ValueToString(object o) { if (o == null) { return "-null-"; } else if (o is string) { return String.Format("\"{0}\"", (string)o); } else if (o is bool) { return o.ToString(); } else if (o is char) { return String.Format("0x{0:X} '{1}'", (int)(char)o, (char)o); } else if (o is Serial) { Serial s = (Serial)o; if (s.IsValid) { if (s.IsItem) { return String.Format("(I) 0x{0:X}", s.Value); } else if (s.IsMobile) { return String.Format("(M) 0x{0:X}", s.Value); } } return String.Format("(?) 0x{0:X}", s.Value); } else if (o is byte || o is sbyte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong) { return String.Format("{0} (0x{0:X})", o); } else if (o is Mobile) { return String.Format("(M) 0x{0:X} \"{1}\"", ((Mobile)o).Serial.Value, ((Mobile)o).Name); } else if (o is Item) { return String.Format("(I) 0x{0:X}", ((Item)o).Serial.Value); } else if (o is Type) { return ((Type)o).Name; } else if (o is TextDefinition) { return ((TextDefinition)o).Format(true); } else { return o.ToString(); } } private ArrayList BuildList() { ArrayList list = new ArrayList(); if (m_Type == null) return list; PropertyInfo[] props = m_Type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); ArrayList groups = GetGroups(m_Type, props); for (int i = 0; i < groups.Count; ++i) { DictionaryEntry de = (DictionaryEntry)groups[i]; ArrayList groupList = (ArrayList)de.Value; if (!HasAttribute((Type)de.Key, typeofNoSort, false)) groupList.Sort(PropertySorter.Instance); if (i != 0) list.Add(null); list.Add(de.Key); list.AddRange(groupList); } return list; } private static Type typeofCPA = typeof(CPA); private static Type typeofObject = typeof(object); private static CPA GetCPA(PropertyInfo prop) { object[] attrs = prop.GetCustomAttributes(typeofCPA, false); if (attrs.Length > 0) return attrs[0] as CPA; else return null; } private ArrayList GetGroups(Type objectType, PropertyInfo[] props) { Hashtable groups = new Hashtable(); for (int i = 0; i < props.Length; ++i) { PropertyInfo prop = props[i]; if (prop.CanRead) { CPA attr = GetCPA(prop); if (attr != null && m_Mobile.AccessLevel >= attr.ReadLevel) { Type type = prop.DeclaringType; while (true) { Type baseType = type.BaseType; if (baseType == null || baseType == typeofObject) break; if (baseType.GetProperty(prop.Name, prop.PropertyType) != null) type = baseType; else break; } ArrayList list = (ArrayList)groups[type]; if (list == null) groups[type] = list = new ArrayList(); list.Add(prop); } } } ArrayList sorted = new ArrayList(groups); sorted.Sort(new GroupComparer(objectType)); return sorted; } public static object GetObjectFromString(Type t, string s) { if (t == typeof(string)) { return s; } else if (t == typeof(byte) || t == typeof(sbyte) || t == typeof(short) || t == typeof(ushort) || t == typeof(int) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong)) { if (s.StartsWith("0x")) { if (t == typeof(ulong) || t == typeof(uint) || t == typeof(ushort) || t == typeof(byte)) { return Convert.ChangeType(Convert.ToUInt64(s.Substring(2), 16), t); } else { return Convert.ChangeType(Convert.ToInt64(s.Substring(2), 16), t); } } else { return Convert.ChangeType(s, t); } } else if (t == typeof(double) || t == typeof(float)) { return Convert.ChangeType(s, t); } else if (t.IsDefined(typeof(ParsableAttribute), false)) { MethodInfo parseMethod = t.GetMethod("Parse", new Type[] { typeof(string) }); return parseMethod.Invoke(null, new object[] { s }); } throw new Exception("bad"); } private static string GetStringFromObject(object o) { if (o == null) { return "-null-"; } else if (o is string) { return String.Format("\"{0}\"", (string)o); } else if (o is bool) { return o.ToString(); } else if (o is char) { return String.Format("0x{0:X} '{1}'", (int)(char)o, (char)o); } else if (o is Serial) { Serial s = (Serial)o; if (s.IsValid) { if (s.IsItem) { return String.Format("(I) 0x{0:X}", s.Value); } else if (s.IsMobile) { return String.Format("(M) 0x{0:X}", s.Value); } } return String.Format("(?) 0x{0:X}", s.Value); } else if (o is byte || o is sbyte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong) { return String.Format("{0} (0x{0:X})", o); } else if (o is Mobile) { return String.Format("(M) 0x{0:X} \"{1}\"", ((Mobile)o).Serial.Value, ((Mobile)o).Name); } else if (o is Item) { return String.Format("(I) 0x{0:X}", ((Item)o).Serial.Value); } else if (o is Type) { return ((Type)o).Name; } else { return o.ToString(); } } private class PropertySorter : IComparer { public static readonly PropertySorter Instance = new PropertySorter(); private PropertySorter() { } public int Compare(object x, object y) { if (x == null && y == null) return 0; else if (x == null) return -1; else if (y == null) return 1; PropertyInfo a = x as PropertyInfo; PropertyInfo b = y as PropertyInfo; if (a == null || b == null) throw new ArgumentException(); return a.Name.CompareTo(b.Name); } } private class GroupComparer : IComparer { private Type m_Start; public GroupComparer(Type start) { m_Start = start; } private static Type typeofObject = typeof(Object); private int GetDistance(Type type) { Type current = m_Start; int dist; for (dist = 0; current != null && current != typeofObject && current != type; ++dist) current = current.BaseType; return dist; } public int Compare(object x, object y) { if (x == null && y == null) return 0; else if (x == null) return -1; else if (y == null) return 1; if (!(x is DictionaryEntry) || !(y is DictionaryEntry)) throw new ArgumentException(); DictionaryEntry de1 = (DictionaryEntry)x; DictionaryEntry de2 = (DictionaryEntry)y; Type a = (Type)de1.Key; Type b = (Type)de2.Key; return GetDistance(a).CompareTo(GetDistance(b)); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Microsoft.Azure.KeyVault { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Models; using System.Security.Cryptography.X509Certificates; /// <summary> /// Extension methods for KeyVaultClient. /// </summary> public static partial class KeyVaultClientExtensions { #region Key Crypto Operations /// <summary> /// Encrypts a single block of data. The amount of data that may be encrypted is determined /// by the target key type and the encryption algorithm. /// </summary> /// <param name="keyIdentifier">The full key identifier</param> /// <param name="algorithm">The algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="plainText">The plain text</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The encrypted text</returns> public static async Task<KeyOperationResult> EncryptAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] plainText, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (plainText == null) throw new ArgumentNullException("plainText"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.EncryptWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, plainText, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Decrypts a single block of encrypted data /// </summary> /// <param name="keyIdentifier">The full key identifier</param> /// <param name="algorithm">The algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="cipherText">The cipher text</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The decryption result</returns> public static async Task<KeyOperationResult> DecryptAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] cipherText, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (cipherText == null) throw new ArgumentNullException("cipherText"); var keyId = new KeyIdentifier(keyIdentifier); // TODO: should we allow or not allow in the Key Identifier the version to be empty? using (var _result = await operations.DecryptWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, cipherText, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a signature from a digest using the specified key in the vault /// </summary> /// <param name="keyIdentifier"> The global key identifier of the signing key </param> /// <param name="algorithm">The signing algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. </param> /// <param name="digest">The digest value to sign</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The signature value</returns> public static async Task<KeyOperationResult> SignAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] digest, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (digest == null) throw new ArgumentNullException("digest"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.SignWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, digest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Verifies a signature using the specified key /// </summary> /// <param name="keyIdentifier"> The global key identifier of the key used for signing </param> /// <param name="algorithm"> The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="digest"> The digest used for signing </param> /// <param name="signature"> The signature to be verified </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> true if the signature is verified, false otherwise. </returns> public static async Task<bool> VerifyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (digest == null) throw new ArgumentNullException("digest"); if (signature == null) throw new ArgumentNullException("signature"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.VerifyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, digest, signature, null, cancellationToken).ConfigureAwait(false)) { var verifyResult = _result.Body; return (verifyResult.Value == true) ? true : false; } } /// <summary> /// Wraps a symmetric key using the specified key /// </summary> /// <param name="keyIdentifier"> The global key identifier of the key used for wrapping </param> /// <param name="algorithm"> The wrap algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="key"> The symmetric key </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> The wrapped symmetric key </returns> public static async Task<KeyOperationResult> WrapKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] key, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (key == null) throw new ArgumentNullException("key"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.WrapKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, key, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Unwraps a symmetric key using the specified key in the vault /// that has initially been used for wrapping the key. /// </summary> /// <param name="keyIdentifier"> The global key identifier of the wrapping/unwrapping key </param> /// <param name="algorithm">The unwrap algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="wrappedKey">The wrapped symmetric key</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The unwrapped symmetric key</returns> public static async Task<KeyOperationResult> UnwrapKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] wrappedKey, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (wrappedKey == null) throw new ArgumentNullException("wrappedKey"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.UnwrapKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, wrappedKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Key Management /// <summary> /// Retrieves the public portion of a key plus its attributes /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A KeyBundle of the key and its attributes</returns> public static async Task<KeyBundle> GetKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); using (var _result = await operations.GetKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves the public portion of a key plus its attributes /// </summary> /// <param name="keyIdentifier">The key identifier</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A KeyBundle of the key and its attributes</returns> public static async Task<KeyBundle> GetKeyAsync(this IKeyVaultClient operations, string keyIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.GetKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Key Attributes associated with the specified key /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="keyOps">Json web key operations. For more information on possible key operations, see JsonWebKeyOperation.</param> /// <param name="attributes">The new attributes for the key. For more information on key attributes, see KeyAttributes.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <returns> The updated key </returns> public static async Task<KeyBundle> UpdateKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, string[] keyOps = null, KeyAttributes attributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); using (var _result = await operations.UpdateKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, string.Empty, keyOps, attributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Key Attributes associated with the specified key /// </summary> /// <param name="keyIdentifier">The key identifier</param> /// <param name="keyOps">Json web key operations. For more information, see JsonWebKeyOperation.</param> /// <param name="attributes">The new attributes for the key. For more information on key attributes, see KeyAttributes.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> The updated key </returns> public static async Task<KeyBundle> UpdateKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string[] keyOps = null, KeyAttributes attributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.UpdateKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, keyOps, attributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Imports a key into the specified vault /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="keyBundle"> Key bundle </param> /// <param name="importToHardware">Whether to import as a hardware key (HSM) or software key </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> Imported key bundle to the vault </returns> public static async Task<KeyBundle> ImportKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, KeyBundle keyBundle, bool? importToHardware = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); if (keyBundle == null) throw new ArgumentNullException("keyBundle"); using (var _result = await operations.ImportKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, keyBundle.Key, importToHardware, keyBundle.Attributes, keyBundle.Tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Secret Management /// <summary> /// Gets a secret. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the secrets.</param> /// <param name="secretName">The name the secret in the given vault.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the secret</returns> public static async Task<SecretBundle> GetSecretAsync(this IKeyVaultClient operations, string vaultBaseUrl, string secretName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(secretName)) throw new ArgumentNullException("secretName"); using (var _result = await operations.GetSecretWithHttpMessagesAsync(vaultBaseUrl, secretName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a secret. /// </summary> /// <param name="secretIdentifier">The URL for the secret.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the secret</returns> public static async Task<SecretBundle> GetSecretAsync(this IKeyVaultClient operations, string secretIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(secretIdentifier)) throw new ArgumentNullException("secretIdentifier"); var secretId = new SecretIdentifier(secretIdentifier); using (var _result = await operations.GetSecretWithHttpMessagesAsync(secretId.Vault, secretId.Name, secretId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the attributes associated with the specified secret /// </summary> /// <param name="secretIdentifier">The URL of the secret</param> /// <param name="contentType">Type of the secret value such as password.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="secretAttributes">Attributes for the secret. For more information on possible attributes, see SecretAttributes.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the updated secret</returns> public static async Task<SecretBundle> UpdateSecretAsync(this IKeyVaultClient operations, string secretIdentifier, string contentType = null, SecretAttributes secretAttributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(secretIdentifier)) throw new ArgumentNullException("secretIdentifier"); var secretId = new SecretIdentifier(secretIdentifier); using (var _result = await operations.UpdateSecretWithHttpMessagesAsync(secretId.Vault, secretId.Name, secretId.Version, contentType, secretAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Recovery Management /// <summary> /// Recovers the deleted secret. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted secret, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered secret</returns> public static async Task<SecretBundle> RecoverDeletedSecretAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var secretRecoveryId = new DeletedSecretIdentifier(recoveryId); using (var _result = await operations.RecoverDeletedSecretWithHttpMessagesAsync(secretRecoveryId.Vault, secretRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Recovers the deleted key. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted key, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered key</returns> public static async Task<KeyBundle> RecoverDeletedKeyAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var keyRecoveryId = new DeletedKeyIdentifier(recoveryId); using (var _result = await operations.RecoverDeletedKeyWithHttpMessagesAsync(keyRecoveryId.Vault, keyRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Recovers the deleted certificate. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted certificate, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered certificate</returns> public static async Task<CertificateBundle> RecoverDeletedCertificateAsync( this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default( CancellationToken ) ) { if ( string.IsNullOrEmpty( recoveryId ) ) throw new ArgumentNullException( nameof( recoveryId ) ); var certificateRecoveryId = new DeletedCertificateIdentifier(recoveryId); using ( var _result = await operations.RecoverDeletedCertificateWithHttpMessagesAsync( certificateRecoveryId.Vault, certificateRecoveryId.Name, null, cancellationToken ).ConfigureAwait( false ) ) { return _result.Body; } } /// <summary> /// Purges the deleted secret immediately. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted secret, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Task representing the asynchronous execution of this request.</returns> public static async Task PurgeDeletedSecretAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var secretRecoveryId = new DeletedSecretIdentifier(recoveryId); using (var _result = await operations.PurgeDeletedSecretWithHttpMessagesAsync(secretRecoveryId.Vault, secretRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return; } } /// <summary> /// Purges the deleted key immediately. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted key, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Task representing the asynchronous execution of this request.</returns> public static async Task PurgeDeletedKeyAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var keyRecoveryId = new DeletedKeyIdentifier(recoveryId); using (var _result = await operations.PurgeDeletedKeyWithHttpMessagesAsync(keyRecoveryId.Vault, keyRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return; } } /// <summary> /// Purges the deleted certificate with immediate effect. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted certificate, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Task representing the asynchronous execution of this request.</returns> public static async Task PurgeDeletedCertificateAsync( this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default( CancellationToken ) ) { if ( string.IsNullOrEmpty( recoveryId ) ) throw new ArgumentNullException( nameof( recoveryId ) ); var certificateRecoveryId = new DeletedCertificateIdentifier(recoveryId); using ( var _result = await operations.PurgeDeletedCertificateWithHttpMessagesAsync( certificateRecoveryId.Vault, certificateRecoveryId.Name, null, cancellationToken ).ConfigureAwait( false ) ) { return; } } #endregion #region Certificate Management /// <summary> /// Gets a certificate. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate.</param> /// <param name="certificateName">The name of the certificate in the given vault.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The retrieved certificate</returns> public static async Task<CertificateBundle> GetCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(certificateName)) throw new ArgumentNullException("certificateName"); using (var _result = await operations.GetCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a certificate. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The retrieved certificate</returns> public static async Task<CertificateBundle> GetCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(certificateIdentifier)) throw new ArgumentNullException("certificateIdentifier"); var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.GetCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a certificate version. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name='certificatePolicy'>The management policy for the certificate.</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The updated certificate.</returns> public static async Task<CertificateBundle> UpdateCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(certificateIdentifier)) throw new ArgumentNullException("certificateIdentifier"); var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.UpdateCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Imports a new certificate version. If this is the first version, the certificate resource is created. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="certificateCollection">The certificate collection with the private key</param> /// <param name="certificatePolicy">The management policy for the certificate</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Imported certificate bundle to the vault.</returns> public static async Task<CertificateBundle> ImportCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection certificateCollection, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); if (null == certificateCollection) throw new ArgumentNullException("certificateCollection"); var base64EncodedCertificate = Convert.ToBase64String(certificateCollection.Export(X509ContentType.Pfx)); using (var _result = await operations.ImportCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken)) { return _result.Body; } } /// <summary> /// Merges a certificate or a certificate chain with a key pair existing on the server. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="x509Certificates">The certificate or the certificte chain to merge</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the merged certificate.</returns> public static async Task<CertificateBundle> MergeCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection x509Certificates, CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); if (x509Certificates == null || x509Certificates.Count == 0) throw new ArgumentException("x509Certificates"); var X5C = new List<byte[]>(); foreach (var cert in x509Certificates) { X5C.Add(cert.Export(X509ContentType.Cert)); } using (var _result = await operations.MergeCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, X5C, certificateAttributes, tags, null, cancellationToken)) { return _result.Body; } } /// <summary> /// Gets the Base64 pending certificate signing request (PKCS-10) /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The pending certificate signing request as Base64 encoded string.</returns> public static async Task<string> GetPendingCertificateSigningRequestAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); using (var _result = await operations.GetPendingCertificateSigningRequestWithHttpMessagesAsync(vaultBaseUrl, certificateName, null, cancellationToken)) { return _result.Body; } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using d60.Cirqus.Events; using d60.Cirqus.Exceptions; using d60.Cirqus.Extensions; using d60.Cirqus.Numbers; using d60.Cirqus.Serialization; using Npgsql; namespace d60.Cirqus.PostgreSql.Events { public class PostgreSqlEventStore : IEventStore { readonly string _connectionString; readonly string _tableName; readonly MetadataSerializer _metadataSerializer = new MetadataSerializer(); public PostgreSqlEventStore(string connectionStringOrConnectionStringName, string tableName, bool automaticallyCreateSchema = true) { _tableName = tableName; _connectionString = SqlHelper.GetConnectionString(connectionStringOrConnectionStringName); if (automaticallyCreateSchema) { CreateSchema(); } } void CreateSchema() { var sql = string.Format(@" DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '{0}' ) THEN CREATE TABLE IF NOT EXISTS ""{0}"" ( ""id"" BIGSERIAL NOT NULL, ""batchId"" UUID NOT NULL, ""aggId"" VARCHAR(255) NOT NULL, ""seqNo"" BIGINT NOT NULL, ""globSeqNo"" BIGINT NOT NULL, ""meta"" BYTEA NOT NULL, ""data"" BYTEA NOT NULL, PRIMARY KEY (""id"") ); CREATE UNIQUE INDEX ""Idx_{0}_aggId_seqNo"" ON ""{0}"" (""aggId"", ""seqNo""); CREATE UNIQUE INDEX ""Idx_{0}_globSeqNo"" ON ""{0}"" (""globSeqNo""); END IF; END$$; ", _tableName); using (var connection = GetConnection()) using (var command = connection.CreateCommand()) { command.CommandText = sql; command.ExecuteNonQuery(); } } public void Save(Guid batchId, IEnumerable<EventData> batch) { var eventList = batch.ToList(); try { using (var connection = GetConnection()) using (var tx = connection.BeginTransaction()) { var nextSequenceNumber = GetNextGlobalSequenceNumber(connection, tx); foreach (var e in eventList) { e.Meta[DomainEvent.MetadataKeys.GlobalSequenceNumber] = (nextSequenceNumber++).ToString(Metadata.NumberCulture); e.Meta[DomainEvent.MetadataKeys.BatchId] = batchId.ToString(); } EventValidation.ValidateBatchIntegrity(batchId, eventList); foreach (var e in eventList) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@" INSERT INTO ""{0}"" ( ""batchId"", ""aggId"", ""seqNo"", ""globSeqNo"", ""data"", ""meta"" ) VALUES ( @batchId, @aggId, @seqNo, @globSeqNo, @data, @meta ) ", _tableName); cmd.Parameters.AddWithValue("batchId", batchId); cmd.Parameters.AddWithValue("aggId", e.GetAggregateRootId()); cmd.Parameters.AddWithValue("seqNo", e.Meta[DomainEvent.MetadataKeys.SequenceNumber]); cmd.Parameters.AddWithValue("globSeqNo", e.Meta[DomainEvent.MetadataKeys.GlobalSequenceNumber]); cmd.Parameters.AddWithValue("data", e.Data); cmd.Parameters.AddWithValue("meta", Encoding.UTF8.GetBytes(_metadataSerializer.Serialize(e.Meta))); cmd.ExecuteNonQuery(); } } tx.Commit(); } } catch (NpgsqlException exception) { if (exception.Code == "23505") { throw new ConcurrencyException(batchId, eventList, exception); } throw; } } long GetNextGlobalSequenceNumber(NpgsqlConnection conn, NpgsqlTransaction tx) { using (var cmd = conn.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"SELECT MAX(""globSeqNo"") FROM ""{0}""", _tableName); var result = cmd.ExecuteScalar(); return result != DBNull.Value ? (long)result + 1 : 0; } } NpgsqlConnection GetConnection() { var connection = new NpgsqlConnection(_connectionString); connection.Open(); return connection; } public IEnumerable<EventData> Load(string aggregateRootId, long firstSeq = 0) { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"SELECT ""data"", ""meta"" FROM ""{0}"" WHERE ""aggId"" = @aggId AND ""seqNo"" >= @firstSeqNo", _tableName); cmd.Parameters.AddWithValue("aggId", aggregateRootId); cmd.Parameters.AddWithValue("firstSeqNo", firstSeq); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return ReadEvent(reader); } } } tx.Commit(); } } } public IEnumerable<EventData> Stream(long globalSequenceNumber = 0) { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@" SELECT ""data"", ""meta"" FROM ""{0}"" WHERE ""globSeqNo"" >= @cutoff ORDER BY ""globSeqNo""", _tableName); cmd.Parameters.AddWithValue("cutoff", globalSequenceNumber); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return ReadEvent(reader); } } } } } } EventData ReadEvent(IDataRecord reader) { var data = (byte[]) reader["data"]; var meta = (byte[]) reader["meta"]; return EventData.FromMetadata(_metadataSerializer.Deserialize(Encoding.UTF8.GetString(meta)), data); } public long GetNextGlobalSequenceNumber() { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { return GetNextGlobalSequenceNumber(connection, tx); } } } public void DropEvents() { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"DELETE FROM ""{0}""", _tableName); cmd.ExecuteNonQuery(); } tx.Commit(); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: helloworld.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 Helloworld { /// <summary>Holder for reflection information generated from helloworld.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class HelloworldReflection { #region Descriptor /// <summary>File descriptor for helloworld.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static HelloworldReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChBoZWxsb3dvcmxkLnByb3RvEgpoZWxsb3dvcmxkIhwKDEhlbGxvUmVxdWVz", "dBIMCgRuYW1lGAEgASgJIh0KCkhlbGxvUmVwbHkSDwoHbWVzc2FnZRgBIAEo", "CTJJCgdHcmVldGVyEj4KCFNheUhlbGxvEhguaGVsbG93b3JsZC5IZWxsb1Jl", "cXVlc3QaFi5oZWxsb3dvcmxkLkhlbGxvUmVwbHkiAEI2Chtpby5ncnBjLmV4", "YW1wbGVzLmhlbGxvd29ybGRCD0hlbGxvV29ybGRQcm90b1ABogIDSExXYgZw", "cm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Helloworld.HelloRequest), global::Helloworld.HelloRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Helloworld.HelloReply), global::Helloworld.HelloReply.Parser, new[]{ "Message" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// The request message containing the user's name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class HelloRequest : pb::IMessage<HelloRequest> { private static readonly pb::MessageParser<HelloRequest> _parser = new pb::MessageParser<HelloRequest>(() => new HelloRequest()); public static pb::MessageParser<HelloRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public HelloRequest() { OnConstruction(); } partial void OnConstruction(); public HelloRequest(HelloRequest other) : this() { name_ = other.name_; } public HelloRequest Clone() { return new HelloRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as HelloRequest); } public bool Equals(HelloRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.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); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(HelloRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } 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; } } } } } /// <summary> /// The response message containing the greetings /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class HelloReply : pb::IMessage<HelloReply> { private static readonly pb::MessageParser<HelloReply> _parser = new pb::MessageParser<HelloReply>(() => new HelloReply()); public static pb::MessageParser<HelloReply> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public HelloReply() { OnConstruction(); } partial void OnConstruction(); public HelloReply(HelloReply other) : this() { message_ = other.message_; } public HelloReply Clone() { return new HelloReply(this); } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 1; private string message_ = ""; public string Message { get { return message_; } set { message_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as HelloReply); } public bool Equals(HelloReply other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Message != other.Message) return false; return true; } public override int GetHashCode() { int hash = 1; if (Message.Length != 0) hash ^= Message.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Message.Length != 0) { output.WriteRawTag(10); output.WriteString(Message); } } public int CalculateSize() { int size = 0; if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } return size; } public void MergeFrom(HelloReply other) { if (other == null) { return; } if (other.Message.Length != 0) { Message = other.Message; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Message = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Common; using Fairweather.Service; namespace Activation { /* Serial numbers generation and validation */ public static class Activation_Data { const int PIN_LENGTH = 16; const string HEX_FORMAT = "{0:X2}"; //{ 0x0D, 0xAB, 0x93, 0x84, 0x71, 0x7D, 0xC1, 0x12, 0xF4, 0x3D } static int[] Hex_Digits { get { // "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; var hex = new int[] { 0x0D, 0xAB, 0x93, 0x84, 0x71, 0x7D, 0xC1, 0x12, 0xF4, 0x3D }; return hex; } } //{ "0D", "AB", "93", "84", "71", "7D", "C1", "12", "F4", "3D" }; static string[] Hex_Strings { get { var ret = Hex_Digits.Select(hex => String.Format(HEX_FORMAT, hex)).ToArray(); return ret; } } /// <summary> Depends on: /// Windows directory date /// Program directory date /// /// "bool request" -> if it is a request key as opposed to activation /// key /// </summary> public static string Generate_Request(bool request) { string windir = H.Get_Win_Dir(); string progdir = Environment.CurrentDirectory; string ret = ""; int temp; DateTime windate = Directory.GetCreationTimeUtc(windir); DateTime progdate = Directory.GetCreationTimeUtc(progdir); temp = (windate.Year % 100) + (progdate.Year % 100) + 20; if (request) temp += 11; ret += String.Format("{0:x}", temp).ToUpper(); ret += "-"; temp = windate.Month + progdate.Month + 40; if (request) temp += 44; ret += String.Format("{0:x}", temp).ToUpper(); ret += "-"; temp = windate.Day + progdate.Day + 30; if (request) temp += 22; ret += String.Format("{0:x}", temp).ToUpper(); ret += "-"; temp = windate.Hour + progdate.Hour + 110; // Removed: + 2 * DateTimeOffset.Now.Offset.Hours; if (request) temp -= 55; ret += String.Format("{0:x}", temp).ToUpper(); ret += "-"; temp = windate.Minute + progdate.Minute + 50; if (request) temp -= 33; ret += String.Format("{0:x}", temp).ToUpper(); return ret; } public static string De_Hyphen(string input) { string ret = input.Replace("-", ""); return ret; } public static bool ValidateKey(string key) { License_Data? temp; bool ret = ValidateKey(key, false, out temp); return ret; } /// <summary> If "validate_modules" is enabled, /// the result depends on the current time. /// /// Otherwise "data" is always null. /// </summary> public static bool ValidateKey(string key, bool validate_modules, out License_Data? data) { data = null; Regex rx_act = new Regex(@"[A-F0-9]{20}"); Regex rx_whyp = new Regex(@"(?:[A-F0-9][A-F0-9]-){9}[A-F0-9][A-F0-9]"); if (rx_whyp.Match(key).Success) { key = De_Hyphen(key); } if (!rx_act.Match(key).Success) return false; if (key.Length != 20) return false; { string temp_1 = ""; for (int i = 0; i < key.Length; i += 4) // XX__XX__XX__XX__XX__ temp_1 += key.Substring(i, 2); var temp_2 = Generate_Request(false); temp_2 = De_Hyphen(temp_2); if (temp_1 != temp_2) return false; } Func<int, int> substring_as_hex = (start) => { var substring = key.Substring(start, 2); return Convert.ToInt32(substring, 16); }; int NC1 = substring_as_hex(2); // Number of companies #1 int MM = substring_as_hex(4); // Month int CE = substring_as_hex(6); // Record Module int DD = substring_as_hex(8); // Day int RE = substring_as_hex(10); // Transactions Module int HH = substring_as_hex(12); // Hour int NC2 = substring_as_hex(14); // Number of companies #2 int LL = substring_as_hex(16); // Minutes int MC = substring_as_hex(18); // Document Module bool rec_module = (CE == HH + DateTime.Today.Day + 62); var today_day = DateTime.Today.Day; if (validate_modules && !rec_module) { if (CE != HH + today_day + 50) return false; } bool tran_module = (RE == LL + today_day + 50); if (validate_modules && !tran_module) { if (RE != LL + today_day + 38) return false; } bool doc_module = (MC == MM + today_day + 82); if (validate_modules && !doc_module) { if (MC != MM + today_day + 96) return false; } if (validate_modules) { int NC = NC1 * 100 + NC2; NC /= 2; NC -= 19; NC -= today_day; NC -= DD; if (NC < 1) return false; data = new License_Data(rec_module, tran_module, doc_module, NC); } return true; } public static bool ValidatePIN(string activation, string pin) { activation = De_Hyphen(activation); string rexpin = @"[A-F0-9]{16}"; string rx_pin_whyp = "(?:[A-F0-9][A-F0-9]-){7}[A-F0-9][A-F0-9]"; if (pin.Match(rx_pin_whyp).Success) pin = De_Hyphen(pin); if (!pin.Match(rexpin).Success) return false; string serial = ""; /* Check if digit groups 0-1, 4-5, etc., are permitted */ /* During activation these digits are generated from the serial number */ var serial_inds = new int[] { 0, 2, 4, 5, 7 }; var allowed = Hex_Strings; for (int ii = 0; ii < serial_inds.Length; ++ii) { var start = 2 * serial_inds[ii]; var temp_str = pin.Substring(start, 2); int index = allowed.IndexOf(temp_str); if (index == -1) return false; serial += index.ToString(); } string generated_pin; Generate_PIN(activation, serial, out generated_pin).tiff(); return generated_pin == pin; #region old // temp now contains integer elements from allowed /* This is where will generate the new PIN */ //var pin_n = new string[10]; //for (int ii = 0; ii < 8; ++ii) { // pin_n[ii] = pin.Substring(2 * ii, 2); //} //int num1 = 4 * (temp[0] % 16) + // temp[1] / 16 + // temp[2] % 16 + // 2 * (temp[3] / 16) + // 3 * (temp[4] % 16); //int num2 = (Convert.ToInt32(activation[1].ToString(), 16) + // 3 * Convert.ToInt32(activation[3].ToString(), 16) + // Convert.ToInt32(activation[8].ToString(), 16) + // 2 * Convert.ToInt32(activation[16].ToString(), 16)); //int num3 = 2 * (temp[0] / 16) + // 4 * temp[1] % 16 + // temp[2] / 16 + // 2 * (temp[3] % 16) + // 3 * (temp[4] % 16); //pin_n[1] = String.Format("{0:X2}", num1); //pin_n[3] = String.Format("{0:X2}", num2); //pin_n[6] = String.Format("{0:X2}", num3); //string pin_t = ""; //foreach (var str in pin_n) // pin_t += str; //return pin == pin_t; #endregion } public static bool Generate_Activation(string request, int nco, bool rec, bool tran, bool doc, out string act) { act = null; try { request = De_Hyphen(request); int LL, HH, DD, MM, YY, NC1, NC2, RM, TM, DM; YY = Convert.ToInt32(request.Substring(0, 2), 16); YY -= 11; MM = Convert.ToInt32(request.Substring(2, 2), 16); MM -= 44; DD = Convert.ToInt32(request.Substring(4, 2), 16); DD -= 22; HH = Convert.ToInt32(request.Substring(6, 2), 16); HH += 55; LL = Convert.ToInt32(request.Substring(8, 2), 16); LL += 33; int today = DateTime.Today.Day; NC1 = ((today + 19 + DD + nco) * 2) / 100; NC2 = ((today + 19 + DD + nco) * 2) % 100; if (rec) RM = HH + today + 62; else RM = HH + today + 50; if (tran) TM = LL + today + 50; else TM = LL + today + 38; if (doc) DM = MM + today + 82; else DM = MM + today + 96; act = String.Format("{0:X2}{1:X2}{2:X2}{3:X2}{4:X2}{5:X2}{6:X2}{7:X2}{8:X2}{9:X2}", YY, NC1, MM, RM, DD, TM, HH, NC2, LL, DM).ToUpper(); return true; } #pragma warning disable catch (ArgumentOutOfRangeException ex) { return false; } #pragma warning restore } public static string Get_Serial(string pin) { if (pin.Length != 16) return ""; var hex = Hex_Strings; Func<int, string> get_from_index = (start) => hex.IndexOf(pin.Substring(start, 2)).ToString(); var ret = get_from_index(0) + get_from_index(4); ret += get_from_index(8) + get_from_index(10); ret += get_from_index(14); return ret; } public static bool Generate_PIN(string activation, string serial, out string pin) { pin = ""; try { activation = De_Hyphen(activation); var hex = Hex_Digits; var serial_as_int = new int[5]; var pin_array = new string[8]; for (int ii = 0; ii < 5; ++ii) { int index = int.Parse(serial[ii].ToString()); serial_as_int[ii] = hex[index]; } Func<int, string> format1 = (index) => String.Format("{0:X2}", serial_as_int[index]); pin_array[0] = format1(0); // pin_array[1] = format2(num1); pin_array[2] = format1(1); // pin_array[3] = format2(num2); pin_array[4] = format1(2); pin_array[5] = format1(3); // pin_array[6] = format2(num3); pin_array[7] = format1(4); Func<int, int> first_hex = (index) => serial_as_int[index] / 16; Func<int, int> second_hex = (index) => serial_as_int[index] % 16; int num1 = 4 * (second_hex(0)) + first_hex(1) + second_hex(2) + 2 * (first_hex(3)) + 3 * (second_hex(4)); Func<int, int> get_digit = (index) => Convert.ToInt16(activation[index].ToString(), 16); int num2 = get_digit(1) + 3 * get_digit(3) + get_digit(8) + 2 * get_digit(16); // There is a small misfeature in the calculation - the former version was missing a pair of braces around // the serial_as_int[1] % 16. See revision 127. int num3 = 2 * (first_hex(0)) + (4 * serial_as_int[1]) % 16 + // sic. first_hex(2) + 2 * (second_hex(3)) + 3 * (second_hex(4)); Func<int, string> format2 = (value) => String.Format("{0:X2}", value); pin_array[1] = format2(num1); pin_array[3] = format2(num2); pin_array[6] = format2(num3); pin = pin_array.Aggregate((a, b) => a + b); return true; } catch (IndexOutOfRangeException) { return false; } } } }
using System; using System.Collections; using System.Collections.Generic; using StructureMap.Pipeline; using StructureMap.Query; namespace StructureMap { /// <summary> /// The main "container" object that implements the Service Locator pattern /// </summary> public interface IContainer : IDisposable { /// <summary> /// Provides queryable access to the configured PluginType's and Instances of this Container /// </summary> IModel Model { get; } /// <summary> /// Creates or finds the named instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object GetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object GetInstance(Type pluginType); /// <summary> /// Creates a new instance of the requested type using the supplied Instance. Mostly used internally /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> /// <returns></returns> object GetInstance(Type pluginType, Instance instance); /// <summary> /// Creates or finds the named instance of T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instanceKey"></param> /// <returns></returns> T GetInstance<T>(string instanceKey); /// <summary> /// Creates or finds the default instance of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T GetInstance<T>(); /// <summary> /// Creates a new instance of the requested type T using the supplied Instance. Mostly used internally /// </summary> /// <param name="instance"></param> /// <returns></returns> T GetInstance<T>(Instance instance); /// <summary> /// Creates or resolves all registered instances of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IList<T> GetAllInstances<T>(); /// <summary> /// Creates or resolves all registered instances of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> IList GetAllInstances(Type pluginType); /// <summary> /// Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object TryGetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object TryGetInstance(Type pluginType); /// <summary> /// Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(); /// <summary> /// Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(string instanceKey); [Obsolete("Please use GetInstance<T>() instead.")] T FillDependencies<T>(); [Obsolete("Please use GetInstance(Type) instead")] object FillDependencies(Type type); /// <summary> /// Used to add additional configuration to a Container *after* the initialization. /// </summary> /// <param name="configure"></param> void Configure(Action<ConfigurationExpression> configure); /// <summary> /// Injects the given object into a Container as the default for the designated /// PLUGINTYPE. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <typeparam name="PLUGINTYPE"></typeparam> /// <param name="instance"></param> void Inject<PLUGINTYPE>(PLUGINTYPE instance); void Inject<PLUGINTYPE>(string name, PLUGINTYPE value); /// <summary> /// Injects the given object into a Container as the default for the designated /// pluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <param name="pluginType"></param> /// <param name="object"></param> void Inject(Type pluginType, object @object); /// <summary> /// Sets the default instance for all PluginType's to the designated Profile. /// </summary> /// <param name="profile"></param> void SetDefaultsToProfile(string profile); /// <summary> /// Returns a report detailing the complete configuration of all PluginTypes and Instances /// </summary> /// <returns></returns> string WhatDoIHave(); /// <summary> /// Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured /// instance and afterward calls any methods marked with the [ValidationMethod] attribute /// </summary> void AssertConfigurationIsValid(); /// <summary> /// Gets all configured instances of type T using explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <returns></returns> IList<T> GetAllInstances<T>(ExplicitArguments args); /// <summary> /// Gets the default instance of type T using the explicitly configured arguments from the "args" /// </summary> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> IList GetAllInstances(Type type, ExplicitArguments args); T GetInstance<T>(ExplicitArguments args); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With<T>(T arg); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument /// with the designated name should be the next value. /// </summary> /// <param name="argName"></param> /// <returns></returns> IExplicitProperty With(string argName); /// <summary> /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <param name="pluginType"></param> /// <param name="args"></param> /// <returns></returns> object GetInstance(Type pluginType, ExplicitArguments args); /// <summary> /// Removes all configured instances of type T from the Container. Use with caution! /// </summary> /// <typeparam name="T"></typeparam> void EjectAllInstancesOf<T>(); /// <summary> /// The "BuildUp" method takes in an already constructed object /// and uses Setter Injection to push in configured dependencies /// of that object /// </summary> /// <param name="target"></param> void BuildUp(object target); void SetDefault(Type pluginType, Instance instance); /// <summary> /// Convenience method to request an object using an Open Generic /// Type and its parameter Types /// </summary> /// <param name="templateType"></param> /// <returns></returns> /// <example> /// IFlattener flattener1 = container.ForGenericType(typeof (IFlattener&lt;&gt;)) /// .WithParameters(typeof (Address)).GetInstanceAs&lt;IFlattener&gt;(); /// </example> Container.OpenGenericTypeExpression ForGenericType(Type templateType); /// <summary> /// Gets the named instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <param name="name"></param> /// <returns></returns> T GetInstance<T>(ExplicitArguments args, string name); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <param name="pluginType"></param> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With(Type pluginType, object arg); /// <summary> /// Shortcut syntax for using an object to find a service that handles /// that type of object by using an open generic type /// </summary> /// <example> /// IHandler handler = container.ForObject(shipment) /// .GetClosedTypeOf(typeof (IHandler<>)) /// .As<IHandler>(); /// </example> /// <param name="subject"></param> /// <returns></returns> CloseGenericTypeExpression ForObject(object subject); /// <summary> /// Starts a "Nested" Container for atomic, isolated access /// </summary> /// <returns></returns> IContainer GetNestedContainer(); /// <summary> /// Starts a new "Nested" Container for atomic, isolated service location. Opens /// </summary> /// <param name="profileName"></param> /// <returns></returns> IContainer GetNestedContainer(string profileName); } }
using FoxTrader.UI.ControlInternal; using OpenTK.Input; using static FoxTrader.Constants; namespace FoxTrader.UI.Control { /// <summary>Control with multiple tabs that can be reordered and dragged</summary> internal class TabControl : GameControl { private readonly ScrollBarButton[] m_scroll; private int m_scrollOffset; /// <summary>Initializes a new instance of the <see cref="TabControl" /> class</summary> /// <param name="c_parentControl">Parent control</param> public TabControl(GameControl c_parentControl) : base(c_parentControl) { m_scroll = new ScrollBarButton[2]; m_scrollOffset = 0; TabStrip = new TabStrip(this); TabStrip.StripPosition = Pos.Top; // Make this some special control? m_scroll[0] = new ScrollBarButton(this); m_scroll[0].SetDirectionLeft(); m_scroll[0].Clicked += ScrollPressedLeft; m_scroll[0].SetSize(14, 16); m_scroll[1] = new ScrollBarButton(this); m_scroll[1].SetDirectionRight(); m_scroll[1].Clicked += ScrollPressedRight; m_scroll[1].SetSize(14, 16); m_innerControl = new TabControlInner(this); m_innerControl.Dock = Pos.Fill; m_innerControl.SendToBack(); IsTabable = false; } /// <summary>Determines if tabs can be reordered by dragging</summary> public bool AllowReorder { get { return TabStrip.AllowReorder; } set { TabStrip.AllowReorder = value; } } /// <summary>Currently active tab button</summary> public TabButton CurrentButton { get; private set; } /// <summary>Current tab strip position</summary> public Pos TabStripPosition { get { return TabStrip.StripPosition; } set { TabStrip.StripPosition = value; } } /// <summary>Tab strip</summary> public TabStrip TabStrip { get; } /// <summary>Number of tabs in the control</summary> public int TabCount => TabStrip.Children.Count; /// <summary>Invoked when a tab has been added</summary> public event TabEventHandler TabAdded; /// <summary>Invoked when a tab has been removed</summary> public event TabEventHandler TabRemoved; /// <summary>Adds a new page/tab</summary> /// <param name="c_label">Tab label</param> /// <param name="c_page">Page contents</param> /// <returns>Newly created control</returns> public TabButton AddPage(string c_label, GameControl c_page = null) { if (null == c_page) { c_page = new GameControl(this); } else { c_page.Parent = this; } var a_button = new TabButton(TabStrip); a_button.SetText(c_label); a_button.Page = c_page; a_button.IsTabable = false; AddPage(a_button); return a_button; } /// <summary>Adds a page/tab</summary> /// <param name="c_button">Page to add. (well, it's a TabButton which is a parent to the page)</param> public void AddPage(TabButton c_button) { var a_page = c_button.Page; a_page.Parent = this; a_page.IsHidden = true; a_page.Margin = new Margin(6, 6, 6, 6); a_page.Dock = Pos.Fill; c_button.Parent = TabStrip; c_button.Dock = Pos.Left; c_button.SizeToContents(); c_button.TabControl?.UnsubscribeTabEvent(c_button); c_button.TabControl = this; c_button.Clicked += OnTabPressed; if (null == CurrentButton) { c_button.OnClicked(null); } TabAdded?.Invoke(this); Invalidate(); } private void UnsubscribeTabEvent(TabButton c_button) { c_button.Clicked -= OnTabPressed; } /// <summary>Handler for tab selection</summary> /// <param name="c_control">Event source (TabButton)</param> internal virtual void OnTabPressed(GameControl c_control, MouseButtonEventArgs c_args) { var a_button = c_control as TabButton; var a_page = a_button?.Page; if (a_page == null) { return; } if (CurrentButton == a_button) { return; } if (null != CurrentButton) { var a_page2 = CurrentButton.Page; if (a_page2 != null) { a_page2.IsHidden = true; } CurrentButton.Redraw(); CurrentButton = null; } CurrentButton = a_button; a_page.IsHidden = false; TabStrip.Invalidate(); Invalidate(); } /// <summary>Function invoked after layout</summary> /// <param name="c_skin">Skin to use</param> protected override void PostLayout(Skin c_skin) { base.PostLayout(c_skin); HandleOverflow(); } /// <summary>Handler for tab removing</summary> /// <param name="c_button"></param> internal virtual void OnLoseTab(TabButton c_button) { if (CurrentButton == c_button) { CurrentButton = null; } //TODO: Select a tab if any exist. if (TabRemoved != null) { TabRemoved.Invoke(this); } Invalidate(); } private void HandleOverflow() { var a_tabsSize = TabStrip.GetChildrenSize(); // Only enable the scrollers if the tabs are at the top. // This is a limitation we should explore. // Really TabControl should have derivitives for tabs placed elsewhere where we could specialize // some functions like this for each direction. var a_needed = a_tabsSize.X > Width && TabStrip.Dock == Pos.Top; m_scroll[0].IsHidden = !a_needed; m_scroll[1].IsHidden = !a_needed; if (!a_needed) { return; } m_scrollOffset = Util.Clamp(m_scrollOffset, 0, a_tabsSize.X - Width + 32); TabStrip.Margin = new Margin(m_scrollOffset * -1, 0, 0, 0); m_scroll[0].SetPosition(Width - 30, 5); m_scroll[1].SetPosition(m_scroll[0].Right, 5); } protected virtual void ScrollPressedLeft(GameControl c_control, MouseButtonEventArgs c_args) { m_scrollOffset -= 120; } protected virtual void ScrollPressedRight(GameControl c_control, MouseButtonEventArgs c_args) { m_scrollOffset += 120; } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Burrows.Util { using System; using System.Collections.Generic; /// <summary> /// Indicates that marked element should be localized or not. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public sealed class LocalizationRequiredAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class. /// </summary> /// <param name="required"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param> public LocalizationRequiredAttribute(bool required) { Required = required; } /// <summary> /// Gets a value indicating whether a element should be localized. /// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value> /// </summary> public bool Required { get; set; } /// <summary> /// Returns whether the value of the given object is equal to the current <see cref="LocalizationRequiredAttribute"/>. /// </summary> /// <param name="obj">The object to test the value equality of. </param> /// <returns> /// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { var attribute = obj as LocalizationRequiredAttribute; return attribute != null && attribute.Required == Required; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current <see cref="LocalizationRequiredAttribute"/>.</returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// Indicates that marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. /// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form /// </summary> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class StringFormatMethodAttribute : Attribute { private readonly string myFormatParameterName; /// <summary> /// Initializes new instance of StringFormatMethodAttribute /// </summary> /// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param> public StringFormatMethodAttribute(string formatParameterName) { myFormatParameterName = formatParameterName; } /// <summary> /// Gets format parameter name /// </summary> public string FormatParameterName { get { return myFormatParameterName; } } } /// <summary> /// Indicates that the function argument should be string literal and match one of the parameters of the caller function. /// For example, <see cref="ArgumentNullException"/> has such parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied. /// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute /// </summary> /// <seealso cref="AssertionConditionAttribute"/> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. /// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute. /// The mandatory argument of the attribute is the assertion type. /// </summary> /// <seealso cref="AssertionConditionType"/> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class AssertionConditionAttribute : Attribute { private readonly AssertionConditionType myConditionType; /// <summary> /// Initializes new instance of AssertionConditionAttribute /// </summary> /// <param name="conditionType">Specifies condition type</param> public AssertionConditionAttribute(AssertionConditionType conditionType) { myConditionType = conditionType; } /// <summary> /// Gets condition type /// </summary> public AssertionConditionType ConditionType { get { return myConditionType; } } } /// <summary> /// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues. /// Otherwise, execution is assumed to be halted /// </summary> public enum AssertionConditionType { /// <summary> /// Indicates that the marked parameter should be evaluated to true /// </summary> IS_TRUE = 0, /// <summary> /// Indicates that the marked parameter should be evaluated to false /// </summary> IS_FALSE = 1, /// <summary> /// Indicates that the marked parameter should be evaluated to null value /// </summary> IS_NULL = 2, /// <summary> /// Indicates that the marked parameter should be evaluated to not null value /// </summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of marked element could never be <c>null</c> /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators. /// There is only exception to compare with <c>null</c>, it is permitted /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to target attribute, specifies a requirement for any type which is marked with /// target attribute to implement or inherit specific type or types /// </summary> /// <example> /// <code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// public class ComponentAttribute : Attribute /// {} /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// public class MyComponent : IComponent /// {} /// </code> /// </example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] [BaseTypeRequired(typeof (Attribute))] public sealed class BaseTypeRequiredAttribute : Attribute { private readonly Type[] myBaseTypes; /// <summary> /// Initializes new instance of BaseTypeRequiredAttribute /// </summary> /// <param name="baseTypes">Specifies which types are required</param> public BaseTypeRequiredAttribute(params Type[] baseTypes) { myBaseTypes = baseTypes; } /// <summary> /// Gets enumerations of specified base types /// </summary> public IEnumerable<Type> BaseTypes { get { return myBaseTypes; } } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public sealed class UsedImplicitlyAttribute : Attribute { [UsedImplicitly] public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } /// <summary> /// Gets value indicating what is meant to be used /// </summary> [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } [UsedImplicitly] public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } /// <summary> /// Gets value indicating what is meant to be used /// </summary> [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] public enum ImplicitUseKindFlags { Default = Access | Assign | Instantiated, /// <summary> /// Only entity marked with attribute considered used /// </summary> Access = 1, /// <summary> /// Indicates implicit assignment to a member /// </summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type /// </summary> Instantiated = 4, } /// <summary> /// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/> /// </summary> [Flags] public enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary> /// Members of entity marked with attribute are considered used /// </summary> Members = 2, /// <summary> /// Entity marked with attribute and all its members considered used /// </summary> WithMembers = Itself | Members } }
// ------------------------------------------------------------------------------ // 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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GroupConversationsCollectionRequest. /// </summary> public partial class GroupConversationsCollectionRequest : BaseRequest, IGroupConversationsCollectionRequest { /// <summary> /// Constructs a new GroupConversationsCollectionRequest. /// </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 GroupConversationsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Conversation to the collection via POST. /// </summary> /// <param name="conversation">The Conversation to add.</param> /// <returns>The created Conversation.</returns> public System.Threading.Tasks.Task<Conversation> AddAsync(Conversation conversation) { return this.AddAsync(conversation, CancellationToken.None); } /// <summary> /// Adds the specified Conversation to the collection via POST. /// </summary> /// <param name="conversation">The Conversation to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Conversation.</returns> public System.Threading.Tasks.Task<Conversation> AddAsync(Conversation conversation, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Conversation>(conversation, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGroupConversationsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGroupConversationsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GroupConversationsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <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 IGroupConversationsCollectionRequest 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 IGroupConversationsCollectionRequest Expand(Expression<Func<Conversation, 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 IGroupConversationsCollectionRequest 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 IGroupConversationsCollectionRequest Select(Expression<Func<Conversation, 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> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGroupConversationsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGroupConversationsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGroupConversationsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGroupConversationsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Windows.Forms.Design; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; namespace TurboControl { public delegate void DigiSwitchStateChangedHandler(DigiSwitch sender, bool newState, bool newLEDState); public delegate void DigiSwitchClickHandler(DigiSwitch sender); /// <summary> /// Visible Control resembling the german DigiTast of the seventies /// </summary> [ Designer(typeof(TurboControl.NoResizeDesigner)), ToolboxBitmap(typeof(DigiSwitch), "Images.Designer.TurboControl.DigiSwitch.bmp") System.ComponentModel.DesignerCategory("") ] public class DigiSwitch : System.Windows.Forms.Control { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; protected DigiSwitchColors iColor = DigiSwitchColors.Red; protected DigiSwitchStyles iStyle = DigiSwitchStyles.Pure; protected bool iClosed = false; protected bool iStateLED = false; protected bool iAutoToggle = false; protected Bitmap ibmOpenOff; protected Bitmap ibmOpenOn; protected Bitmap ibmClosedOn; protected Bitmap ibmClosedOff; public event DigiSwitchStateChangedHandler StateChanged; public new event DigiSwitchClickHandler Click; protected System.Threading.Timer ClickTimer; public void AnimateClick() { iClosed = true; if (Click != null) Click(this); this.Invalidate(); ClickTimer = new System.Threading.Timer(new TimerCallback(this.AnimateClickEnd), null, TimeSpan.FromMilliseconds(120), TimeSpan.FromMilliseconds(120)); } public void AnimateClickEnd(Object state) { iClosed = false; this.Invalidate(); ClickTimer.Dispose(); } /// <summary> /// Initializes a red digiswitch without an LED /// </summary> public DigiSwitch() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call iColor = DigiSwitchColors.Red; iStyle = DigiSwitchStyles.Pure; this.SetDimensions(); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); UpdateStyles(); this.OpenBitmaps(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } if (ibmOpenOff != null) ibmOpenOff.Dispose(); if (ibmOpenOn != null) ibmOpenOn.Dispose(); if (ibmClosedOff != null) ibmClosedOff.Dispose(); if (ibmClosedOn != null) ibmClosedOn.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() { components = new System.ComponentModel.Container(); } #endregion [Browsable(false)] public override Font Font { get { return base.Font; } set { base.Font = value; } } [Browsable(false)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } /// <summary> /// State of the LED. If the switch does not have an LED the value is stored anyway. /// </summary> [Description("LED State")] public bool StateLED { get { return iStateLED; } set { if (iStateLED != value) { iStateLED = value; this.Invalidate(); } } } /// <summary> /// When set to true, the digiswitch will toggle the state of the LED each time it is left-clicked. /// </summary> [Description("Auto-Toggle LED on click")] public bool AutoToggle { get { return iAutoToggle; } set { iAutoToggle= value; } } /// <summary> /// Color of the switch. It is available in commercial version colors. /// </summary> [ Description("Color Style") ] public TurboControl.DigiSwitchColors StyleColor { get { return iColor; } set { if (iColor != value) { iColor = value; OpenBitmaps(); this.Invalidate(); } } } /// <summary> /// Display and color of the integrated LED. /// </summary> // [Category("Appearance")] [ Description("LED Style") ] public TurboControl.DigiSwitchStyles Style { get { return iStyle; } set { if (iStyle != value) { iStyle = value; OpenBitmaps(); this.Invalidate(); } } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown (e); iClosed = true; if (StateChanged != null) StateChanged(this,iClosed,iStateLED); this.Invalidate(); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp (e); iClosed = false; if (iAutoToggle) iStateLED = !iStateLED; if (StateChanged != null) StateChanged(this,iClosed,iStateLED); if (Click != null) Click(this); this.Invalidate(); } /// <summary> /// Set Dimensions of the control from its properties. /// </summary> protected void SetDimensions() { this.Width = 20 + 2; this.Height = 30 + 2; } protected void ClearBitmapCache() { if (ibmOpenOff != null) { ibmOpenOff.Dispose(); ibmOpenOff = null; } if (ibmOpenOn != null) { ibmOpenOn.Dispose(); ibmOpenOn = null; } if (ibmClosedOff != null) { ibmClosedOff.Dispose(); ibmClosedOff = null; } if (ibmClosedOn != null) { ibmClosedOn.Dispose(); ibmClosedOn = null; } } /// <summary> /// Set up the needed bitmaps from the properties of the control. /// </summary> protected void OpenBitmaps() { ClearBitmapCache(); string mainstr = "TurboControl.Images.DigiSwitch."; string ledstr = ""; string colstr = "red"; if (iColor == DigiSwitchColors.Green) colstr = "green"; else if (iColor == DigiSwitchColors.Blue) colstr = "blue"; else if (iColor == DigiSwitchColors.Black) colstr = "black"; else if (iColor == DigiSwitchColors.Yellow) colstr = "yellow"; if (iStyle == DigiSwitchStyles.RedLED) ledstr = "_redled"; if (iStyle == DigiSwitchStyles.GreenLED) ledstr = "_greenled"; if (iStyle == DigiSwitchStyles.Pure) { ibmOpenOff = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_open.bmp")); ibmOpenOn = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_open.bmp")); ibmClosedOff = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_closed.bmp")); ibmClosedOn = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_closed.bmp")); } else { ibmOpenOff = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_open" + ledstr + "_off.bmp")); ibmOpenOn = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_open" + ledstr + "_on.bmp")); ibmClosedOff = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_closed" + ledstr + "_off.bmp")); ibmClosedOn = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(mainstr + colstr + "_closed" + ledstr + "_on.bmp")); } } private int max ( int a, int b) { if (a>b) return a; return b; } private int min ( int a, int b) { if (b>a) return a; return b; } protected override void OnPaint(PaintEventArgs e) { //base.OnPaint (e); Color ColorTopLeft = Color.FromArgb(max(BackColor.R / 2,0),max(BackColor.G / 2,0),max(BackColor.B / 2,0)); Color ColorBottomRight = Color.FromArgb(min((int)(BackColor.R * 1.5),255),min((int)(BackColor.G * 1.5),255),min((int)(BackColor.B * 1.5),255)); Pen PenTopLeft = new Pen(new SolidBrush(ColorTopLeft),1); Pen PenBottomRight = new Pen(new SolidBrush(ColorBottomRight),1); e.Graphics.DrawRectangle(PenBottomRight,0,0,this.Width-1,this.Height-1); e.Graphics.DrawRectangle(PenTopLeft,0,0,this.Width-2,this.Height-2); if (iClosed) { if (iStateLED) { e.Graphics.DrawImage(ibmClosedOn,1,1,this.Width-2,this.Height-2); } else { e.Graphics.DrawImage(ibmClosedOff,1,1,this.Width-2,this.Height-2); } } else { if (iStateLED) { e.Graphics.DrawImage(ibmOpenOn,1,1,this.Width-2,this.Height-2); } else { e.Graphics.DrawImage(ibmOpenOff,1,1,this.Width-2,this.Height-2); } } } } /// <summary> /// Color options used for digiswitch controls. /// </summary> public enum DigiSwitchColors { Black, Blue, Green, Red, Yellow } /// <summary> /// LED color options for digiswitch controls. /// </summary> public enum DigiSwitchStyles { Pure, RedLED, GreenLED } }
// 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.Text; using System.Reflection; using System.Globalization; using System.Collections.Generic; using System.Configuration.Assemblies; using System.Runtime.Serialization; using System.IO; #if FEATURE_ASSEMBLYLOADCONTEXT using System.Reflection.PortableExecutable; using System.Reflection.Metadata; #endif namespace Microsoft.Build.Shared { /// <summary> /// Specifies the parts of the assembly name to partially match /// </summary> [FlagsAttribute] internal enum PartialComparisonFlags : int { /// <summary> /// Compare SimpleName A.PartialCompare(B,SimpleName) match the simple name on A and B if the simple name on A is not null. /// </summary> SimpleName = 1, // 0000 0000 0000 0001 /// <summary> /// Compare Version A.PartialCompare(B, Version) match the Version on A and B if the Version on A is not null. /// </summary> Version = 2, // 0000 0000 0000 0010 /// <summary> /// Compare Culture A.PartialCompare(B, Culture) match the Culture on A and B if the Culture on A is not null. /// </summary> Culture = 4, // 0000 0000 0000 0100 /// <summary> /// Compare PublicKeyToken A.PartialCompare(B, PublicKeyToken) match the PublicKeyToken on A and B if the PublicKeyToken on A is not null. /// </summary> PublicKeyToken = 8, // 0000 0000 0000 1000 /// <summary> /// When doing a comparison A.PartialCompare(B, Default) compare all fields of A which are not null with B. /// </summary> Default = 15, // 0000 0000 0000 1111 } /// <summary> /// A replacement for AssemblyName that optimizes calls to FullName which is expensive. /// The assembly name is represented internally by an AssemblyName and a string, conversion /// between the two is done lazily on demand. /// </summary> [Serializable] internal sealed class AssemblyNameExtension : ISerializable, IEquatable<AssemblyNameExtension> { private AssemblyName asAssemblyName = null; private string asString = null; private bool isSimpleName = false; private bool hasProcessorArchitectureInFusionName; private bool immutable; /// <summary> /// Set of assemblyNameExtensions that THIS assemblyname was remapped from. /// </summary> private HashSet<AssemblyNameExtension> remappedFrom; private static readonly AssemblyNameExtension s_unnamedAssembly = new AssemblyNameExtension(); /// <summary> /// Construct an unnamed assembly. /// Private because we want only one of these. /// </summary> private AssemblyNameExtension() { } /// <summary> /// Construct with AssemblyName. /// </summary> /// <param name="assemblyName"></param> internal AssemblyNameExtension(AssemblyName assemblyName) : this() { asAssemblyName = assemblyName; } /// <summary> /// Construct with string. /// </summary> /// <param name="assemblyName"></param> internal AssemblyNameExtension(string assemblyName) : this() { asString = assemblyName; } /// <summary> /// Construct from a string, but immediately construct a real AssemblyName. /// This will cause an exception to be thrown up front if the assembly name /// isn't well formed. /// </summary> /// <param name="assemblyName"> /// The string version of the assembly name. /// </param> /// <param name="validate"> /// Used when the assembly name comes from a user-controlled source like a project file or config file. /// Does extra checking on the assembly name and will throw exceptions if something is invalid. /// </param> internal AssemblyNameExtension(string assemblyName, bool validate) : this() { asString = assemblyName; if (validate) { // This will throw... CreateAssemblyName(); } } /// <summary> /// Ctor for deserializing from state file (binary serialization). /// <remarks>This is required because AssemblyName is not Serializable on .NET Core.</remarks> /// </summary> /// <param name="info"></param> /// <param name="context"></param> private AssemblyNameExtension(SerializationInfo info, StreamingContext context) { var hasAssemblyName = info.GetBoolean("hasAN"); if (hasAssemblyName) { var name = info.GetString("name"); var publicKey = (byte[]) info.GetValue("pk", typeof(byte[])); var publicKeyToken = (byte[]) info.GetValue("pkt", typeof(byte[])); var version = (Version)info.GetValue("ver", typeof(Version)); var flags = (AssemblyNameFlags) info.GetInt32("flags"); var processorArchitecture = (ProcessorArchitecture) info.GetInt32("cpuarch"); CultureInfo cultureInfo = null; var hasCultureInfo = info.GetBoolean("hasCI"); if (hasCultureInfo) { cultureInfo = new CultureInfo(info.GetInt32("ci")); } var hashAlgorithm = (System.Configuration.Assemblies.AssemblyHashAlgorithm) info.GetInt32("hashAlg"); var versionCompatibility = (AssemblyVersionCompatibility) info.GetInt32("verCompat"); var codeBase = info.GetString("codebase"); var keyPair = (StrongNameKeyPair) info.GetValue("keypair", typeof(StrongNameKeyPair)); asAssemblyName = new AssemblyName { Name = name, Version = version, Flags = flags, ProcessorArchitecture = processorArchitecture, CultureInfo = cultureInfo, HashAlgorithm = hashAlgorithm, VersionCompatibility = versionCompatibility, CodeBase = codeBase, KeyPair = keyPair }; asAssemblyName.SetPublicKey(publicKey); asAssemblyName.SetPublicKeyToken(publicKeyToken); } asString = info.GetString("asStr"); isSimpleName = info.GetBoolean("isSName"); hasProcessorArchitectureInFusionName = info.GetBoolean("hasCpuArch"); immutable = info.GetBoolean("immutable"); remappedFrom = (HashSet<AssemblyNameExtension>) info.GetValue("remapped", typeof(HashSet<AssemblyNameExtension>)); } /// <summary> /// To be used as a delegate. Gets the AssemblyName of the given file. /// </summary> /// <param name="path"></param> /// <returns></returns> internal static AssemblyNameExtension GetAssemblyNameEx(string path) { AssemblyName assemblyName = null; #if !FEATURE_ASSEMBLYLOADCONTEXT try { assemblyName = AssemblyName.GetAssemblyName(path); } catch (FileLoadException) { // Its pretty hard to get here, you need an assembly that contains a valid reference // to a dependent assembly that, in turn, throws a FileLoadException during GetAssemblyName. // Still it happened once, with an older version of the CLR. // ...falling through and relying on the assemblyName == null behavior below... } catch (FileNotFoundException) { // Its pretty hard to get here, also since we do a file existence check right before calling this method so it can only happen if the file got deleted between that check and this call. } #else using (var stream = File.OpenRead(path)) using (var peFile = new PEReader(stream)) { bool hasMetadata = false; try { // This can throw if the stream is too small, which means // the assembly doesn't have metadata. hasMetadata = peFile.HasMetadata; } finally { // If the file does not contain PE metadata, throw BadImageFormatException to preserve // behavior from AssemblyName.GetAssemblyName(). RAR will deal with this correctly. if (!hasMetadata) { throw new BadImageFormatException(string.Format(CultureInfo.CurrentCulture, AssemblyResources.GetString("ResolveAssemblyReference.AssemblyDoesNotContainPEMetadata"), path)); } } var metadataReader = peFile.GetMetadataReader(); var entry = metadataReader.GetAssemblyDefinition(); assemblyName = new AssemblyName(); assemblyName.Name = metadataReader.GetString(entry.Name); assemblyName.Version = entry.Version; assemblyName.CultureName = metadataReader.GetString(entry.Culture); assemblyName.SetPublicKey(metadataReader.GetBlobBytes(entry.PublicKey)); assemblyName.Flags = (AssemblyNameFlags)(int)entry.Flags; } #endif return assemblyName == null ? null : new AssemblyNameExtension(assemblyName); } /// <summary> /// Run after the object has been deserialized /// </summary> [OnDeserialized] private void SetRemappedFromDefaultAfterSerialization(StreamingContext sc) { InitializeRemappedFrom(); } /// <summary> /// Initialize the remapped from structure. /// </summary> private void InitializeRemappedFrom() { if (remappedFrom == null) { remappedFrom = new HashSet<AssemblyNameExtension>(AssemblyNameComparer.GenericComparerConsiderRetargetable); } } /// <summary> /// Assume there is a string version, create the AssemblyName version. /// </summary> private void CreateAssemblyName() { if (asAssemblyName == null) { asAssemblyName = GetAssemblyNameFromDisplayName(asString); if (asAssemblyName != null) { hasProcessorArchitectureInFusionName = asString.IndexOf("ProcessorArchitecture", StringComparison.OrdinalIgnoreCase) != -1; isSimpleName = ((Version == null) && (CultureInfo == null) && (GetPublicKeyToken() == null) && (!hasProcessorArchitectureInFusionName)); } } } /// <summary> /// Assume there is a string version, create the AssemblyName version. /// </summary> private void CreateFullName() { if (asString == null) { asString = asAssemblyName.FullName; } } /// <summary> /// The base name of the assembly. /// </summary> /// <value></value> internal string Name { get { // Is there a string? CreateAssemblyName(); return asAssemblyName.Name; } } /// <summary> /// Gets the backing AssemblyName, this can be None. /// </summary> internal ProcessorArchitecture ProcessorArchitecture => asAssemblyName?.ProcessorArchitecture ?? ProcessorArchitecture.None; /// <summary> /// The assembly's version number. /// </summary> /// <value></value> internal Version Version { get { // Is there a string? CreateAssemblyName(); return asAssemblyName.Version; } } /// <summary> /// Is the assembly a complex name or a simple name. A simple name is where only the name is set /// a complex name is where the version, culture or publickeytoken is also set /// </summary> internal bool IsSimpleName { get { CreateAssemblyName(); return isSimpleName; } } /// <summary> /// Does the fullName have the processor architecture defined /// </summary> internal bool HasProcessorArchitectureInFusionName { get { CreateAssemblyName(); return hasProcessorArchitectureInFusionName; } } /// <summary> /// Replace the current version with a new version. /// </summary> /// <param name="version"></param> internal void ReplaceVersion(Version version) { ErrorUtilities.VerifyThrow(!immutable, "Object is immutable cannot replace the version"); CreateAssemblyName(); if (asAssemblyName.Version != version) { asAssemblyName.Version = version; // String would now be invalid. asString = null; } } /// <summary> /// The assembly's Culture /// </summary> /// <value></value> internal CultureInfo CultureInfo { get { // Is there a string? CreateAssemblyName(); return asAssemblyName.CultureInfo; } } /// <summary> /// The assembly's retargetable bit /// </summary> /// <value></value> internal bool Retargetable { get { // Is there a string? CreateAssemblyName(); // Cannot use the HasFlag method on the Flags enum because this class needs to work with 3.5 return (asAssemblyName.Flags & AssemblyNameFlags.Retargetable) == AssemblyNameFlags.Retargetable; } } /// <summary> /// The full name of the original extension we were before being remapped. /// </summary> internal IEnumerable<AssemblyNameExtension> RemappedFromEnumerator { get { InitializeRemappedFrom(); return remappedFrom; } } /// <summary> /// Add an assemblyNameExtension which represents an assembly name which was mapped to THIS assemblyName. /// </summary> internal void AddRemappedAssemblyName(AssemblyNameExtension extensionToAdd) { ErrorUtilities.VerifyThrow(extensionToAdd.Immutable, "ExtensionToAdd is not immutable"); InitializeRemappedFrom(); remappedFrom.Add(extensionToAdd); } /// <summary> /// As an AssemblyName /// </summary> /// <value></value> internal AssemblyName AssemblyName { get { // Is there a string? CreateAssemblyName(); return asAssemblyName; } } /// <summary> /// The assembly's full name. /// </summary> /// <value></value> internal string FullName { get { // Is there a string? CreateFullName(); return asString; } } /// <summary> /// Get the assembly's public key token. /// </summary> /// <returns></returns> internal byte[] GetPublicKeyToken() { // Is there a string? CreateAssemblyName(); return asAssemblyName.GetPublicKeyToken(); } /// <summary> /// A special "unnamed" instance of AssemblyNameExtension. /// </summary> /// <value></value> internal static AssemblyNameExtension UnnamedAssembly => s_unnamedAssembly; /// <summary> /// Compare one assembly name to another. /// </summary> /// <param name="that"></param> /// <returns></returns> internal int CompareTo(AssemblyNameExtension that) { return CompareTo(that, false); } /// <summary> /// Compare one assembly name to another. /// </summary> internal int CompareTo(AssemblyNameExtension that, bool considerRetargetableFlag) { // Are they identical? if (this.Equals(that, considerRetargetableFlag)) { return 0; } // Are the base names not identical? int result = CompareBaseNameTo(that); if (result != 0) { return result; } // We would like to compare the version numerically rather than alphabetically (because for example version 10.0.0. should be below 9 not between 1 and 2) if (this.Version != that.Version) { if (this.Version == null) { // This is therefore less than that. Since this is null and that is not null return -1; } // Will not return 0 as the this != that check above takes care of the case where they are equal. return this.Version.CompareTo(that.Version); } // We need some final collating order for these, alphabetical by FullName seems as good as any. return string.Compare(this.FullName, that.FullName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Get a hash code for this assembly name. /// </summary> /// <returns></returns> internal new int GetHashCode() { // Ok, so this isn't a great hashing algorithm. However, basenames with different // versions or PKTs are relatively uncommon and so collisions should be low. // Hashing on FullName is wrong because the order of tuple fields is undefined. int hash = StringComparer.OrdinalIgnoreCase.GetHashCode(this.Name); return hash; } /// <summary> /// Compare two base names as quickly as possible. /// </summary> /// <param name="that"></param> /// <returns></returns> internal int CompareBaseNameTo(AssemblyNameExtension that) { int result = CompareBaseNameToImpl(that); #if DEBUG // Now, compare to the real value to make sure the result was accurate. AssemblyName a1 = asAssemblyName; AssemblyName a2 = that.asAssemblyName; if (a1 == null) { a1 = new AssemblyName(asString); } if (a2 == null) { a2 = new AssemblyName(that.asString); } int baselineResult = string.Compare(a1.Name, a2.Name, StringComparison.OrdinalIgnoreCase); ErrorUtilities.VerifyThrow(result == baselineResult, "Optimized version of CompareBaseNameTo didn't return the same result as the baseline."); #endif return result; } /// <summary> /// An implementation of compare that compares two base /// names as quickly as possible. /// </summary> /// <param name="that"></param> /// <returns></returns> private int CompareBaseNameToImpl(AssemblyNameExtension that) { // Pointer compare, if identical then base names are equal. if (this == that) { return 0; } // Do both have assembly names? if (asAssemblyName != null && that.asAssemblyName != null) { // Pointer compare or base name compare. return asAssemblyName == that.asAssemblyName ? 0 : string.Compare(asAssemblyName.Name, that.asAssemblyName.Name, StringComparison.OrdinalIgnoreCase); } // Do both have strings? if (asString != null && that.asString != null) { // If we have two random-case strings, then we need to compare case sensitively. return CompareBaseNamesStringWise(asString, that.asString); } // Fall back to comparing by name. This is the slow path. return string.Compare(this.Name, that.Name, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Compare two basenames. /// </summary> /// <param name="asString1"></param> /// <param name="asString2"></param> /// <returns></returns> private static int CompareBaseNamesStringWise(string asString1, string asString2) { // Identical strings just match. if (asString1 == asString2) { return 0; } // Get the lengths of base names to compare. int baseLenThis = asString1.IndexOf(','); int baseLenThat = asString2.IndexOf(','); if (baseLenThis == -1) { baseLenThis = asString1.Length; } if (baseLenThat == -1) { baseLenThat = asString2.Length; } // If the lengths are the same then we can compare without copying. if (baseLenThis == baseLenThat) { return string.Compare(asString1, 0, asString2, 0, baseLenThis, StringComparison.OrdinalIgnoreCase); } // Lengths are different, so string copy is required. string nameThis = asString1.Substring(0, baseLenThis); string nameThat = asString2.Substring(0, baseLenThat); return string.Compare(nameThis, nameThat, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Clone this assemblyNameExtension /// </summary> internal AssemblyNameExtension Clone() { AssemblyNameExtension newExtension = new AssemblyNameExtension(); if (asAssemblyName != null) { newExtension.asAssemblyName = asAssemblyName.CloneIfPossible(); } newExtension.asString = asString; newExtension.isSimpleName = isSimpleName; newExtension.hasProcessorArchitectureInFusionName = hasProcessorArchitectureInFusionName; newExtension.remappedFrom = remappedFrom; // We are cloning so we can now party on the object even if the parent was immutable newExtension.immutable = false; return newExtension; } /// <summary> /// Clone the object but mark and mark the cloned object as immutable /// </summary> /// <returns></returns> internal AssemblyNameExtension CloneImmutable() { AssemblyNameExtension clonedExtension = Clone(); clonedExtension.MarkImmutable(); return clonedExtension; } /// <summary> /// Is this object immutable /// </summary> public bool Immutable => immutable; /// <summary> /// Mark this object as immutable /// </summary> internal void MarkImmutable() { immutable = true; } /// <summary> /// Compare two assembly names for equality. /// </summary> /// <param name="that"></param> /// <returns></returns> internal bool Equals(AssemblyNameExtension that) { return EqualsImpl(that, false, false); } /// <summary> /// Interface method for IEquatable&lt;AssemblyNameExtension&gt; /// </summary> /// <param name="other"></param> /// <returns></returns> bool IEquatable<AssemblyNameExtension>.Equals(AssemblyNameExtension other) { return Equals(other); } /// <summary> /// Compare two assembly names for equality ignoring version. /// </summary> /// <param name="that"></param> /// <returns></returns> internal bool EqualsIgnoreVersion(AssemblyNameExtension that) { return EqualsImpl(that, true, false); } /// <summary> /// Compare two assembly names and consider the retargetable flag during the comparison /// </summary> internal bool Equals(AssemblyNameExtension that, bool considerRetargetableFlag) { return EqualsImpl(that, false, considerRetargetableFlag); } /// <summary> /// Compare two assembly names for equality. /// </summary> private bool EqualsImpl(AssemblyNameExtension that, bool ignoreVersion, bool considerRetargetableFlag) { // Pointer compare. if (object.ReferenceEquals(this, that)) { return true; } // If that is null then this and that are not equal. Also, this would cause a crash on the next line. if (that is null) { return false; } // Do both have assembly names? if (asAssemblyName != null && that.asAssemblyName != null) { // Pointer compare. if (object.ReferenceEquals(asAssemblyName, that.asAssemblyName)) { return true; } } // Do both have strings that equal each-other? if (asString != null && that.asString != null) { if (asString == that.asString) { return true; } // If they weren't identical then they might still differ only by // case. So we can't assume that they don't match. So fall through... } // Do the names match? if (!string.Equals(Name, that.Name, StringComparison.OrdinalIgnoreCase)) { return false; } if (!ignoreVersion && (this.Version != that.Version)) { return false; } if (!CompareCultures(AssemblyName, that.AssemblyName)) { return false; } if (!ComparePublicKeyToken(that)) { return false; } if (considerRetargetableFlag && this.Retargetable != that.Retargetable) { return false; } return true; } /// <summary> /// Allows the comparison of the culture. /// </summary> internal static bool CompareCultures(AssemblyName a, AssemblyName b) { // Do the Cultures match? CultureInfo aCulture = a.CultureInfo; CultureInfo bCulture = b.CultureInfo; if (aCulture == null) { aCulture = CultureInfo.InvariantCulture; } if (bCulture == null) { bCulture = CultureInfo.InvariantCulture; } return aCulture.LCID == bCulture.LCID; } /// <summary> /// Allows the comparison of just the PublicKeyToken /// </summary> internal bool ComparePublicKeyToken(AssemblyNameExtension that) { // Do the PKTs match? byte[] aPKT = GetPublicKeyToken(); byte[] bPKT = that.GetPublicKeyToken(); return ComparePublicKeyTokens(aPKT, bPKT); } /// <summary> /// Compare two public key tokens. /// </summary> internal static bool ComparePublicKeyTokens(byte[] aPKT, byte[] bPKT) { // Some assemblies (real case was interop assembly) may have null PKTs. if (aPKT == null) { aPKT = new byte[0]; } if (bPKT == null) { bPKT = new byte[0]; } if (aPKT.Length != bPKT.Length) { return false; } for (int i = 0; i < aPKT.Length; ++i) { if (aPKT[i] != bPKT[i]) { return false; } } return true; } /// <summary> /// Only the unnamed assembly has both null assemblyname and null string. /// </summary> /// <returns></returns> internal bool IsUnnamedAssembly => asAssemblyName == null && asString == null; /// <summary> /// Given a display name, construct an assembly name. /// </summary> /// <param name="displayName">The display name.</param> /// <returns>The assembly name.</returns> private static AssemblyName GetAssemblyNameFromDisplayName(string displayName) { AssemblyName assemblyName = new AssemblyName(displayName); return assemblyName; } /// <summary> /// Return a string that has AssemblyName special characters escaped. /// Those characters are Equals(=), Comma(,), Quote("), Apostrophe('), Backslash(\). /// </summary> /// <remarks> /// WARNING! This method is not meant as a general purpose escaping method for assembly names. /// Use only if you really know that this does what you need. /// </remarks> /// <param name="displayName"></param> /// <returns></returns> internal static string EscapeDisplayNameCharacters(string displayName) { StringBuilder sb = new StringBuilder(displayName); sb = sb.Replace("\\", "\\\\"); sb = sb.Replace("=", "\\="); sb = sb.Replace(",", "\\,"); sb = sb.Replace("\"", "\\\""); sb = sb.Replace("'", "\\'"); return sb.ToString(); } /// <summary> /// Convert to a string for display. /// </summary> /// <returns></returns> public override string ToString() { CreateFullName(); return asString; } /// <summary> /// Compare the fields of this with that if they are not null. /// </summary> internal bool PartialNameCompare(AssemblyNameExtension that) { return PartialNameCompare(that, PartialComparisonFlags.Default, false /* do not consider retargetable flag*/); } /// <summary> /// Compare the fields of this with that if they are not null. /// </summary> internal bool PartialNameCompare(AssemblyNameExtension that, bool considerRetargetableFlag) { return PartialNameCompare(that, PartialComparisonFlags.Default, considerRetargetableFlag); } /// <summary> /// Do a partial comparison between two assembly name extensions. /// Compare the fields of A and B on the following conditions: /// 1) A.Field has a non null value /// 2) The field has been selected in the comparison flags or the default comparison flags are passed in. /// /// If A.Field is null then we will not compare A.Field and B.Field even when the comparison flag is set for that field unless skipNullFields is false. /// </summary> internal bool PartialNameCompare(AssemblyNameExtension that, PartialComparisonFlags comparisonFlags) { return PartialNameCompare(that, comparisonFlags, false /* do not consider retargetable flag*/); } /// <summary> /// Do a partial comparison between two assembly name extensions. /// Compare the fields of A and B on the following conditions: /// 1) A.Field has a non null value /// 2) The field has been selected in the comparison flags or the default comparison flags are passed in. /// /// If A.Field is null then we will not compare A.Field and B.Field even when the comparison flag is set for that field unless skipNullFields is false. /// </summary> internal bool PartialNameCompare(AssemblyNameExtension that, PartialComparisonFlags comparisonFlags, bool considerRetargetableFlag) { // Pointer compare. if (object.ReferenceEquals(this, that)) { return true; } // If that is null then this and that are not equal. Also, this would cause a crash on the next line. if (that is null) { return false; } // Do both have assembly names? if (asAssemblyName != null && that.asAssemblyName != null) { // Pointer compare. if (object.ReferenceEquals(asAssemblyName, that.asAssemblyName)) { return true; } } // Do the names match? if ((comparisonFlags & PartialComparisonFlags.SimpleName) != 0 && Name != null && !string.Equals(Name, that.Name, StringComparison.OrdinalIgnoreCase)) { return false; } if ((comparisonFlags & PartialComparisonFlags.Version) != 0 && Version != null && this.Version != that.Version) { return false; } if ((comparisonFlags & PartialComparisonFlags.Culture) != 0 && CultureInfo != null && (that.CultureInfo == null || !CompareCultures(AssemblyName, that.AssemblyName))) { return false; } if ((comparisonFlags & PartialComparisonFlags.PublicKeyToken) != 0 && GetPublicKeyToken() != null && !ComparePublicKeyToken(that)) { return false; } if (considerRetargetableFlag && (Retargetable != that.Retargetable)) { return false; } return true; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("hasAN", asAssemblyName != null); if (asAssemblyName != null) { info.AddValue("name", asAssemblyName.Name); info.AddValue("pk", asAssemblyName.GetPublicKey()); info.AddValue("pkt", asAssemblyName.GetPublicKeyToken()); info.AddValue("ver", asAssemblyName.Version); info.AddValue("flags", (int) asAssemblyName.Flags); info.AddValue("cpuarch", (int) asAssemblyName.ProcessorArchitecture); info.AddValue("hasCI", asAssemblyName.CultureInfo != null); if (asAssemblyName.CultureInfo != null) { info.AddValue("ci", asAssemblyName.CultureInfo.LCID); } info.AddValue("hashAlg", asAssemblyName.HashAlgorithm); info.AddValue("verCompat", asAssemblyName.VersionCompatibility); info.AddValue("codebase", asAssemblyName.CodeBase); info.AddValue("keypair", asAssemblyName.KeyPair); } info.AddValue("asStr", asString); info.AddValue("isSName", isSimpleName); info.AddValue("hasCpuArch", hasProcessorArchitectureInFusionName); info.AddValue("immutable", immutable); info.AddValue("remapped", remappedFrom); } } }
// 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.AcceptanceTestsBodyFile { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Files operations. /// </summary> public partial class Files : IServiceOperations<AutoRestSwaggerBATFileService>, IFiles { /// <summary> /// Initializes a new instance of the Files class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Files(AutoRestSwaggerBATFileService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestSwaggerBATFileService /// </summary> public AutoRestSwaggerBATFileService Client { get; private set; } /// <summary> /// Get file /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.IO.Stream>> GetFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetFile", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/nonempty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<System.IO.Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty file /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.IO.Stream>> GetEmptyFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmptyFile", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<System.IO.Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } 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.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class ToArrayTests { public class ToArray006 { private static int ToArray001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.ToArray<int>(); var rst2 = q.ToArray<int>(); return Verification.Allequal(rst1, rst2); } private static int ToArray002() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; var rst1 = q.ToArray<string>(); var rst2 = q.ToArray<string>(); return Verification.Allequal(rst1, rst2); } public static int Main() { int ret = RunTest(ToArray001) + RunTest(ToArray002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToArray1 { // source is of type ICollection and source is empty public static int Test1() { int[] source = { }; int[] expected = { }; ICollection<int> collection = source as ICollection<int>; if (collection == null) return 1; var actual = source.ToArray(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToArray2 { // source is of type ICollection and source has few elements public static int Test2() { int?[] source = { -5, null, 0, 10, 3, -1, null, 4, 9 }; int?[] expected = { -5, null, 0, 10, 3, -1, null, 4, 9 }; ICollection<int?> collection = source as ICollection<int?>; if (collection == null) return 1; var actual = source.ToArray(); return Verification.Allequal(expected, actual); } public static int Main() { return Test2(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToArray3 { // source is NOT of type ICollection and source is empty public static int Test3() { IEnumerable<int> source = Functions.NumList(-4, 0); int[] expected = { }; ICollection<int> collection = source as ICollection<int>; if (collection != null) return 1; var actual = source.ToArray(); return Verification.Allequal(expected, actual); } public static int Main() { return Test3(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToArray4 { // source is NOT of type ICollection and source has few elements public static int Test4() { IEnumerable<int> source = Functions.NumList(-4, 10); int[] expected = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }; ICollection<int> collection = source as ICollection<int>; if (collection != null) return 1; var actual = source.ToArray(); return Verification.Allequal(expected, actual); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ToArray5 { // source is NOT of type ICollection and source has null elements only public static int Test5() { IEnumerable<int?> source = Functions.NullSeq(5); int?[] expected = { null, null, null, null, null }; ICollection<int?> collection = source as ICollection<int?>; if (collection != null) return 1; var actual = source.ToArray(); return Verification.Allequal(expected, actual); } public static int Main() { return Test5(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; using Pomona.Common; using CustomAttributeNamedArgument = Mono.Cecil.CustomAttributeNamedArgument; using FieldAttributes = Mono.Cecil.FieldAttributes; using MethodAttributes = Mono.Cecil.MethodAttributes; using ParameterAttributes = Mono.Cecil.ParameterAttributes; using PropertyAttributes = Mono.Cecil.PropertyAttributes; using TypeAttributes = Mono.Cecil.TypeAttributes; namespace Pomona.CodeGen { /// <summary> /// A class that builds classes that looks like C# anonymous types runtime. /// This is a huge mess, but implemented to make .Select(x => new { ... }) /// queries dynamically. /// /// Write only code. Seriously, don't read, your eyes will burn. /// </summary> public class AnonymousTypeBuilder { private static int anonTypeNumber = 100; private static readonly ConcurrentDictionary<string, Type> anonTypeCache = new ConcurrentDictionary<string, Type>(); private readonly IList<Property> properties; private TypeDefinition definition; private GenericInstanceType ilFieldDeclaringType; private ModuleDefinition module; public AnonymousTypeBuilder(IEnumerable<string> propNames) { this.properties = propNames.Select((x, i) => new Property { Index = i, Name = x }).ToList(); } private int PropCount => this.properties.Count; public TypeDefinition BuildAnonymousType() { var assemblyName = "dyn" + Guid.NewGuid().ToString(); var dynamicAssembly = AssemblyDefinition.CreateAssembly( new AssemblyNameDefinition(assemblyName, new Version(1, 0)), assemblyName, ModuleKind.Dll); this.module = dynamicAssembly.MainModule; this.module.Architecture = TargetArchitecture.I386; this.module.Attributes = ModuleAttributes.ILOnly; AddAssemblyAttributes(); this.definition = new TypeDefinition( "", $"<>f__AnonymousType{AllocateUniqueAnonymousClassNumber()}`{PropCount}", TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, this.module.TypeSystem.Object); AddGenericParams(); this.module.Types.Add(this.definition); foreach (var prop in this.properties) AddProperty(prop); AddConstructor(); AddGetHashCode(); AddEquals(); AddToString(); AddDebuggerDisplayAttribute(); AddCompilerGeneratedAttribute(); AddDebuggerBrowseableAttributesToFields(); return this.definition; } public static object CreateAnonymousObject<T>(IEnumerable<T> source, Func<T, string> nameSelector, Func<T, object> valueSelector, Func<T, Type> typeSelector) { var sourceList = source as IList<T> ?? source.ToList(); var anonType = GetAnonymousType(sourceList.Select(nameSelector)); var typeArguments = sourceList.Select(typeSelector).ToArray(); var anonTypeInstance = anonType.MakeGenericType(typeArguments); var constructorInfo = anonTypeInstance.GetConstructor(typeArguments); if (constructorInfo == null) throw new InvalidOperationException("Did not find expected constructor on anonymous type."); return constructorInfo.Invoke(sourceList.Select(valueSelector).ToArray()); } public static Expression CreateNewExpression(IEnumerable<KeyValuePair<string, Expression>> map, out Type anonTypeInstance) { var kvpList = map.ToList(); var propNames = kvpList.Select(x => x.Key); var anonType = GetAnonymousType(propNames); var typeArguments = kvpList.Select(x => x.Value.Type).ToArray(); anonTypeInstance = anonType.MakeGenericType(typeArguments); var constructorInfo = anonTypeInstance.GetConstructor(typeArguments); if (constructorInfo == null) throw new InvalidOperationException("Did not find expected constructor on anonymous type."); var anonTypeLocal = anonTypeInstance; return Expression.New( constructorInfo, kvpList.Select(x => x.Value), kvpList.Select(x => anonTypeLocal.GetProperty(x.Key))); } public MethodReference MakeHostInstanceGeneric(MethodReference self, params TypeReference[] arguments) { /* var returnType = self.ReturnType; if (returnType is GenericInstanceType) returnType = ReplaceGenericArguments((GenericInstanceType)self.ReturnType, self.DeclaringType, arguments); */ var reference = new MethodReference( self.Name, self.ReturnType, self.DeclaringType.MakeGenericInstanceType(arguments)) { HasThis = self.HasThis, ExplicitThis = self.ExplicitThis, CallingConvention = self.CallingConvention }; foreach (var parameter in self.Parameters) reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); foreach (var generic_parameter in self.GenericParameters) reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); return this.module.Import(reference, this.ilFieldDeclaringType); } public static void ScanAssemblyForExistingAnonymousTypes(Assembly assembly) { var anonTypes = assembly.GetTypes().Where(x => x.IsAnonymous()).ToList(); foreach (var anonType in anonTypes) { var typeKey = GetAnonTypeKey(anonType.GetConstructors().Single().GetParameters().Select(x => x.Name)); anonTypeCache[typeKey] = anonType; } } private void AddAssemblyAttributes() { AddRuntimeCompabilityAttributeToAssembly(); AddCompilationRelaxationsAttributeToAssembly(); } private void AddCompilationRelaxationsAttributeToAssembly() { var attrType = this.module.Import(typeof(CompilationRelaxationsAttribute)); var methodDefinition = this.module.Import(attrType.Resolve().Methods.First(x => x.IsConstructor && x.Parameters.Count == 1)); var attr = new CustomAttribute(methodDefinition); attr.ConstructorArguments.Add(new CustomAttributeArgument(this.module.TypeSystem.Int32, 8)); this.module.Assembly.CustomAttributes.Add(attr); } private void AddCompilerGeneratedAttribute() { var attrType = this.module.Import(typeof(CompilerGeneratedAttribute)); var methodDefinition = this.module.Import(attrType.Resolve().Methods.First(x => x.IsConstructor && x.Parameters.Count == 0)); var attr = new CustomAttribute(methodDefinition); this.definition.CustomAttributes.Add(attr); } private void AddConstructor() { var baseCtor = this.module.Import(this.module.TypeSystem.Object.Resolve().GetConstructors().First()); const MethodAttributes methodAttributes = MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var ctor = new MethodDefinition( ".ctor", methodAttributes, this.module.TypeSystem.Void); foreach (var prop in this.properties) { prop.CtorParameter = new ParameterDefinition(prop.Name, ParameterAttributes.None, prop.GenericParameter); ctor.Parameters.Add(prop.CtorParameter); } var ctorBody = ctor.Body; ctorBody.MaxStackSize = 8; var ilproc = ctorBody.GetILProcessor(); ilproc.Emit(OpCodes.Ldarg_0); ilproc.Emit(OpCodes.Call, baseCtor); foreach (var prop in this.properties) { ilproc.Emit(OpCodes.Ldarg_0); ilproc.Emit(OpCodes.Ldarg, prop.CtorParameter); ilproc.Emit(OpCodes.Stfld, prop.FieldIlReference); } ilproc.Emit(OpCodes.Ret); this.definition.Methods.Add(ctor); } private void AddDebuggerBrowseableAttributesToFields() { var attrType = this.module.Import(typeof(DebuggerBrowsableAttribute)); var methodDefinition = this.module.Import(attrType.Resolve().Methods.First(x => x.IsConstructor && x.Parameters.Count == 1)); foreach (var prop in this.properties) { var attr = new CustomAttribute(methodDefinition); attr.ConstructorArguments.Add( new CustomAttributeArgument(this.module.TypeSystem.String, DebuggerBrowsableState.Never)); prop.Field.CustomAttributes.Add(attr); } } private void AddDebuggerDisplayAttribute() { // \{ Foo = {Foo}, Bar = {Bar} } var attrValue = $"\\{{ {string.Join(", ", this.properties.Select(x => string.Format("{0} = {{{0}}}", x.Name)))} }}"; var attrType = this.module.Import(typeof(DebuggerDisplayAttribute)); var methodDefinition = this.module.Import(attrType.Resolve().Methods.First(x => x.IsConstructor && x.Parameters.Count == 1)); var attr = new CustomAttribute(methodDefinition); attr.ConstructorArguments.Add(new CustomAttributeArgument(this.module.TypeSystem.String, attrValue)); this.definition.CustomAttributes.Add(attr); } private void AddEquals() { var method = new MethodDefinition( "Equals", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, this.module.TypeSystem.Boolean); method.Body.MaxStackSize = 5; method.Body.InitLocals = true; var otherArg = new ParameterDefinition("value", ParameterAttributes.None, this.module.TypeSystem.Object); method.Parameters.Add(otherArg); var otherVar = new VariableDefinition(this.ilFieldDeclaringType); method.Body.Variables.Add(otherVar); var isEqualVar = new VariableDefinition(this.module.TypeSystem.Int32); method.Body.Variables.Add(isEqualVar); var il = method.Body.GetILProcessor(); var setToFalseInstruction = Instruction.Create(OpCodes.Ldc_I4_0); //IL_0000: ldarg.1 il.Emit(OpCodes.Ldarg, otherArg); //IL_0001: isinst class '<>f__AnonymousType0`2'<!'<Lo>j__TPar', !'<La>j__TPar'> il.Emit(OpCodes.Isinst, this.ilFieldDeclaringType); //IL_0006: stloc.0 il.Emit(OpCodes.Stloc, otherVar); //IL_0007: ldloc.0 il.Emit(OpCodes.Ldloc, otherVar); //IL_0008: brfalse.s IL_003a il.Emit(OpCodes.Brfalse, setToFalseInstruction); var storeResultInstruction = Instruction.Create(OpCodes.Stloc, isEqualVar); for (var i = 0; i < this.properties.Count; i++) { var prop = this.properties[i]; //IL_000a: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<!'<Lo>j__TPar'>::get_Default() il.Emit(OpCodes.Call, prop.GetDefaultEqualityComparerMethod); //IL_000f: ldarg.0 il.Emit(OpCodes.Ldarg_0); //IL_0010: ldfld !0 class '<>f__AnonymousType0`2'<!'<Lo>j__TPar', !'<La>j__TPar'>::'<Lo>i__Field' il.Emit(OpCodes.Ldfld, prop.FieldIlReference); //IL_0015: ldloc.0 il.Emit(OpCodes.Ldloc, otherVar); //IL_0016: ldfld !0 class '<>f__AnonymousType0`2'<!'<Lo>j__TPar', !'<La>j__TPar'>::'<Lo>i__Field' il.Emit(OpCodes.Ldfld, prop.FieldIlReference); //IL_001b: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<!'<Lo>j__TPar'>::Equals(!0, !0) il.Emit(OpCodes.Callvirt, prop.EqualityComparerEquals); //IL_0020: brfalse.s IL_003a if (i == this.properties.Count - 1) il.Emit(OpCodes.Br, storeResultInstruction); else il.Emit(OpCodes.Brfalse, setToFalseInstruction); } //IL_003a: ldc.i4.0 il.Append(setToFalseInstruction); //IL_003b: stloc.1 il.Append(storeResultInstruction); //IL_003c: br.s IL_003e //IL_003e: ldloc.1 il.Emit(OpCodes.Ldloc, isEqualVar); //IL_003f: ret il.Emit(OpCodes.Ret); this.definition.Methods.Add(method); } private void AddGenericParams() { this.ilFieldDeclaringType = new GenericInstanceType(this.definition); foreach (var prop in this.properties) { prop.GenericParameter = new GenericParameter($"<{prop.Name}>j__TPar", this.definition); this.definition.GenericParameters.Add(prop.GenericParameter); this.ilFieldDeclaringType.GenericArguments.Add(prop.GenericParameter); } } private void AddGetHashCode() { var method = new MethodDefinition( "GetHashCode", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, this.module.TypeSystem.Int32); method.Body.MaxStackSize = 3; method.Body.InitLocals = true; var var0 = new VariableDefinition(this.module.TypeSystem.Int32); method.Body.Variables.Add(var0); var var1 = new VariableDefinition(this.module.TypeSystem.Int32); method.Body.Variables.Add(var1); var il = method.Body.GetILProcessor(); // Different initial seed for different combinations of hashcodes int seed; using (var cipher = new SHA1Managed()) { var uniqueTypeString = string.Join("|", this.properties.Select(x => x.Name)); var hash = cipher.ComputeHash(Encoding.UTF8.GetBytes(uniqueTypeString)); seed = BitConverter.ToInt32(hash, 0); } il.Emit(OpCodes.Ldc_I4, seed); il.Emit(OpCodes.Stloc, var0); foreach (var prop in this.properties) { //IL_0006: ldc.i4 -1521134295 il.Emit(OpCodes.Ldc_I4, -1521134295); //IL_000b: ldloc.0 il.Emit(OpCodes.Ldloc, var0); //IL_000c: mul il.Emit(OpCodes.Mul); //IL_000d: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<!'<Lo>j__TPar'>::get_Default() il.Emit(OpCodes.Call, prop.GetDefaultEqualityComparerMethod); //IL_0012: ldarg.0 il.Emit(OpCodes.Ldarg_0); //IL_0013: ldfld !0 class '<>f__AnonymousType0`2'<!'<Lo>j__TPar', !'<La>j__TPar'>::'<Lo>i__Field' il.Emit(OpCodes.Ldfld, prop.FieldIlReference); //IL_0018: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<!'<Lo>j__TPar'>::GetHashCode(!0) il.Emit(OpCodes.Callvirt, prop.EqualityComparerGetHashCode); //IL_001d: add il.Emit(OpCodes.Add); //IL_001e: stloc.0 il.Emit(OpCodes.Stloc, var0); } il.Emit(OpCodes.Ldloc, var0); il.Emit(OpCodes.Stloc, var1); il.Emit(OpCodes.Ldloc, var1); il.Emit(OpCodes.Ret); this.definition.Methods.Add(method); } private void AddProperty(Property prop) { prop.Field = new FieldDefinition( $"<{prop.Name}>i__Field", FieldAttributes.InitOnly | FieldAttributes.Private, prop.GenericParameter); this.definition.Fields.Add(prop.Field); // Getter prop.Definition = new PropertyDefinition(prop.Name, PropertyAttributes.None, prop.GenericParameter); this.definition.Properties.Add(prop.Definition); prop.GetMethod = new MethodDefinition( $"get_{prop.Name}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, prop.GenericParameter); prop.FieldIlReference = new FieldReference( prop.Field.Name, prop.GenericParameter, this.ilFieldDeclaringType); var getter = prop.GetMethod; var getterBody = getter.Body; getterBody.MaxStackSize = 1; getterBody.InitLocals = true; getterBody.Variables.Add(new VariableDefinition(prop.GenericParameter)); var ilProc = getterBody.GetILProcessor(); ilProc.Append(Instruction.Create(OpCodes.Ldarg_0)); ilProc.Append(Instruction.Create(OpCodes.Ldfld, prop.FieldIlReference)); ilProc.Append(Instruction.Create(OpCodes.Stloc_0)); ilProc.Append(Instruction.Create(OpCodes.Ldloc_0)); ilProc.Append(Instruction.Create(OpCodes.Ret)); prop.GetMethod = getter; this.definition.Methods.Add(getter); prop.Definition.GetMethod = getter; var equalityComparerOfPropTypeDef = this.module.Import(typeof(EqualityComparer<>)).Resolve(); prop.GetDefaultEqualityComparerMethod = MakeHostInstanceGeneric( equalityComparerOfPropTypeDef. Properties.Where(x => x.Name == "Default" && x.GetMethod.IsStatic).Select(x => x.GetMethod). First(), prop.GenericParameter); prop.EqualityComparerGetHashCode = MakeHostInstanceGeneric( equalityComparerOfPropTypeDef.Methods.First(x => x.Name == "GetHashCode"), prop.GenericParameter); prop.EqualityComparerEquals = MakeHostInstanceGeneric( equalityComparerOfPropTypeDef.Methods.First(x => x.Name == "Equals"), prop.GenericParameter); // Constructor */ } private void AddRuntimeCompabilityAttributeToAssembly() { var attrType = this.module.Import(typeof(RuntimeCompatibilityAttribute)); var methodDefinition = this.module.Import(attrType.Resolve().Methods.First(x => x.IsConstructor && x.Parameters.Count == 0)); var attr = new CustomAttribute(methodDefinition); attr.Properties.Add( new CustomAttributeNamedArgument( "WrapNonExceptionThrows", new CustomAttributeArgument(this.module.TypeSystem.Boolean, true))); this.module.Assembly.CustomAttributes.Add(attr); } private void AddToString() { var method = new MethodDefinition( "ToString", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, this.module.TypeSystem.String); method.Body.MaxStackSize = 2; method.Body.InitLocals = true; var stringBuilderTypeRef = this.module.Import(typeof(StringBuilder)); var stringBuilderTypeDef = stringBuilderTypeRef.Resolve(); var stringBuilderCtor = this.module.Import( stringBuilderTypeDef.GetConstructors().First(x => x.Parameters.Count == 0 && !x.IsStatic)); var appendStringMethod = this.module.Import( stringBuilderTypeDef.Methods.First( x => x.Name == "Append" && x.Parameters.Count == 1 && x.Parameters[0].ParameterType.FullName == this.module.TypeSystem.String.FullName)); var appendObjectMethod = this.module.Import( stringBuilderTypeDef.Methods.First( x => x.Name == "Append" && x.Parameters.Count == 1 && x.Parameters[0].ParameterType.FullName == this.module.TypeSystem.Object.FullName)); var stringBuilderToStringMethod = this.module.Import( stringBuilderTypeDef.Methods.First( x => !x.IsStatic && x.Name == "ToString" && x.Parameters.Count == 0)); var stringBuilderVar = new VariableDefinition(stringBuilderTypeRef); method.Body.Variables.Add(stringBuilderVar); var tmpStringVar = new VariableDefinition(this.module.TypeSystem.String); method.Body.Variables.Add(tmpStringVar); var il = method.Body.GetILProcessor(); //IL_0000: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor() il.Emit(OpCodes.Newobj, stringBuilderCtor); //IL_0005: stloc.0 il.Emit(OpCodes.Stloc, stringBuilderVar); //IL_0006: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_0007: ldstr "{ Target = " il.Emit(OpCodes.Ldstr, $"{{ {this.properties[0].Name} = "); //IL_000c: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string) il.Emit(OpCodes.Callvirt, appendStringMethod); //IL_0011: pop il.Emit(OpCodes.Pop); //IL_0012: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_0013: ldarg.0 il.Emit(OpCodes.Ldarg_0); //IL_0014: ldfld !0 class '<>f__AnonymousType1`2'<!'<Target>j__TPar', !'<Elements>j__TPar'>::'<Target>i__Field' il.Emit(OpCodes.Ldfld, this.properties[0].FieldIlReference); //IL_0019: box !'<Target>j__TPar' il.Emit(OpCodes.Box, this.properties[0].GenericParameter); //IL_001e: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(object) il.Emit(OpCodes.Callvirt, appendObjectMethod); //IL_0023: pop il.Emit(OpCodes.Pop); foreach (var prop in this.properties.Skip(1)) { //IL_0024: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_0025: ldstr ", Elements = " il.Emit(OpCodes.Ldstr, $", {prop.Name} = "); //IL_002a: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string) il.Emit(OpCodes.Callvirt, appendStringMethod); //IL_002f: pop il.Emit(OpCodes.Pop); //IL_0030: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_0031: ldarg.0 il.Emit(OpCodes.Ldarg_0); //IL_0032: ldfld !1 class '<>f__AnonymousType1`2'<!'<Target>j__TPar', !'<Elements>j__TPar'>::'<Elements>i__Field' il.Emit(OpCodes.Ldfld, prop.FieldIlReference); //IL_0037: box !'<Elements>j__TPar' il.Emit(OpCodes.Box, prop.GenericParameter); //IL_003c: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(object) il.Emit(OpCodes.Callvirt, appendObjectMethod); //IL_0041: pop il.Emit(OpCodes.Pop); } //IL_0042: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_0043: ldstr " }" il.Emit(OpCodes.Ldstr, " }"); //IL_0048: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string) il.Emit(OpCodes.Callvirt, appendStringMethod); //IL_004d: pop il.Emit(OpCodes.Pop); //IL_004e: ldloc.0 il.Emit(OpCodes.Ldloc, stringBuilderVar); //IL_004f: callvirt instance string [mscorlib]System.Object::ToString() il.Emit(OpCodes.Callvirt, stringBuilderToStringMethod); //IL_0054: stloc.1 il.Emit(OpCodes.Stloc, tmpStringVar); //IL_0055: br.s IL_0057 // nah //IL_0057: ldloc.1 il.Emit(OpCodes.Ldloc, tmpStringVar); //IL_0058: ret il.Emit(OpCodes.Ret); this.definition.Methods.Add(method); } private static int AllocateUniqueAnonymousClassNumber() { return Interlocked.Increment(ref anonTypeNumber); } private static string GetAnonTypeKey(IEnumerable<string> propNames) { return string.Join(",", propNames); } private static Type GetAnonymousType(IEnumerable<string> propNames) { var anonType = anonTypeCache.GetOrCreate(GetAnonTypeKey(propNames), () => { var atb = new AnonymousTypeBuilder(propNames); var typedef = atb.BuildAnonymousType(); var memStream = new MemoryStream(); typedef.Module.Assembly.Write(memStream); var loadedAsm = AppDomain.CurrentDomain.Load(memStream.ToArray()); return loadedAsm.GetTypes().First(x => x.Name == typedef.Name); }); return anonType; } private TypeReference Import<T>() { return this.module.Import(typeof(T)); } #region Nested type: Property private class Property { public Property() { // Set to invalid value by default Index = int.MinValue; } public ParameterDefinition CtorParameter { get; set; } public PropertyDefinition Definition { get; set; } public MethodReference EqualityComparerEquals { get; set; } public MethodReference EqualityComparerGetHashCode { get; set; } public FieldDefinition Field { get; set; } public FieldReference FieldIlReference { get; set; } public GenericParameter GenericParameter { get; set; } public MethodReference GetDefaultEqualityComparerMethod { get; set; } public MethodDefinition GetMethod { get; set; } public int Index { get; set; } public string Name { get; set; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Cci; using Microsoft.Cci.Extensions; using Microsoft.Cci.Filters; using Microsoft.Cci.Writers; using Microsoft.Cci.Writers.Syntax; using Microsoft.Fx.CommandLine; namespace GenAPI { internal class Program { private static int Main(string[] args) { ParseCommandLine(args); HostEnvironment host = new HostEnvironment(); host.UnableToResolve += host_UnableToResolve; host.UnifyToLibPath = true; if (!string.IsNullOrWhiteSpace(s_libPath)) host.AddLibPaths(HostEnvironment.SplitPaths(s_libPath)); IEnumerable<IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(s_assembly)); if (!assemblies.Any()) { Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", s_assembly); return 1; } string headerText = GetHeaderText(); bool loopPerAssembly = Directory.Exists(s_out); if (loopPerAssembly) { foreach (var assembly in assemblies) { using (TextWriter output = GetOutput(GetFilename(assembly))) using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output)) { if (headerText != null) output.Write(headerText); ICciWriter writer = GetWriter(output, syntaxWriter); writer.WriteAssemblies(new IAssembly[] { assembly }); } } } else { using (TextWriter output = GetOutput()) using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output)) { if (headerText != null) output.Write(headerText); ICciWriter writer = GetWriter(output, syntaxWriter); writer.WriteAssemblies(assemblies); } } return 0; } private static void host_UnableToResolve(object sender, UnresolvedReference<IUnit, AssemblyIdentity> e) { Console.WriteLine("Unable to resolve assembly '{0}' referenced by '{1}'.", e.Unresolved.ToString(), e.Referrer.ToString()); } private static string GetHeaderText() { if (!String.IsNullOrEmpty(s_headerFile)) { if (!File.Exists(s_headerFile)) { Console.WriteLine("ERROR: header file '{0}' does not exist", s_headerFile); } using (TextReader headerText = File.OpenText(s_headerFile)) { return headerText.ReadToEnd(); } } return null; } private static TextWriter GetOutput(string filename = "") { // If this is a null, empty, whitespace, or a directory use console if (string.IsNullOrWhiteSpace(s_out)) return Console.Out; if (Directory.Exists(s_out) && !string.IsNullOrEmpty(filename)) { return File.CreateText(Path.Combine(s_out, filename)); } return File.CreateText(s_out); } private static string GetFilename(IAssembly assembly) { string name = assembly.Name.Value; switch (s_writer) { case WriterType.DocIds: case WriterType.TypeForwards: return name + ".txt"; case WriterType.TypeList: case WriterType.CSDecl: default: switch (s_syntaxWriter) { case SyntaxWriterType.Xml: return name + ".xml"; case SyntaxWriterType.Html: return name + ".html"; case SyntaxWriterType.Text: default: return name + ".cs"; } } } private static ICciWriter GetWriter(TextWriter output, IStyleSyntaxWriter syntaxWriter) { ICciFilter filter = GetFilter(); switch (s_writer) { case WriterType.DocIds: return new DocumentIdWriter(output, filter); case WriterType.TypeForwards: return new TypeForwardWriter(output, filter) { IncludeForwardedTypes = true }; case WriterType.TypeList: return new TypeListWriter(syntaxWriter, filter); default: case WriterType.CSDecl: { CSharpWriter writer = new CSharpWriter(syntaxWriter, filter, s_apiOnly); writer.IncludeSpaceBetweenMemberGroups = writer.IncludeMemberGroupHeadings = s_memberHeadings; writer.HighlightBaseMembers = s_hightlightBaseMembers; writer.HighlightInterfaceMembers = s_hightlightInterfaceMembers; writer.PutBraceOnNewLine = true; writer.ThrowPlatformNotSupportedForCompilation = s_throw; return writer; } } } private static ICciFilter GetFilter() { ICciFilter includeFilter = null; if (string.IsNullOrWhiteSpace(s_apiList)) { if (s_all) { includeFilter = new IncludeAllFilter(); } else { includeFilter = new PublicOnlyCciFilter(excludeAttributes: s_apiOnly); } } else { includeFilter = new DocIdIncludeListFilter(s_apiList); } if (!string.IsNullOrWhiteSpace(s_excludeApiList)) { includeFilter = new IntersectionFilter(includeFilter, new DocIdExcludeListFilter(s_excludeApiList)); } if (!string.IsNullOrWhiteSpace(s_excludeAttributesList)) { includeFilter = new IntersectionFilter(includeFilter, new ExcludeAttributesFilter(s_excludeAttributesList)); } return includeFilter; } private static IStyleSyntaxWriter GetSyntaxWriter(TextWriter output) { if (s_writer != WriterType.CSDecl && s_writer != WriterType.TypeList) return null; switch (s_syntaxWriter) { case SyntaxWriterType.Xml: return new OpenXmlSyntaxWriter(output); case SyntaxWriterType.Html: return new HtmlSyntaxWriter(output); case SyntaxWriterType.Text: default: return new TextSyntaxWriter(output) { SpacesInIndent = 4 }; } } private enum WriterType { CSDecl, DocIds, TypeForwards, TypeList, } private enum SyntaxWriterType { Text, Html, Xml } private static string s_assembly; private static WriterType s_writer = WriterType.CSDecl; private static SyntaxWriterType s_syntaxWriter = SyntaxWriterType.Text; private static string s_apiList; private static string s_excludeApiList; private static string s_excludeAttributesList; private static string s_headerFile; private static string s_out; private static string s_libPath; private static bool s_apiOnly; private static bool s_memberHeadings; private static bool s_hightlightBaseMembers; private static bool s_hightlightInterfaceMembers; private static bool s_all; private static bool s_throw; private static void ParseCommandLine(string[] args) { CommandLineParser.ParseForConsoleApplication((parser) => { parser.DefineOptionalQualifier("libPath", ref s_libPath, "Delimited (',' or ';') set of paths to use for resolving assembly references"); parser.DefineAliases("apiList", "al"); parser.DefineOptionalQualifier("apiList", ref s_apiList, "(-al) Specify a api list in the DocId format of which APIs to include."); parser.DefineAliases("excludeApiList", "xal"); parser.DefineOptionalQualifier("excludeApiList", ref s_excludeApiList, "(-xal) Specify a api list in the DocId format of which APIs to exclude."); parser.DefineOptionalQualifier("excludeAttributesList", ref s_excludeAttributesList, "Specify a list in the DocId format of which attributes should be excluded from being applied on apis."); parser.DefineAliases("writer", "w"); parser.DefineOptionalQualifier<WriterType>("writer", ref s_writer, "(-w) Specify the writer type to use."); parser.DefineAliases("syntax", "s"); parser.DefineOptionalQualifier<SyntaxWriterType>("syntax", ref s_syntaxWriter, "(-s) Specific the syntax writer type. Only used if the writer is CSDecl"); parser.DefineOptionalQualifier("out", ref s_out, "Output path. Default is the console. Can specify an existing directory as well and then a file will be created for each assembly with the matching name of the assembly."); parser.DefineAliases("headerFile", "h"); parser.DefineOptionalQualifier("headerFile", ref s_headerFile, "(-h) Specify a file with header content to prepend to output."); parser.DefineAliases("apiOnly", "api"); parser.DefineOptionalQualifier("apiOnly", ref s_apiOnly, "(-api) [CSDecl] Include only API's not CS code that compiles."); parser.DefineOptionalQualifier("all", ref s_all, "Include all API's not just public APIs. Default is public only."); parser.DefineAliases("memberHeadings", "mh"); parser.DefineOptionalQualifier("memberHeadings", ref s_memberHeadings, "(-mh) [CSDecl] Include member headings for each type of member."); parser.DefineAliases("hightlightBaseMembers", "hbm"); parser.DefineOptionalQualifier("hightlightBaseMembers", ref s_hightlightBaseMembers, "(-hbm) [CSDecl] Highlight overridden base members."); parser.DefineAliases("hightlightInterfaceMembers", "him"); parser.DefineOptionalQualifier("hightlightInterfaceMembers", ref s_hightlightInterfaceMembers, "(-him) [CSDecl] Highlight interface implementation members."); parser.DefineAliases("throw", "t"); parser.DefineOptionalQualifier("throw", ref s_throw, "(-t) Method bodies should throw PlatformNotSupportedException."); parser.DefineQualifier("assembly", ref s_assembly, "Path for an specific assembly or a directory to get all assemblies."); }, args); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace ESRI.ArcGIS.Geodatabase { /// <summary> /// Provides extension methods for the <see cref="ESRI.ArcGIS.Geodatabase.IRow" /> interface. /// </summary> public static class RowExtensions { #region Fields private static readonly Dictionary<IRow, ReentrancyMonitor> _ReentrancyMonitors = new Dictionary<IRow, ReentrancyMonitor>(new RowEqualityComparer()); #endregion #region Public Methods /// <summary> /// Disallow reentrant attempts to save changes to the object. /// </summary> /// <param name="source">The source.</param> /// <returns> /// Returns a <see cref="IDisposable" /> implementation used to remove the block on dispose. /// </returns> /// <remarks> /// The reentrancy is only implemented in the <see cref="M:SaveChanges" /> method. The blocking will not take affect if /// the Store method is invoked. /// </remarks> public static IDisposable BlockReentrancy(this IRow source) { if (source == null) return null; if (!_ReentrancyMonitors.ContainsKey(source)) _ReentrancyMonitors.Add(source, new ReentrancyMonitor()); var reentrancyMonitor = _ReentrancyMonitors[source]; reentrancyMonitor.Set(); return reentrancyMonitor; } /// <summary> /// Creates a new row by duplicating the contents of the specified row. /// </summary> /// <param name="source">The source.</param> /// <returns> /// Returns a <see cref="IRow" /> representings a duplicate copy of the row. /// </returns> public static IRow Clone(this IRow source) { return source.Clone(true); } /// <summary> /// Creates a new row by duplicating the contents of the specified row. /// </summary> /// <param name="source">The source.</param> /// <param name="committed">if set to <c>true</c> if created row is committed to the database.</param> /// <returns> /// Returns a <see cref="IRow" /> representings a duplicate copy of the row. /// </returns> public static IRow Clone(this IRow source, bool committed) { ITable table = source.Table; var row = table.CreateNew(); for (int i = 0; i < row.Fields.FieldCount; i++) { if (row.Fields.Field[i].Editable) { object o = source.Value[i]; row.Value[i] = o; } } if (committed) row.Store(); return row; } /// <summary> /// Gets the indexes and field names for all of the fields that have changed values. /// </summary> /// <param name="source">The source.</param> /// <returns> /// Returns a <see cref="Dictionary{Int32, String}" /> representing the indexes/names of the fields that have changed. /// </returns> public static Dictionary<int, string> GetChanges(this IRow source) { if (source == null) return null; Dictionary<int, string> list = new Dictionary<int, string>(); IRowChanges rowChanges = (IRowChanges) source; for (int i = 0; i < source.Fields.FieldCount; i++) { if (rowChanges.ValueChanged[i]) { list.Add(i, source.Fields.Field[i].Name); } } return list; } /// <summary> /// Gets the field name and original value for those fields that have changed. /// </summary> /// <param name="source">The source.</param> /// <param name="fieldNames">The field names.</param> /// <returns> /// Returns a <see cref="Dictionary{String, Object}" /> representing the field name / original values for those fields /// that have changed. /// </returns> /// <exception cref="System.ArgumentNullException">fieldNames</exception> public static Dictionary<string, object> GetChanges(this IRow source, params string[] fieldNames) { if (source == null) return null; if (fieldNames == null) throw new ArgumentNullException("fieldNames"); Dictionary<string, object> list = new Dictionary<string, object>(StringComparer.Create(CultureInfo.CurrentCulture, true)); IRowChanges rowChanges = (IRowChanges) source; for (int i = 0; i < source.Fields.FieldCount; i++) { foreach (var fieldName in fieldNames) { if (source.Fields.Field[i].Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) { if (rowChanges.ValueChanged[i] && !list.ContainsKey(fieldName)) { list.Add(fieldName, rowChanges.OriginalValue[i]); } } } } return list; } /// <summary> /// Gets the domain that is assigned to the field. /// </summary> /// <param name="source">The row.</param> /// <param name="index">The index.</param> /// <returns> /// Returns a <see cref="IDomain" /> representing the domain for the field. /// </returns> /// <exception cref="IndexOutOfRangeException"></exception> public static IDomain GetDomain(this IRow source, int index) { if (source == null) return null; if (index < 0 || index > source.Fields.FieldCount - 1) throw new IndexOutOfRangeException(); ISubtypes subtypes = (ISubtypes) source.Table; if (subtypes.HasSubtype) { string fieldName = source.Fields.Field[index].Name; IRowSubtypes rowSubtypes = (IRowSubtypes) source; return subtypes.Domain[rowSubtypes.SubtypeCode, fieldName]; } return source.Fields.Field[index].Domain; } /// <summary> /// Returns the field value that has the specified <paramref name="fieldName" /> field name for the /// <paramref name="source" />. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The row.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="fallbackValue">The default value.</param> /// <returns> /// Returns an <see cref="object" /> representing the converted value to the specified type. /// </returns> /// <exception cref="System.ArgumentNullException">fieldName</exception> /// <exception cref="IndexOutOfRangeException"></exception> public static TValue GetValue<TValue>(this IRow source, string fieldName, TValue fallbackValue) { if (source == null) return fallbackValue; if (fieldName == null) throw new ArgumentNullException("fieldName"); int index = source.Table.FindField(fieldName); return source.GetValue(index, fallbackValue); } /// <summary> /// Returns the field value that at the specified <paramref name="index" /> for the <paramref name="source" />. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The row.</param> /// <param name="index">The index.</param> /// <param name="fallbackValue">The default value.</param> /// <returns> /// Returns an <see cref="object" /> representing the converted value to the specified type. /// </returns> /// <exception cref="IndexOutOfRangeException"></exception> public static TValue GetValue<TValue>(this IRowBuffer source, int index, TValue fallbackValue) { if (source == null) return fallbackValue; if (index < 0 || index > source.Fields.FieldCount - 1) throw new IndexOutOfRangeException(); return TypeCast.Cast(source.Value[index], fallbackValue); } /// <summary> /// Deletes the row from the database but does not trigger the OnDelete event. /// </summary> /// <param name="source">The source.</param> /// <remarks> /// Any associated object behavior is not triggered, thus should only be used when implementing custom features that /// bypass store method. /// </remarks> public static void Remove(this IRow source) { if (source == null) return; ITableWrite tableWrite = source.Table as ITableWrite; if (tableWrite != null) { tableWrite.RemoveRow(source); } } /// <summary> /// Commits the changes to the database when one or more field values have changed. /// </summary> /// <param name="source">The source.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the store was called on the row; otherwise <c>false</c> /// </returns> /// <remarks> /// The changes will not be saved, if there was a call to BlockReentrancy of which the IDisposable return value has not /// yet been disposed of. /// </remarks> public static bool SaveChanges(this IRow source) { if (source == null) return false; return source.SaveChanges(field => field.Editable); } /// <summary> /// Commits the changes to the database when one or more field values have changed. /// </summary> /// <param name="source">The source.</param> /// <param name="predicate">The predicate that indicates if the field should be checked for changes.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the store was called on the row; otherwise <c>false</c> /// </returns> /// <exception cref="System.ArgumentNullException">predicate</exception> /// <remarks> /// The changes will not be saved, if there was a call to BlockReentrancy of which the IDisposable return value has not /// yet been disposed of. /// </remarks> public static bool SaveChanges(this IRow source, Predicate<IField> predicate) { if (source == null) return false; if (predicate == null) throw new ArgumentNullException("predicate"); source.CheckReentrancy(); bool saveChanges = false; IRowChanges rowChanges = (IRowChanges) source; for (int i = 0; i < source.Fields.FieldCount; i++) { if (predicate(source.Fields.Field[i]) && rowChanges.ValueChanged[i]) { saveChanges = true; break; } } if (saveChanges) { source.Store(); } return saveChanges; } /// <summary> /// Creates an <see cref="IDictionary{TKey, TValue}" /> from an <see cref="IFields" /> /// </summary> /// <param name="source">An <see cref="IRowBuffer" /> to create an <see cref="IDictionary{TKey, Object}" /> from.</param> /// <returns> /// An <see cref="IDictionary{TKey, Object}" /> that contains the fields from the input source. /// </returns> public static IDictionary<string, object> ToDictionary(this IRowBuffer source) { Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Create(CultureInfo.CurrentCulture, true)); for (int i = 0; i < source.Fields.FieldCount; i++) { dictionary.Add(source.Fields.Field[i].Name, source.Value[i]); } return dictionary; } /// <summary> /// Returns the field value that at the specified <paramref name="fieldName" /> for the <paramref name="source" />. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The row.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="fallbackValue">The default value.</param> /// <param name="value"> /// When this method returns, contains the value associat/ed with the specified /// index, if the index is found; otherwise, the default value for the type of the /// value parameter. This parameter is passed uninitialized. /// </param> /// <returns> /// Returns an <see cref="bool" /> representing <c>true</c> if the field index is valid; otherwise, false. /// </returns> /// <exception cref="System.ArgumentNullException">fieldName</exception> public static bool TryGetValue<TValue>(this IRow source, string fieldName, TValue fallbackValue, out TValue value) { value = fallbackValue; if (source == null) return false; if (fieldName == null) throw new ArgumentNullException("fieldName"); int index = source.Table.FindField(fieldName); return source.TryGetValue(index, fallbackValue, out value); } /// <summary> /// Returns the field value that at the specified <paramref name="index" /> for the <paramref name="source" />. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The row.</param> /// <param name="index">The field index.</param> /// <param name="fallbackValue">The default value.</param> /// <param name="value"> /// When this method returns, contains the value associat/ed with the specified /// index, if the index is found; otherwise, the default value for the type of the /// value parameter. This parameter is passed uninitialized. /// </param> /// <returns> /// Returns an <see cref="bool" /> representing <c>true</c> if the field index is valid; otherwise, false. /// </returns> public static bool TryGetValue<TValue>(this IRowBuffer source, int index, TValue fallbackValue, out TValue value) { try { value = source.GetValue(index, fallbackValue); return true; } catch (Exception) { value = fallbackValue; return false; } } /// <summary> /// Updates the column on the row with the value when the original value and the specified /// <paramref name="value" /> are different. /// </summary> /// <param name="source">The source.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="value">The value for the field.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the row updated; otherwise <c>false</c> /// </returns> /// <exception cref="System.ArgumentNullException">fieldName</exception> /// <exception cref="ArgumentOutOfRangeException">fieldName</exception> public static bool Update(this IRow source, string fieldName, object value) { return source.Update(fieldName, value, true); } /// <summary> /// Updates the column on the row with the value when the original value and the specified /// <paramref name="value" /> are different. /// </summary> /// <param name="source">The source.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="value">The value for the field.</param> /// <param name="equalityCompare">if set to <c>true</c> when the changes need to be compared prior to updating.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the row updated; otherwise <c>false</c> /// </returns> /// <exception cref="System.ArgumentNullException">fieldName</exception> /// <exception cref="ArgumentOutOfRangeException">fieldName</exception> public static bool Update(this IRow source, string fieldName, object value, bool equalityCompare) { if (source == null) return false; if (fieldName == null) throw new ArgumentNullException("fieldName"); int i = source.Table.FindField(fieldName); return source.Update(i, value, equalityCompare); } /// <summary> /// Updates the column index on the row with the value when the original value and the specified /// <paramref name="value" /> are different. /// </summary> /// <param name="source">The source.</param> /// <param name="index">The index of the field.</param> /// <param name="value">The value for the field.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the row updated; otherwise <c>false</c> /// </returns> /// <exception cref="IndexOutOfRangeException"></exception> public static bool Update(this IRowBuffer source, int index, object value) { return source.Update(index, value, true); } /// <summary> /// Updates the column index on the row with the value when the original value and the specified /// <paramref name="value" /> are different. /// </summary> /// <param name="source">The source.</param> /// <param name="index">The index of the field.</param> /// <param name="value">The value for the field.</param> /// <param name="equalityCompare">if set to <c>true</c> when the changes need to be compared prior to updating.</param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the row updated; otherwise <c>false</c> /// </returns> /// <exception cref="IndexOutOfRangeException"></exception> public static bool Update(this IRowBuffer source, int index, object value, bool equalityCompare) { if (source == null) return false; if (index < 0 || index > source.Fields.FieldCount - 1) throw new IndexOutOfRangeException(); if (equalityCompare) { switch (source.Fields.Field[index].Type) { case esriFieldType.esriFieldTypeOID: case esriFieldType.esriFieldTypeInteger: return source.Update(index, TypeCast.Cast(value, default(long)), EqualityComparer<long>.Default); case esriFieldType.esriFieldTypeSmallInteger: return source.Update(index, TypeCast.Cast(value, default(int)), EqualityComparer<int>.Default); case esriFieldType.esriFieldTypeSingle: return source.Update(index, TypeCast.Cast(value, default(float)), EqualityComparer<float>.Default); case esriFieldType.esriFieldTypeDouble: return source.Update(index, TypeCast.Cast(value, default(double)), EqualityComparer<double>.Default); case esriFieldType.esriFieldTypeString: case esriFieldType.esriFieldTypeDate: case esriFieldType.esriFieldTypeGUID: case esriFieldType.esriFieldTypeGlobalID: return source.Update(index, TypeCast.Cast(value, default(string)), EqualityComparer<string>.Default); default: return source.Update(index, value, EqualityComparer<object>.Default); } } return source.Update(index, value, null); } /// <summary> /// Stores a row into the database but does not trigger the OnStore event. /// </summary> /// <param name="source">The source.</param> /// <remarks> /// Any associated object behavior is not triggered, thus should only be used when implementing custom features that /// bypass store method. /// </remarks> public static void Write(this IRow source) { if (source == null) return; ITableWrite tableWrite = source.Table as ITableWrite; if (tableWrite != null) { tableWrite.WriteRow(source); } } #endregion #region Private Methods /// <summary> /// Checks and aserts for reentrant attempts to change the object. /// </summary> /// <param name="source">The source.</param> /// <exception cref="System.InvalidOperationException"> /// There was a call to BlockReentrancy of which the IDisposable return /// value has not yet been disposed of. /// </exception> private static void CheckReentrancy(this IRow source) { if (source == null) return; if (_ReentrancyMonitors.ContainsKey(source)) { var reentrancyMonitor = _ReentrancyMonitors[source]; if (reentrancyMonitor.IsBusy) throw new InvalidOperationException("There was a call to BlockReentrancy of which the IDisposable return value has not yet been disposed of."); } } /// <summary> /// Updates the column index on the row with the value when the original value and the specified /// <paramref name="value" /> are different. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The source.</param> /// <param name="index">The index of the field.</param> /// <param name="value">The value for the field.</param> /// <param name="equalityComparer"> /// The equality comparer to use to determine whether or not values are equal. /// If null, the default equality comparer for object is used. /// </param> /// <returns> /// Returns a <see cref="bool" /> representing <c>true</c> when the row updated; otherwise <c>false</c> /// </returns> /// <exception cref="IndexOutOfRangeException"></exception> private static bool Update<TValue>(this IRowBuffer source, int index, TValue value, IEqualityComparer<TValue> equalityComparer) { bool pendingChanges = true; if (equalityComparer != null) { IRowChanges rowChanges = (IRowChanges) source; object originalValue = rowChanges.OriginalValue[index]; TValue oldValue = TypeCast.Cast(originalValue, default(TValue)); pendingChanges = !equalityComparer.Equals(oldValue, value); } if (pendingChanges) { if (Equals(value, default(TValue)) && source.Fields.Field[index].IsNullable) { source.Value[index] = DBNull.Value; } else { source.Value[index] = value; } } return pendingChanges; } #endregion } }
namespace Watts.Azure.Common.ServiceBus.Management { using System; using System.Collections.Generic; using System.Linq; using General; using Interfaces.ServiceBus; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Objects; /// <summary> /// This class represents a certain topology in Azure Service Bus. It can create auto-forwarding topics etc in a tree-structure that allows /// for scaling beyond the 2000 subscriptions per topic currently imposed in Azure Service Bus. /// It is possible to specify the maximum number of subscribers that should be allowed. At the time of writing, the hard limit in Azure is 2000 subscriptions per topic, /// but this could change in the future so no hard limit is enforced here. /// </summary> public class AzureServiceBusTopology : ICloneable { /// <summary> /// The number of times that we should retry when Azure service bus management throws an error /// </summary> private const int NumberOfRetriesOnFailure = 5; /// <summary> /// The number of milliseconds delay between each retry attempt /// </summary> private const int MillisecondDelayBetweenAttemptsOnFailure = 500; /// <summary> /// The maximum number of subscribers per service topic /// </summary> private readonly int maxSubscribersPerTopic; /// <summary> /// The name of the root service bus namespace. Sub-namespaces names are derived from this, when necessary /// </summary> private readonly string rootNamespaceName; /// <summary> /// The name of the topic /// </summary> private string topicName; /// <summary> /// The root of the topology. This represents the root topic. /// If the number of required subscribers to the topic exceeds the maximum threshold, sub-topics are created and the root forwards to these. /// This process is repeated until there are enough levels to support the required number of subscribers /// </summary> private TreeNode<AzureServiceBusTopicInfo> rootNode; /// <summary> /// The location where the service bus should be located /// </summary> private readonly AzureLocation location; /// <summary> /// Management client for CRUD operations on the service bus API /// </summary> private readonly IAzureServiceBusManagement management; /// <summary> /// Keeps track of the total number of topics that have been processed (created or deleted) /// </summary> private int numberOfTopicsProcessed = 0; /// <summary> /// Keeps track of the total number of subscriptions that have been processed (created or deleted) /// </summary> private int numberOfSubscriptionsProcessed = 0; /// <summary> /// Callback action to report progress/events on. /// </summary> private Action<string> reportAction; /// <summary> /// Creates a new instance of AzureServiceBusTopology /// </summary> /// <param name="rootNamespace">The root service bus namespace name</param> /// <param name="topicName">The name of the topic to scale</param> /// <param name="serviceBusManagement">Management client for Azure Service Bus</param> /// <param name="location">Location to create the bus in</param> /// <param name="maxSubscribersPerTopic">(optional) The maximum number of subscribers to allow per topic.</param> public AzureServiceBusTopology(string rootNamespace, string topicName, IAzureServiceBusManagement serviceBusManagement, AzureLocation location, int maxSubscribersPerTopic = 2000) { this.rootNamespaceName = rootNamespace; this.maxSubscribersPerTopic = maxSubscribersPerTopic; this.topicName = topicName; this.location = location; // Create the management client for CRUD operations on namespaces and topics this.management = serviceBusManagement; } public string TopicName { get => this.topicName; set => this.topicName = value; } public int MaxSubscribersPerTopic => this.maxSubscribersPerTopic; /// <summary> /// Get or set the total number of nodes. /// </summary> public int TotalNumberOfNodes { get; set; } = 1; /// <summary> /// Specify an action to report information/progress on. /// </summary> /// <param name="action"></param> public void ReportOn(Action<string> action) { this.reportAction = action; } /// <summary> /// Generate a topology that would support the given number of subscribers. /// E.g. if the maximum number of subscribers per topic is 2000 and we need to support 10000 subscribers, we will need to create one 'root' topic /// and five children, which the root topic will auto-forward to. /// </summary> public void GenerateBusTopology(int numberOfSubscribers) { this.Report("Creating topology..."); // Determine the number of 'levels' that we need to create. // E.g. let's say there are 10,000 subscribers. Each namespace topic can handle a total of 2000 subscriptions by default, i.e. we'll need to add another level. // One root, with 5 sub-namespaces that it forwards to and // five sub-namespaces with 2000 subscriptions for the topic in each. // If the number of subscribers exceeds 2000*2000 = 4,000,000 (i.e. one root with 2000 subscribers with 2000 subscribers each), we will have to create e third level. // Formally, the number of levels we'll need is log_maxSubsribersPerNamespace(number of subscribers) int numberOfLevels = (int)Math.Ceiling(Math.Log(numberOfSubscribers, this.maxSubscribersPerTopic)); this.Report($"There will be {numberOfLevels} levels"); this.rootNode = new TreeNode<AzureServiceBusTopicInfo>(new AzureServiceBusTopicInfo() { Name = this.topicName }); // Fill all levels up to the leaf level this.FillWithChildTopics(this.rootNode, this.maxSubscribersPerTopic, 1, (int)Math.Max(1, numberOfLevels - 1)); // There can be maxNumberOfSubscribers per leaf node, meaning that the total number of available leaf nodes should be // numberOfSubscribers / maxSubscribersPerNamespace int requiredLeaves = numberOfSubscribers / this.maxSubscribersPerTopic; var leaves = this.rootNode.FlattenNodes().Where(p => p.IsLeaf).ToList(); // The number of 'leaves' in our tree of Topics will need to be numberOfSubscribers / maxNumberOfSubscribers. // E.g. 10000 subscribers with max subscribers equal to 2000 will mean that there needs to be 5 separate topic instances that // we can subscribe to. int numberOfChildrenPerNode = (int)Math.Ceiling((double)requiredLeaves / leaves.Count); // Get the number of leaves we need to create in order to have enough int totalNumberRemaining = numberOfLevels == 2 ? requiredLeaves : requiredLeaves - leaves.Count; // Go through each current leaf create children (the new leaves) as required, until we have enough leaves to support the required number of topic subscribers leaves.ForEach(n => { if (totalNumberRemaining > 0) { // Create new children, thereby creating new leaves. Minimum 2 children must be created, as creating one child will not add // any new leaves. int children = (int)Math.Max(2, Math.Min(totalNumberRemaining, numberOfChildrenPerNode)); // Give each node at the second-last level an equal share of children. this.FillWithChildTopics(n, children, 1, 2); // The number of new leaves created is the number of children - 1, since this node is no longer a leaf. int newLeavesCreated = children - 1; totalNumberRemaining -= newLeavesCreated; } }); // Copy the total number of nodes in. this.TotalNumberOfNodes = this.rootNode.TotalNumberOfNodes; } /// <summary> /// Get the number of leaf topics (the topics that subscriptions can be added to) /// </summary> /// <returns></returns> public int GetNumberOfLeafTopics() { return this.rootNode.FlattenNodes().Count(p => p.IsLeaf); } public IEnumerable<TreeNode<AzureServiceBusTopicInfo>> GetLeafNodes() { return this.rootNode.FlattenNodes().Where(p => p.IsLeaf); } public IEnumerable<AzureServiceBusTopicSubscriptionInfo> GenerateLeafSubscriptions(int numberOfSubscriptions) { List<AzureServiceBusTopicSubscriptionInfo> retVal = new List<AzureServiceBusTopicSubscriptionInfo>(); int numberOfLeafNodes = this.GetLeafNodes().Count(); int subscriptionsPerLeaf = (int) Math.Ceiling((double) numberOfSubscriptions / numberOfLeafNodes); foreach (var leaf in this.GetLeafNodes()) { for (int i = 0; i < subscriptionsPerLeaf; i++) { string subscriptionName = $"sub-{leaf.Value.Name}-{i + 1}"; Retry.Do(() => { try { retVal.Add(new AzureServiceBusTopicSubscriptionInfo(leaf.Value.Name, leaf.Value.PrimaryConnectionString, subscriptionName)); return true; } catch (Exception ex) { return false; } }) .WithRandomDelay(MillisecondDelayBetweenAttemptsOnFailure, 4 * MillisecondDelayBetweenAttemptsOnFailure) .MaxTimes(NumberOfRetriesOnFailure) .Go(); } } return retVal; } public AzureServiceBusTopicInfo GetRootTopic() { return this.rootNode.Value; } /// <summary> /// Ensure the topology exists. If it doesn't, it will be created and auto-forwarding of topic subscriptions set up where relevant. /// Any existing topics/subscriptions will be updated to ensure they have the properties required (e.g. auto-forward settings) /// </summary> public void Emit() { this.numberOfSubscriptionsProcessed = 0; this.numberOfTopicsProcessed = 0; this.Report("Creating bus if it doesn't exist"); this.EmitBusIfNotExists(); this.Report("Bus created..."); this.Report("Emitting topics"); // Emit all topics this.rootNode.TraverseParallel(this.EmitTopic); this.Report("Topics created!"); this.Report("Replicating connection string to topology."); // Get a connection string for the namespace and pass that to all nodes string namespaceConnectionString = this.management.GetNamespaceConnectionString(this.rootNamespaceName); this.rootNode.Traverse(p => p.PrimaryConnectionString = namespaceConnectionString); // Emit all subscriptions (for auto-forwarding) this.EmitSubscriptions(); } /// <summary> /// Destroy the bus topology (topics and subscriptions) /// </summary> /// <param name="leaveRoot"></param> public void Destroy(bool leaveRoot = true) { this.Report("Destroying topology!"); this.numberOfSubscriptionsProcessed = 0; this.numberOfTopicsProcessed = 0; if (leaveRoot) { this.Report("Will leave the root topic..."); // Only destroy child topics, so iterate child nodes foreach (var rootNodeChild in this.rootNode.Children) { rootNodeChild.TraverseParallel(this.DestroyTopic); } } else { this.Report("Will delete the root topic as well..."); this.rootNode.TraverseParallel(this.DestroyTopic); } } /// <summary> /// Create subscriptions for level in the topology, meaning that if there are e.g. two levels (root and x children) the root will have subscriptions that auto-forward /// to the same topic on each of the x children. /// </summary> internal void EmitSubscriptions() { this.Report("Emitting subscriptions!"); if (this.rootNode.Children.Count == 0) { // There are no children, so no forwarding is neccessary return; } this.EmitChildSubscriptions(this.rootNode); } /// <summary> /// Destroy all subscriptions /// </summary> internal void DestroySubscriptions() { if (this.rootNode.Children.Count == 0) { return; } this.DestroyChildSubscriptions(this.rootNode); } /// <summary> /// Create child subscriptions on the given topic node /// </summary> /// <param name="node"></param> internal void EmitChildSubscriptions(TreeNode<AzureServiceBusTopicInfo> node) { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(node.Value.PrimaryConnectionString); foreach (var child in node.Children) { // Create a subscription that forwards to the node's child. SubscriptionDescription subscription = new SubscriptionDescription(node.Value.Name, child.Value.Name); subscription.ForwardTo = child.Value.Name; Retry.Do(() => { try { namespaceManager.CreateSubscription(subscription); this.numberOfSubscriptionsProcessed++; this.Report($"\rCreated {this.numberOfSubscriptionsProcessed} of {this.TotalNumberOfNodes} subscriptions"); return true; } catch (Exception) { return false; } }) .WithDelayInMs(MillisecondDelayBetweenAttemptsOnFailure) .MaxTimes(NumberOfRetriesOnFailure) .Go(); this.EmitChildSubscriptions(child); } } /// <summary> /// Delete all child subscriptions from the topic /// </summary> /// <param name="node"></param> internal void DestroyChildSubscriptions(TreeNode<AzureServiceBusTopicInfo> node) { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(node.Value.PrimaryConnectionString); foreach (var child in node.Children) { Retry.Do(() => { try { namespaceManager.DeleteSubscription(node.Value.Name, "forward-" + child.Value.Name); this.numberOfSubscriptionsProcessed++; this.Report($"Deleted {this.numberOfSubscriptionsProcessed} of {this.TotalNumberOfNodes}"); return true; } catch (Exception) { return false; } }) .WithDelayInMs(NumberOfRetriesOnFailure) .MaxTimes(NumberOfRetriesOnFailure).Go(); this.DestroyChildSubscriptions(child); } } /// <summary> /// Create the bus namespace if it doesn't already exist. /// </summary> internal void EmitBusIfNotExists() { this.Report("Creating namespace if it doesn't already exist..."); var existingBus = this.management.GetNamespace(this.rootNamespaceName); if (existingBus == null) { this.management.CreateOrUpdateNamespace(this.rootNamespaceName, this.location); } } /// <summary> /// Create a topic through the management api. /// </summary> /// <param name="topicInfo"></param> internal void EmitTopic(AzureServiceBusTopicInfo topicInfo) { Retry.Do(() => { try { this.management.CreateOrUpdateTopic(this.rootNamespaceName, topicInfo.Name); this.numberOfTopicsProcessed++; this.Report($"\rCreated {this.numberOfTopicsProcessed} of {this.TotalNumberOfNodes} topics"); return true; } catch (Exception ex) { this.Report($"Exception when emitting topic {topicInfo.Name}: {ex}"); return false; } }).WithDelayInMs(MillisecondDelayBetweenAttemptsOnFailure) .MaxTimes(NumberOfRetriesOnFailure) .Go(); } /// <summary> /// Delete a topic. /// </summary> /// <param name="topicInfo"></param> internal void DestroyTopic(AzureServiceBusTopicInfo topicInfo) { Retry.Do(() => { try { this.management.DeleteTopic(this.rootNamespaceName, topicInfo.Name); this.numberOfTopicsProcessed++; this.Report($"Deleted {this.numberOfTopicsProcessed} of {this.TotalNumberOfNodes} topics"); return true; } catch (Exception ex) { this.Report($"Exception when destroying topic {topicInfo.Name}, {ex}"); return false; } }) .WithDelayInMs(MillisecondDelayBetweenAttemptsOnFailure) .MaxTimes(NumberOfRetriesOnFailure) .Go(); } /// <summary> /// Create child topics recursively /// </summary> /// <param name="node"></param> /// <param name="numberOfChildren"></param> /// <param name="currentLevel"></param> /// <param name="maxLevel"></param> internal void FillWithChildTopics(TreeNode<AzureServiceBusTopicInfo> node, int numberOfChildren, int currentLevel = 0, int maxLevel = 1) { if (currentLevel == maxLevel) { return; } this.Report($"Will create {numberOfChildren} child topics/subscriptions to {node.Value.Name} (not actual, just topology)"); for (int i = 1; i <= numberOfChildren; i++) { var child = new TreeNode<AzureServiceBusTopicInfo>(new AzureServiceBusTopicInfo() { Name = $"{node.Value.Name}-{i}" }); if (currentLevel != maxLevel) { this.FillWithChildTopics(child, numberOfChildren, currentLevel + 1, maxLevel); } node.AddChild(child); } } /// <summary> /// Report something on the reporting delegate if it is not null /// </summary> /// <param name="progress"></param> internal void Report(string progress) { this.reportAction?.Invoke(progress); } public object Clone() { AzureServiceBusTopology clone = new AzureServiceBusTopology(this.rootNamespaceName, this.topicName, this.management, this.location, this.maxSubscribersPerTopic); return clone; } } }
using System; using System.Collections.Generic; using System.Net; using System.Xml; namespace Recurly { /// <summary> /// Represents subscriptions for accounts /// </summary> public class Subscription : RecurlyEntity { // changed to flags based on https://dev.recurly.com/docs/list-subscriptions saying Subscriptions can be in multiple states [Flags] // The currently valid Subscription States public enum SubscriptionState : short { All = 0, Active = 1, Canceled = 2, Expired = 4, Future = 8, InTrial = 16, Live = 32, PastDue = 64, Pending = 128 } public enum ChangeTimeframe : short { Now, Renewal } public enum RefundType : short { Full, Partial, None } public Address Address { get { return _address ?? (_address = new Address()); } set { _address = value; } } private Address _address; private string _accountCode; private Account _account; /// <summary> /// Account in Recurly /// </summary> public Account Account { get { return _account ?? (_account = Accounts.Get(_accountCode)); } } private Plan _plan; private string _planCode; // TODO expose publicly, avoid need to hit API for the Plan public Plan Plan { get { return _plan ?? (_plan = Plans.Get(_planCode)); } set { _plan = value; _planCode = value.PlanCode; } } public string Uuid { get; private set; } public SubscriptionState State { get; private set; } /// <summary> /// Unit amount per quantity. Leave null to keep as is. Set to override plan's default amount. /// </summary> public int? UnitAmountInCents { get; set; } public string Currency { get; set; } public int Quantity { get; set; } public bool? Bulk { get; set; } /// <summary> /// Date the subscription started. /// </summary> public DateTime? ActivatedAt { get; private set; } /// <summary> /// If set, the date the subscriber canceled their subscription. /// </summary> public DateTime? CanceledAt { get; private set; } /// <summary> /// If set, the subscription will expire/terminate on this date. /// </summary> public DateTime? ExpiresAt { get; private set; } /// <summary> /// Date the current invoice period started. /// </summary> public DateTime? CurrentPeriodStartedAt { get; private set; } /// <summary> /// The subscription is paid until this date. Next invoice date. /// </summary> public DateTime? CurrentPeriodEndsAt { get; private set; } /// <summary> /// Date the trial started, if the subscription has a trial. /// </summary> public DateTime? TrialPeriodStartedAt { get; private set; } /// <summary> /// Date the Bank Account has been authorized for this subscription /// </summary> public DateTime? BankAccountAuthorizedAt { get; set; } /// <summary> /// Date the trial ends, if the subscription has/had a trial. /// /// This may optionally be set on new subscriptions to specify an exact time for the /// subscription to commence. The subscription will be active and in "trial" until /// this date. /// </summary> public DateTime? TrialPeriodEndsAt { get { return _trialPeriodEndsAt; } set { if (ActivatedAt.HasValue) throw new InvalidOperationException("Cannot set TrialPeriodEndsAt on existing subscriptions."); if (value.HasValue && (value < DateTime.UtcNow)) throw new ArgumentException("TrialPeriodEndsAt must occur in the future."); _trialPeriodEndsAt = value; } } private DateTime? _trialPeriodEndsAt; /// <summary> /// If set, the subscription will begin in the future on this date. /// The subscription will apply the setup fee and trial period, unless the plan has no trial. /// </summary> public DateTime? StartsAt { get; set; } /// <summary> /// Represents pending changes to the subscription /// </summary> public Subscription PendingSubscription { get; private set; } /// <summary> /// If true, this is a "pending subscription" object and no changes are allowed /// </summary> private bool IsPendingSubscription { get; set; } private Coupon _coupon; private string _couponCode; private Coupon[] _coupons; private string[] _couponCodes; /// <summary> /// Optional coupon for the subscription /// </summary> public Coupon Coupon { get { return _coupon ?? (_coupon = Recurly.Coupons.Get(_couponCode)); } set { _coupon = value; _couponCode = value.CouponCode; } } /// <summary> /// Optional coupons for the subscription /// </summary> public Coupon[] Coupons { get { if (_coupons == null) { _coupons = new Coupon[_couponCodes.Length]; } if ( _coupons.Length == 0) { for (int i = 0; i<_couponCodes.Length; i++) { _coupons[i] = Recurly.Coupons.Get(_couponCodes[i]); } } return _coupons; } set { _coupons = value; _couponCodes = new string[_coupons.Length]; for (int i = 0; i<_coupons.Length; i++) { _couponCodes[i] = _coupons[i].CouponCode; } } } /// <summary> /// List of add ons for this subscription /// </summary> public SubscriptionAddOnList AddOns { get { return _addOns ?? (_addOns = new SubscriptionAddOnList(this)); } set { _addOns = value; } } private SubscriptionAddOnList _addOns; /// <summary> /// The invoice generated when calling the Preview method /// </summary> public Invoice InvoicePreview { get; private set; } public int? TotalBillingCycles { get; set; } public DateTime? FirstRenewalDate { get; set; } internal const string UrlPrefix = "/subscriptions/"; public string CollectionMethod { get; set; } public int? NetTerms { get; set; } public string PoNumber { get; set; } /// <summary> /// Amount of tax or VAT within the transaction, in cents. /// </summary> public int? TaxInCents { get; private set; } /// <summary> /// Tax type as "vat" for VAT or "usst" for US Sales Tax. /// </summary> public string TaxType { get; private set; } /// <summary> /// Tax rate that will be applied to this subscription. /// </summary> public decimal? TaxRate { get; private set; } /// <summary> /// Determines if this object exists in the Recurly API /// </summary> internal bool _saved; internal bool _preview; public string CustomerNotes { get; set; } public string TermsAndConditions { get; set; } public string VatReverseChargeNotes { get; set; } internal Subscription() { IsPendingSubscription = false; } internal Subscription(XmlTextReader reader) { ReadXml(reader); } /// <summary> /// Creates a new subscription object /// </summary> /// <param name="account"></param> /// <param name="plan"></param> /// <param name="currency"></param> public Subscription(Account account, Plan plan, string currency) { _accountCode = account.AccountCode; _account = account; Plan = plan; Currency = currency; Quantity = 1; } /// <summary> /// Creates a new subscription object, with coupon /// </summary> /// <param name="account"></param> /// <param name="plan"></param> /// <param name="currency"></param> /// <param name="couponCode"></param> public Subscription(Account account, Plan plan, string currency, string couponCode) { _accountCode = account.AccountCode; _account = account; Plan = plan; Currency = currency; Quantity = 1; _couponCode = couponCode; } /// <summary> /// Creates a new subscription on Recurly /// </summary> public void Create() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Post, UrlPrefix, WriteSubscriptionXml, ReadXml); } /// <summary> /// Request that an update to a subscription take place /// </summary> /// <param name="timeframe">when the update should occur: now (default) or at renewal</param> public void ChangeSubscription(ChangeTimeframe timeframe) { Client.WriteXmlDelegate writeXmlDelegate; if (ChangeTimeframe.Renewal == timeframe) writeXmlDelegate = WriteChangeSubscriptionAtRenewalXml; else writeXmlDelegate = WriteChangeSubscriptionNowXml; Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid), writeXmlDelegate, ReadXml); } public void ChangeSubscription() { ChangeSubscription(ChangeTimeframe.Now); } /// <summary> /// Cancel an active subscription. The subscription will not renew, but will continue to be active /// through the remainder of the current term. /// </summary> public void Cancel() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid) + "/cancel", ReadXml); } /// <summary> /// Reactivate a canceled subscription. The subscription will renew at the end of its current term. /// </summary> public void Reactivate() { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid) + "/reactivate", ReadXml); } /// <summary> /// Terminates the subscription immediately. /// </summary> /// <param name="refund"></param> public void Terminate(RefundType refund) { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid) + "/terminate?refund=" + refund.ToString().EnumNameToTransportCase(), ReadXml); } /// <summary> /// Transforms this object into a preview Subscription applied to the account. /// </summary> /// <param name="timeframe">ChangeTimeframe.Now (default) or at Renewal</param> public void Preview(ChangeTimeframe timeframe) { if (_saved) { throw new Recurly.RecurlyException("Cannot preview an existing subscription."); } Client.Instance.PerformRequest(Client.HttpRequestMethod.Post, UrlPrefix + "preview", WriteSubscriptionXml, ReadXml); // this method does not save the object _saved = false; } public void Preview() { Preview(ChangeTimeframe.Now); } /// <summary> /// Preview the changes associated with the current subscription /// </summary> /// <param name="timeframe">ChangeTimeframe.Now (default) or at Renewal</param> public virtual Subscription PreviewChange(ChangeTimeframe timeframe) { if (!_saved) { throw new Recurly.RecurlyException("Must have an existing subscription to preview changes."); } Client.WriteXmlDelegate writeXmlDelegate; if (ChangeTimeframe.Renewal == timeframe) writeXmlDelegate = WriteChangeSubscriptionAtRenewalXml; else writeXmlDelegate = WriteChangeSubscriptionNowXml; var previewSubscription = new Subscription(); var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Post, UrlPrefix + Uri.EscapeUriString(Uuid) + "/preview", writeXmlDelegate, previewSubscription.ReadPreviewXml); return statusCode == HttpStatusCode.NotFound ? null : previewSubscription; } public virtual Subscription PreviewChange() { return PreviewChange(ChangeTimeframe.Now); } /// <summary> /// For an active subscription, this will pause the subscription until the specified date. /// </summary> /// <param name="nextRenewalDate">The specified time the subscription will be postponed</param> /// <param name="bulk">bulk = false (default) or true to bypass the 60 second wait while postponing</param> public void Postpone(DateTime nextRenewalDate, bool bulk = false) { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid) + "/postpone?next_renewal_date=" + nextRenewalDate.ToString("yyyy-MM-ddThh:mm:ssZ") + "&bulk=" + bulk.ToString().ToLower(), ReadXml); } public bool UpdateNotes(Dictionary<string, string> notes) { Client.Instance.PerformRequest(Client.HttpRequestMethod.Put, UrlPrefix + Uri.EscapeUriString(Uuid) + "/notes", WriteSubscriptionNotesXml(notes), ReadXml); CustomerNotes = notes["CustomerNotes"]; TermsAndConditions = notes["TermsAndConditions"]; VatReverseChargeNotes = notes["VatReverseChargeNotes"]; return true; } public RecurlyList<CouponRedemption> GetRedemptions() { var coupons = new CouponRedemptionList(); var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get, UrlPrefix + Uri.EscapeUriString(Uuid) + "/redemptions/", coupons.ReadXmlList); return statusCode == HttpStatusCode.NotFound ? null : coupons; } #region Read and Write XML documents internal void ReadPlanXml(XmlTextReader reader) { while (reader.Read()) { if (reader.Name == "plan" && reader.NodeType == XmlNodeType.EndElement) break; if (reader.NodeType != XmlNodeType.Element) continue; switch (reader.Name) { case "plan_code": _planCode = reader.ReadElementContentAsString(); break; } } } internal void ReadPreviewXml(XmlTextReader reader) { _preview = true; ReadXml(reader); } internal override void ReadXml(XmlTextReader reader) { _saved = true; string href; while (reader.Read()) { if (reader.Name == "subscription" && reader.NodeType == XmlNodeType.EndElement) break; if (reader.NodeType != XmlNodeType.Element) continue; DateTime dateVal; Int32 billingCycles; switch (reader.Name) { case "account": href = reader.GetAttribute("href"); if (null != href) _accountCode = Uri.UnescapeDataString(href.Substring(href.LastIndexOf("/") + 1)); break; case "plan": ReadPlanXml(reader); break; case "uuid": Uuid = reader.ReadElementContentAsString(); break; case "state": State = reader.ReadElementContentAsString().ParseAsEnum<SubscriptionState>(); break; case "unit_amount_in_cents": UnitAmountInCents = reader.ReadElementContentAsInt(); break; case "currency": Currency = reader.ReadElementContentAsString(); break; case "quantity": Quantity = reader.ReadElementContentAsInt(); break; case "activated_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) ActivatedAt = dateVal; break; case "canceled_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) CanceledAt = dateVal; break; case "expires_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) ExpiresAt = dateVal; break; case "current_period_started_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) CurrentPeriodStartedAt = dateVal; break; case "current_period_ends_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) CurrentPeriodEndsAt = dateVal; break; case "trial_started_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) TrialPeriodStartedAt = dateVal; break; case "trial_ends_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) _trialPeriodEndsAt = dateVal; break; case "bank_account_authorized_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) BankAccountAuthorizedAt = dateVal; break; case "subscription_add_ons": // overwrite existing list with what came back from Recurly AddOns = new SubscriptionAddOnList(this); AddOns.ReadXml(reader); break; case "invoice": href = reader.GetAttribute("href"); //only parse the invoice xml if it's not just a link if (string.IsNullOrEmpty(href)) InvoicePreview = new Invoice(reader); break; case "pending_subscription": PendingSubscription = new Subscription { IsPendingSubscription = true }; PendingSubscription.ReadPendingSubscription(reader); // TODO test all returned properties are read break; case "collection_method": CollectionMethod = reader.ReadElementContentAsString(); break; case "net_terms": NetTerms = reader.ReadElementContentAsInt(); break; case "po_number": PoNumber = reader.ReadElementContentAsString(); break; case "total_billing_cycles": if (Int32.TryParse(reader.ReadElementContentAsString(), out billingCycles)) TotalBillingCycles = billingCycles; break; case "tax_in_cents": TaxInCents = reader.ReadElementContentAsInt(); break; case "tax_type": TaxType = reader.ReadElementContentAsString(); break; case "tax_rate": TaxRate = reader.ReadElementContentAsDecimal(); break; case "customer_notes": CustomerNotes = reader.ReadElementContentAsString(); break; case "terms_and_conditions": TermsAndConditions = reader.ReadElementContentAsString(); break; case "vat_reverse_charge_notes": VatReverseChargeNotes = reader.ReadElementContentAsString(); break; case "address": Address = new Address(reader); break; } } } internal override void WriteXml(XmlTextWriter writer) { throw new NotImplementedException(); } protected void ReadPendingSubscription(XmlTextReader reader) { while (reader.Read()) { if (reader.Name == "pending_subscription" && reader.NodeType == XmlNodeType.EndElement) break; if (reader.NodeType != XmlNodeType.Element) continue; switch (reader.Name) { case "plan": ReadPlanXml(reader); break; case "unit_amount_in_cents": UnitAmountInCents = reader.ReadElementContentAsInt(); break; case "quantity": Quantity = reader.ReadElementContentAsInt(); break; case "subscription_add_ons": AddOns = new SubscriptionAddOnList(this); AddOns.ReadXml(reader); break; } } } protected void WriteSubscriptionXml(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("subscription"); // Start: subscription xmlWriter.WriteElementString("plan_code", _planCode); xmlWriter.WriteElementString("currency", Currency); xmlWriter.WriteIfCollectionHasAny("subscription_add_ons", AddOns); xmlWriter.WriteStringIfValid("coupon_code", _couponCode); if (_couponCodes != null && _couponCodes.Length != 0) { xmlWriter.WriteStartElement("coupon_codes"); foreach (var _coupon_code in _couponCodes) { xmlWriter.WriteElementString("coupon_code", _coupon_code); } xmlWriter.WriteEndElement(); } xmlWriter.WriteElementString("customer_notes", CustomerNotes); xmlWriter.WriteElementString("terms_and_conditions", TermsAndConditions); xmlWriter.WriteElementString("vat_reverse_charge_notes", VatReverseChargeNotes); if (UnitAmountInCents.HasValue) xmlWriter.WriteElementString("unit_amount_in_cents", UnitAmountInCents.Value.AsString()); xmlWriter.WriteElementString("quantity", Quantity.AsString()); if (TrialPeriodEndsAt.HasValue) xmlWriter.WriteElementString("trial_ends_at", TrialPeriodEndsAt.Value.ToString("s")); if (BankAccountAuthorizedAt.HasValue) xmlWriter.WriteElementString("bank_account_authorized_at", BankAccountAuthorizedAt.Value.ToString("s")); if (StartsAt.HasValue) xmlWriter.WriteElementString("starts_at", StartsAt.Value.ToString("s")); if (TotalBillingCycles.HasValue) xmlWriter.WriteElementString("total_billing_cycles", TotalBillingCycles.Value.AsString()); if (FirstRenewalDate.HasValue) xmlWriter.WriteElementString("first_renewal_date", FirstRenewalDate.Value.ToString("s")); if (Bulk.HasValue) xmlWriter.WriteElementString("bulk", Bulk.ToString().ToLower()); if (CollectionMethod.Like("manual")) { xmlWriter.WriteElementString("collection_method", "manual"); xmlWriter.WriteElementString("net_terms", NetTerms.Value.AsString()); xmlWriter.WriteElementString("po_number", PoNumber); } else if (CollectionMethod.Like("automatic")) xmlWriter.WriteElementString("collection_method", "automatic"); // <account> and billing info Account.WriteXml(xmlWriter); xmlWriter.WriteEndElement(); // End: subscription } protected void WriteChangeSubscriptionNowXml(XmlTextWriter xmlWriter) { WriteChangeSubscriptionXml(xmlWriter, ChangeTimeframe.Now); } protected void WriteChangeSubscriptionAtRenewalXml(XmlTextWriter xmlWriter) { WriteChangeSubscriptionXml(xmlWriter, ChangeTimeframe.Renewal); } protected void WriteChangeSubscriptionXml(XmlTextWriter xmlWriter, ChangeTimeframe timeframe) { xmlWriter.WriteStartElement("subscription"); // Start: subscription xmlWriter.WriteElementString("timeframe", timeframe.ToString().EnumNameToTransportCase()); xmlWriter.WriteElementString("quantity", Quantity.AsString()); xmlWriter.WriteStringIfValid("plan_code", _planCode); xmlWriter.WriteIfCollectionHasAny("subscription_add_ons", AddOns); xmlWriter.WriteStringIfValid("coupon_code", _couponCode); if (_couponCodes != null && _couponCodes.Length != 0) { xmlWriter.WriteStartElement("coupon_codes"); foreach (var _coupon_code in _couponCodes) { xmlWriter.WriteElementString("coupon_code", _coupon_code); } xmlWriter.WriteEndElement(); } if (UnitAmountInCents.HasValue) xmlWriter.WriteElementString("unit_amount_in_cents", UnitAmountInCents.Value.AsString()); if (CollectionMethod.Like("manual")) { xmlWriter.WriteElementString("collection_method", "manual"); xmlWriter.WriteElementString("net_terms", NetTerms.Value.AsString()); xmlWriter.WriteElementString("po_number", PoNumber); } else if (CollectionMethod.Like("automatic")) xmlWriter.WriteElementString("collection_method", "automatic"); xmlWriter.WriteEndElement(); // End: subscription } internal Client.WriteXmlDelegate WriteSubscriptionNotesXml(Dictionary<string, string> notes) { return delegate(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("subscription"); // Start: subscription xmlWriter.WriteElementString("customer_notes", notes["CustomerNotes"]); xmlWriter.WriteElementString("terms_and_conditions", notes["TermsAndConditions"]); xmlWriter.WriteElementString("vat_reverse_charge_notes", notes["VatReverseChargeNotes"]); xmlWriter.WriteEndElement(); // End: subscription }; } #endregion #region Object Overrides public override string ToString() { return "Recurly Subscription: " + Uuid; } public override bool Equals(object obj) { var sub = obj as Subscription; return sub != null && Equals(sub); } public bool Equals(Subscription subscription) { return Uuid == subscription.Uuid; } public override int GetHashCode() { return Uuid.GetHashCode(); } #endregion } public sealed class Subscriptions { /// <summary> /// Returns a list of recurly subscriptions /// /// A subscription will belong to more than one state. /// </summary> /// <param name="state">State of subscriptions to return, defaults to "live"</param> /// <returns></returns> public static RecurlyList<Subscription> List(Subscription.SubscriptionState state = Subscription.SubscriptionState.Live) { return new SubscriptionList(Subscription.UrlPrefix + "?state=" + state.ToString().EnumNameToTransportCase()); } public static Subscription Get(string uuid) { var s = new Subscription(); var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get, Subscription.UrlPrefix + Uri.EscapeUriString(uuid), s.ReadXml); return statusCode == HttpStatusCode.NotFound ? null : s; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// A virtual network /// First published in XenServer 4.0. /// </summary> public partial class Network : XenObject<Network> { public Network() { } public Network(string uuid, string name_label, string name_description, List<network_operations> allowed_operations, Dictionary<string, network_operations> current_operations, List<XenRef<VIF>> VIFs, List<XenRef<PIF>> PIFs, long MTU, Dictionary<string, string> other_config, string bridge, bool managed, Dictionary<string, XenRef<Blob>> blobs, string[] tags, network_default_locking_mode default_locking_mode, Dictionary<XenRef<VIF>, string> assigned_ips, List<network_purpose> purpose) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.VIFs = VIFs; this.PIFs = PIFs; this.MTU = MTU; this.other_config = other_config; this.bridge = bridge; this.managed = managed; this.blobs = blobs; this.tags = tags; this.default_locking_mode = default_locking_mode; this.assigned_ips = assigned_ips; this.purpose = purpose; } /// <summary> /// Creates a new Network from a Proxy_Network. /// </summary> /// <param name="proxy"></param> public Network(Proxy_Network proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Network update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; allowed_operations = update.allowed_operations; current_operations = update.current_operations; VIFs = update.VIFs; PIFs = update.PIFs; MTU = update.MTU; other_config = update.other_config; bridge = update.bridge; managed = update.managed; blobs = update.blobs; tags = update.tags; default_locking_mode = update.default_locking_mode; assigned_ips = update.assigned_ips; purpose = update.purpose; } internal void UpdateFromProxy(Proxy_Network proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<network_operations>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_network_operations(proxy.current_operations); VIFs = proxy.VIFs == null ? null : XenRef<VIF>.Create(proxy.VIFs); PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs); MTU = proxy.MTU == null ? 0 : long.Parse((string)proxy.MTU); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); bridge = proxy.bridge == null ? null : (string)proxy.bridge; managed = (bool)proxy.managed; blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs); tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags; default_locking_mode = proxy.default_locking_mode == null ? (network_default_locking_mode) 0 : (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)proxy.default_locking_mode); assigned_ips = proxy.assigned_ips == null ? null : Maps.convert_from_proxy_XenRefVIF_string(proxy.assigned_ips); purpose = proxy.purpose == null ? null : Helper.StringArrayToEnumList<network_purpose>(proxy.purpose); } public Proxy_Network ToProxy() { Proxy_Network result_ = new Proxy_Network(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {}; result_.current_operations = Maps.convert_to_proxy_string_network_operations(current_operations); result_.VIFs = (VIFs != null) ? Helper.RefListToStringArray(VIFs) : new string[] {}; result_.PIFs = (PIFs != null) ? Helper.RefListToStringArray(PIFs) : new string[] {}; result_.MTU = MTU.ToString(); result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.bridge = bridge ?? ""; result_.managed = managed; result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs); result_.tags = tags; result_.default_locking_mode = network_default_locking_mode_helper.ToString(default_locking_mode); result_.assigned_ips = Maps.convert_to_proxy_XenRefVIF_string(assigned_ips); result_.purpose = (purpose != null) ? Helper.ObjectListToStringArray(purpose) : new string[] {}; return result_; } /// <summary> /// Creates a new Network from a Hashtable. /// </summary> /// <param name="table"></param> public Network(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); allowed_operations = Helper.StringArrayToEnumList<network_operations>(Marshalling.ParseStringArray(table, "allowed_operations")); current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations")); VIFs = Marshalling.ParseSetRef<VIF>(table, "VIFs"); PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs"); MTU = Marshalling.ParseLong(table, "MTU"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); bridge = Marshalling.ParseString(table, "bridge"); managed = Marshalling.ParseBool(table, "managed"); blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); tags = Marshalling.ParseStringArray(table, "tags"); default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode")); assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips")); purpose = Helper.StringArrayToEnumList<network_purpose>(Marshalling.ParseStringArray(table, "purpose")); } public bool DeepEquals(Network other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._VIFs, other._VIFs) && Helper.AreEqual2(this._PIFs, other._PIFs) && Helper.AreEqual2(this._MTU, other._MTU) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._bridge, other._bridge) && Helper.AreEqual2(this._managed, other._managed) && Helper.AreEqual2(this._blobs, other._blobs) && Helper.AreEqual2(this._tags, other._tags) && Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) && Helper.AreEqual2(this._assigned_ips, other._assigned_ips) && Helper.AreEqual2(this._purpose, other._purpose); } public override string SaveChanges(Session session, string opaqueRef, Network server) { if (opaqueRef == null) { Proxy_Network p = this.ToProxy(); return session.proxy.network_create(session.uuid, p).parse(); } else { if (!Helper.AreEqual2(_name_label, server._name_label)) { Network.set_name_label(session, opaqueRef, _name_label); } if (!Helper.AreEqual2(_name_description, server._name_description)) { Network.set_name_description(session, opaqueRef, _name_description); } if (!Helper.AreEqual2(_MTU, server._MTU)) { Network.set_MTU(session, opaqueRef, _MTU); } if (!Helper.AreEqual2(_other_config, server._other_config)) { Network.set_other_config(session, opaqueRef, _other_config); } if (!Helper.AreEqual2(_tags, server._tags)) { Network.set_tags(session, opaqueRef, _tags); } return null; } } /// <summary> /// Get a record containing the current state of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Network get_record(Session session, string _network) { return new Network((Proxy_Network)session.proxy.network_get_record(session.uuid, _network ?? "").parse()); } /// <summary> /// Get a reference to the network instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Network> get_by_uuid(Session session, string _uuid) { return XenRef<Network>.Create(session.proxy.network_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Create a new network instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Network> create(Session session, Network _record) { return XenRef<Network>.Create(session.proxy.network_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Create a new network instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Network _record) { return XenRef<Task>.Create(session.proxy.async_network_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified network instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static void destroy(Session session, string _network) { session.proxy.network_destroy(session.uuid, _network ?? "").parse(); } /// <summary> /// Destroy the specified network instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static XenRef<Task> async_destroy(Session session, string _network) { return XenRef<Task>.Create(session.proxy.async_network_destroy(session.uuid, _network ?? "").parse()); } /// <summary> /// Get all the network instances with the given label. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Network>> get_by_name_label(Session session, string _label) { return XenRef<Network>.Create(session.proxy.network_get_by_name_label(session.uuid, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_uuid(Session session, string _network) { return (string)session.proxy.network_get_uuid(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the name/label field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_name_label(Session session, string _network) { return (string)session.proxy.network_get_name_label(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the name/description field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_name_description(Session session, string _network) { return (string)session.proxy.network_get_name_description(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the allowed_operations field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<network_operations> get_allowed_operations(Session session, string _network) { return Helper.StringArrayToEnumList<network_operations>(session.proxy.network_get_allowed_operations(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the current_operations field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, network_operations> get_current_operations(Session session, string _network) { return Maps.convert_from_proxy_string_network_operations(session.proxy.network_get_current_operations(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the VIFs field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<XenRef<VIF>> get_VIFs(Session session, string _network) { return XenRef<VIF>.Create(session.proxy.network_get_vifs(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the PIFs field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<XenRef<PIF>> get_PIFs(Session session, string _network) { return XenRef<PIF>.Create(session.proxy.network_get_pifs(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the MTU field of the given network. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static long get_MTU(Session session, string _network) { return long.Parse((string)session.proxy.network_get_mtu(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, string> get_other_config(Session session, string _network) { return Maps.convert_from_proxy_string_string(session.proxy.network_get_other_config(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the bridge field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_bridge(Session session, string _network) { return (string)session.proxy.network_get_bridge(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the managed field of the given network. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static bool get_managed(Session session, string _network) { return (bool)session.proxy.network_get_managed(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the blobs field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _network) { return Maps.convert_from_proxy_string_XenRefBlob(session.proxy.network_get_blobs(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the tags field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string[] get_tags(Session session, string _network) { return (string [])session.proxy.network_get_tags(session.uuid, _network ?? "").parse(); } /// <summary> /// Get the default_locking_mode field of the given network. /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static network_default_locking_mode get_default_locking_mode(Session session, string _network) { return (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)session.proxy.network_get_default_locking_mode(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the assigned_ips field of the given network. /// First published in XenServer 6.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<XenRef<VIF>, string> get_assigned_ips(Session session, string _network) { return Maps.convert_from_proxy_XenRefVIF_string(session.proxy.network_get_assigned_ips(session.uuid, _network ?? "").parse()); } /// <summary> /// Get the purpose field of the given network. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<network_purpose> get_purpose(Session session, string _network) { return Helper.StringArrayToEnumList<network_purpose>(session.proxy.network_get_purpose(session.uuid, _network ?? "").parse()); } /// <summary> /// Set the name/label field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_label">New value to set</param> public static void set_name_label(Session session, string _network, string _label) { session.proxy.network_set_name_label(session.uuid, _network ?? "", _label ?? "").parse(); } /// <summary> /// Set the name/description field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_description">New value to set</param> public static void set_name_description(Session session, string _network, string _description) { session.proxy.network_set_name_description(session.uuid, _network ?? "", _description ?? "").parse(); } /// <summary> /// Set the MTU field of the given network. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_mtu">New value to set</param> public static void set_MTU(Session session, string _network, long _mtu) { session.proxy.network_set_mtu(session.uuid, _network ?? "", _mtu.ToString()).parse(); } /// <summary> /// Set the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _network, Dictionary<string, string> _other_config) { session.proxy.network_set_other_config(session.uuid, _network ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _network, string _key, string _value) { session.proxy.network_add_to_other_config(session.uuid, _network ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _network, string _key) { session.proxy.network_remove_from_other_config(session.uuid, _network ?? "", _key ?? "").parse(); } /// <summary> /// Set the tags field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_tags">New value to set</param> public static void set_tags(Session session, string _network, string[] _tags) { session.proxy.network_set_tags(session.uuid, _network ?? "", _tags).parse(); } /// <summary> /// Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">New value to add</param> public static void add_tags(Session session, string _network, string _value) { session.proxy.network_add_tags(session.uuid, _network ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">Value to remove</param> public static void remove_tags(Session session, string _network, string _value) { session.proxy.network_remove_tags(session.uuid, _network ?? "", _value ?? "").parse(); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type) { return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.uuid, _network ?? "", _name ?? "", _mime_type ?? "").parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type) { return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.uuid, _network ?? "", _name ?? "", _mime_type ?? "").parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> /// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param> public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public) { return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.uuid, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> /// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param> public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public) { return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.uuid, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse()); } /// <summary> /// Set the default locking mode for VIFs attached to this network /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The default locking mode for VIFs attached to this network.</param> public static void set_default_locking_mode(Session session, string _network, network_default_locking_mode _value) { session.proxy.network_set_default_locking_mode(session.uuid, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse(); } /// <summary> /// Set the default locking mode for VIFs attached to this network /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The default locking mode for VIFs attached to this network.</param> public static XenRef<Task> async_set_default_locking_mode(Session session, string _network, network_default_locking_mode _value) { return XenRef<Task>.Create(session.proxy.async_network_set_default_locking_mode(session.uuid, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse()); } /// <summary> /// Give a network a new purpose (if not present already) /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to add</param> public static void add_purpose(Session session, string _network, network_purpose _value) { session.proxy.network_add_purpose(session.uuid, _network ?? "", network_purpose_helper.ToString(_value)).parse(); } /// <summary> /// Give a network a new purpose (if not present already) /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to add</param> public static XenRef<Task> async_add_purpose(Session session, string _network, network_purpose _value) { return XenRef<Task>.Create(session.proxy.async_network_add_purpose(session.uuid, _network ?? "", network_purpose_helper.ToString(_value)).parse()); } /// <summary> /// Remove a purpose from a network (if present) /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to remove</param> public static void remove_purpose(Session session, string _network, network_purpose _value) { session.proxy.network_remove_purpose(session.uuid, _network ?? "", network_purpose_helper.ToString(_value)).parse(); } /// <summary> /// Remove a purpose from a network (if present) /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to remove</param> public static XenRef<Task> async_remove_purpose(Session session, string _network, network_purpose _value) { return XenRef<Task>.Create(session.proxy.async_network_remove_purpose(session.uuid, _network ?? "", network_purpose_helper.ToString(_value)).parse()); } /// <summary> /// Return a list of all the networks known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Network>> get_all(Session session) { return XenRef<Network>.Create(session.proxy.network_get_all(session.uuid).parse()); } /// <summary> /// Get all the network Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Network>, Network> get_all_records(Session session) { return XenRef<Network>.Create<Proxy_Network>(session.proxy.network_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<network_operations> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; Changed = true; NotifyPropertyChanged("allowed_operations"); } } } private List<network_operations> _allowed_operations; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, network_operations> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; Changed = true; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, network_operations> _current_operations; /// <summary> /// list of connected vifs /// </summary> public virtual List<XenRef<VIF>> VIFs { get { return _VIFs; } set { if (!Helper.AreEqual(value, _VIFs)) { _VIFs = value; Changed = true; NotifyPropertyChanged("VIFs"); } } } private List<XenRef<VIF>> _VIFs; /// <summary> /// list of connected pifs /// </summary> public virtual List<XenRef<PIF>> PIFs { get { return _PIFs; } set { if (!Helper.AreEqual(value, _PIFs)) { _PIFs = value; Changed = true; NotifyPropertyChanged("PIFs"); } } } private List<XenRef<PIF>> _PIFs; /// <summary> /// MTU in octets /// First published in XenServer 5.6. /// </summary> public virtual long MTU { get { return _MTU; } set { if (!Helper.AreEqual(value, _MTU)) { _MTU = value; Changed = true; NotifyPropertyChanged("MTU"); } } } private long _MTU; /// <summary> /// additional configuration /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; /// <summary> /// name of the bridge corresponding to this network on the local host /// </summary> public virtual string bridge { get { return _bridge; } set { if (!Helper.AreEqual(value, _bridge)) { _bridge = value; Changed = true; NotifyPropertyChanged("bridge"); } } } private string _bridge; /// <summary> /// true if the bridge is managed by xapi /// First published in XenServer 7.2. /// </summary> public virtual bool managed { get { return _managed; } set { if (!Helper.AreEqual(value, _managed)) { _managed = value; Changed = true; NotifyPropertyChanged("managed"); } } } private bool _managed; /// <summary> /// Binary blobs associated with this network /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, XenRef<Blob>> blobs { get { return _blobs; } set { if (!Helper.AreEqual(value, _blobs)) { _blobs = value; Changed = true; NotifyPropertyChanged("blobs"); } } } private Dictionary<string, XenRef<Blob>> _blobs; /// <summary> /// user-specified tags for categorization purposes /// First published in XenServer 5.0. /// </summary> public virtual string[] tags { get { return _tags; } set { if (!Helper.AreEqual(value, _tags)) { _tags = value; Changed = true; NotifyPropertyChanged("tags"); } } } private string[] _tags; /// <summary> /// The network will use this value to determine the behaviour of all VIFs where locking_mode = default /// First published in XenServer 6.1. /// </summary> public virtual network_default_locking_mode default_locking_mode { get { return _default_locking_mode; } set { if (!Helper.AreEqual(value, _default_locking_mode)) { _default_locking_mode = value; Changed = true; NotifyPropertyChanged("default_locking_mode"); } } } private network_default_locking_mode _default_locking_mode; /// <summary> /// The IP addresses assigned to VIFs on networks that have active xapi-managed DHCP /// First published in XenServer 6.5. /// </summary> public virtual Dictionary<XenRef<VIF>, string> assigned_ips { get { return _assigned_ips; } set { if (!Helper.AreEqual(value, _assigned_ips)) { _assigned_ips = value; Changed = true; NotifyPropertyChanged("assigned_ips"); } } } private Dictionary<XenRef<VIF>, string> _assigned_ips; /// <summary> /// Set of purposes for which the server will use this network /// First published in Unreleased. /// </summary> public virtual List<network_purpose> purpose { get { return _purpose; } set { if (!Helper.AreEqual(value, _purpose)) { _purpose = value; Changed = true; NotifyPropertyChanged("purpose"); } } } private List<network_purpose> _purpose; } }
// Metric.cs // // Author: // Allis Tauri <allista@gmail.com> // // Copyright (c) 2016 Allis Tauri using System.Collections.Generic; using UnityEngine; namespace AT_Utils { public struct MeshTransform { public Mesh m; public Transform t; public Renderer r; public bool Valid => m != null && t != null && r != null && t.gameObject != null; public MeshTransform(MeshFilter mesh_filter) { t = mesh_filter.transform; m = mesh_filter.sharedMesh; r = mesh_filter.GetComponent<MeshRenderer>(); } public MeshTransform(SkinnedMeshRenderer skin) { r = skin; t = skin.transform; m = new Mesh(); skin.BakeMesh(m); } } public struct Metric : IConfigNode { //convex hull public ConvexHull3D hull { get; private set; } Mesh _hull_mesh; public Mesh hull_mesh { get { if(_hull_mesh == null && hull != null) _hull_mesh = hull.MakeMesh(); return _hull_mesh; } } public float volume => hull == null ? bounds_volume : hull.Volume; public float area => hull == null ? bounds_area : hull.Area; //bounds public Bounds bounds { get; private set; } public Vector3 center => bounds.center; public Vector3 extents => bounds.extents; public Vector3 size => bounds.size; //physical properties public float bounds_volume { get; private set; } public float bounds_area { get; private set; } public float mass { get; set; } //part-vessel properties public int CrewCapacity { get; private set; } public float cost { get; set; } public bool Empty => bounds.size.IsZero(); static Vector3[] local2local(Transform _from, Transform _to, Vector3[] points) { if(_from != _to) for(int p = 0; p < points.Length; p++) points[p] = _to.InverseTransformPoint(_from.TransformPoint(points[p])); return points; } static Vector3[] local2world(Transform _from, Vector3[] points) { for(int p = 0; p < points.Length; p++) points[p] = _from.TransformPoint(points[p]); return points; } static Vector3[] world2local(Transform _to, Vector3[] points) { for(int p = 0; p < points.Length; p++) points[p] = _to.InverseTransformPoint(points[p]); return points; } static float boundsVolume(Bounds b) => b.size.x * b.size.y * b.size.z; static float boundsArea(Bounds b) => 2 * (b.size.x * b.size.y + b.size.x * b.size.z + b.size.y * b.size.z); static Bounds initBounds(Vector3[] edges) { var b = new Bounds(edges[0], new Vector3()); for(int i = 1; i < edges.Length; i++) b.Encapsulate(edges[i]); return b; } static void updateBounds(ref Bounds b, Vector3[] edges) { if(b == default(Bounds)) b = initBounds(edges); else for(int i = 0; i < edges.Length; i++) b.Encapsulate(edges[i]); } static void updateBounds(ref Bounds b, Bounds nb) { if(b == default(Bounds)) b = nb; else b.Encapsulate(nb); } Bounds partsBounds(IList<Part> parts, Transform refT, bool compute_hull, bool exclude_disabled = true) { //reset metric mass = 0; cost = 0; CrewCapacity = 0; Bounds b = default(Bounds); if(parts == null || parts.Count == 0) { Utils.Log("Metric.partsBounds: WARNING! No parts were provided."); return b; } //calculate bounds and convex hull float b_size = 0; List<Vector3> hull_points = compute_hull ? new List<Vector3>() : null; for(int i = 0, partsCount = parts.Count; i < partsCount; i++) { Part p = parts[i]; if(p == null) continue; //EditorLogic.SortedShipList returns List<Part>{null} when all parts are deleted //check for weels; if it's a wheel, get all meshes under the wheel collider var wheel = p.Modules.GetModule<ModuleWheelBase>(); var wheel_transform = wheel != null && wheel.Wheel != null && wheel.Wheel.wheelCollider != null ? wheel.Wheel.wheelCollider.wheelTransform : null; //check for asteroids var is_asteroid = p.Modules.GetModule<ModuleAsteroid>() != null; //check for bad parts var pname = p.partInfo != null ? p.partInfo.name : p.name; var bad_part = Utils.NameMatches(pname, AT_UtilsGlobals.Instance.BadPartsList); var part_rot = p.partTransform.rotation; if(bad_part) p.partTransform.rotation = Quaternion.identity; foreach(var mesh in p.AllModelMeshes()) { //skip disabled objects if(!mesh.Valid || exclude_disabled && (!mesh.r.enabled || !mesh.t.gameObject.activeInHierarchy)) continue; //skip meshes from the blacklist if(Utils.NameMatches(mesh.t.name, AT_UtilsGlobals.Instance.MeshesToSkipList)) continue; Vector3[] verts; if(bad_part) { verts = Utils.BoundCorners(mesh.r.bounds); for(int j = 0, len = verts.Length; j < len; j++) { var v = p.partTransform.position + part_rot * (verts[j] - p.partTransform.position); if(refT != null) v = refT.InverseTransformPoint(v); verts[j] = v; } } else { if(is_asteroid || wheel_transform != null && mesh.t.IsChildOf(wheel_transform) || (compute_hull && Vector3.Scale(mesh.m.bounds.size, mesh.t.lossyScale).sqrMagnitude > b_size / 10)) verts = mesh.m.uniqueVertices(); else verts = Utils.BoundCorners(mesh.m.bounds); verts = refT != null ? local2local(mesh.t, refT, verts) : local2world(mesh.t, verts); } updateBounds(ref b, verts); if(compute_hull) { hull_points.AddRange(verts); b_size = b.size.sqrMagnitude; } } CrewCapacity += p.CrewCapacity; mass += p.TotalMass(); cost += p.TotalCost(); if(bad_part) p.partTransform.rotation = part_rot; } if(compute_hull && hull_points.Count >= 4) { hull = new ConvexHull3D(hull_points); _hull_mesh = null; } return b; } #region Constructors //metric copy public Metric(Metric m) : this() { hull = m.hull; bounds = new Bounds(m.bounds.center, m.bounds.size); bounds_volume = m.bounds_volume; bounds_area = m.bounds_area; mass = m.mass; CrewCapacity = m.CrewCapacity; } //metric from bounds void init_with_bounds(Bounds b, float m, int crew_capacity) { bounds = b; bounds_volume = boundsVolume(b); bounds_area = boundsArea(b); mass = m; CrewCapacity = crew_capacity; } public Metric(Bounds b, float m = 0f, int crew_capacity = 0) : this() { init_with_bounds(b, m, crew_capacity); } //metric from size public Metric(Vector3 center, Vector3 size, float m = 0f, int crew_capacity = 0) : this(new Bounds(center, size), m, crew_capacity) { } public Metric(Vector3 size, float m = 0f, int crew_capacity = 0) : this(Vector3.zero, size, m, crew_capacity) { } //metric from volume public Metric(float V, float m = 0f, int crew_capacity = 0) : this() { var a = Mathf.Pow(V, 1 / 3f); init_with_bounds(new Bounds(Vector3.zero, new Vector3(a, a, a)), m, crew_capacity); } //metric form vertices public Metric(Vector3[] verts, float m = 0f, int crew_capacity = 0, bool compute_hull = false) : this() { if(compute_hull) hull = new ConvexHull3D(verts); bounds = initBounds(verts); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); mass = m; CrewCapacity = crew_capacity; } //metric from config node public Metric(ConfigNode node) : this() { Load(node); } //mesh metric void init_with_mesh(MeshFilter mesh, Transform refT, bool compute_hull) { Vector3[] verts = Utils.BoundCorners(mesh.sharedMesh.bounds); if(refT != null) local2local(mesh.transform, refT, verts); else local2world(mesh.transform, verts); if(compute_hull) { hull = refT != null ? new ConvexHull3D(local2local(mesh.transform, refT, mesh.sharedMesh.uniqueVertices())) : new ConvexHull3D(local2world(mesh.transform, mesh.sharedMesh.uniqueVertices())); } bounds = initBounds(verts); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); mass = 0f; } public Metric(MeshFilter mesh, Transform refT = null, bool compute_hull = false) : this() { init_with_mesh(mesh, refT, compute_hull); } public Metric(Transform transform, bool compute_hull = false, bool world_space = false) : this() { MeshFilter m = transform.gameObject.GetComponent<MeshFilter>(); if(m == null) { Utils.Log("[Metric] {} does not have MeshFilter component", transform.gameObject); return; } init_with_mesh(m, world_space ? null : transform, compute_hull); } public Metric(Part part, string mesh_name, bool compute_hull = false, bool world_space = false) : this() { MeshFilter m = part.FindModelComponent<MeshFilter>(mesh_name); if(m == null) { Utils.Log("[Metric] {} does not have '{}' mesh", part.name, mesh_name); return; } init_with_mesh(m, world_space ? null : part.transform, compute_hull); } //part metric public Metric(Part part, bool compute_hull = false, bool world_space = false) : this() { var exclude_disabled = part.partInfo != null && part != part.partInfo.partPrefab; bounds = partsBounds(new List<Part> { part }, world_space ? null : part.partTransform, compute_hull, exclude_disabled); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); } //vessel metric public Metric(Vessel vessel, bool compute_hull = false, bool world_space = false) : this() { bounds = partsBounds(vessel.parts, world_space ? null : vessel.vesselTransform, compute_hull); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); } //in-editor vessel metric public Metric(List<Part> vessel, bool compute_hull = false, bool world_space = false) : this() { bounds = partsBounds(vessel, world_space ? null : vessel[0].partTransform, compute_hull); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); } public Metric(IShipconstruct vessel, bool compute_hull = false, bool world_space = false) : this() { bounds = partsBounds(vessel.Parts, world_space ? null : vessel.Parts[0].partTransform, compute_hull); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); } #endregion //public methods public void Clear() { bounds = default(Bounds); bounds_volume = bounds_area = mass = cost = 0; CrewCapacity = 0; hull = null; } public Bounds GetBounds() { return new Bounds(bounds.center, bounds.size); } public void Scale(float s) { bounds = new Bounds(center, size * s); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); if(hull != null) hull = hull.Scale(s); } public void Save(ConfigNode node) { node.AddValue("bounds_center", ConfigNode.WriteVector(bounds.center)); node.AddValue("bounds_size", ConfigNode.WriteVector(bounds.size)); node.AddValue("crew_capacity", CrewCapacity); node.AddValue("mass", mass); node.AddValue("cost", cost); if(hull != null) hull.Save(node.AddNode("HULL")); } public void Load(ConfigNode node) { if(!node.HasValue("bounds_center") || !node.HasValue("bounds_size") || !node.HasValue("crew_capacity") || !node.HasValue("mass") || !node.HasValue("cost")) throw new KeyNotFoundException("Metric.Load: not all needed values are present in the config node."); Vector3 _center = ConfigNode.ParseVector3(node.GetValue("bounds_center")); Vector3 _size = ConfigNode.ParseVector3(node.GetValue("bounds_size")); bounds = new Bounds(_center, _size); bounds_volume = boundsVolume(bounds); bounds_area = boundsArea(bounds); CrewCapacity = int.Parse(node.GetValue("crew_capacity")); mass = float.Parse(node.GetValue("mass")); cost = float.Parse(node.GetValue("cost")); if(node.HasNode("HULL")) hull = ConvexHull3D.Load(node.GetNode("HULL")); } #region Fitting bool fits_somehow(List<float> _D) { var D = new List<float> { size.x, size.y, size.z }; D.Sort(); _D.Sort(); foreach(float d in D) { if(_D.Count == 0) break; int ud = -1; for(int i = 0; i < _D.Count; i++) { if(d <= _D[i]) { ud = i; break; } } if(ud < 0) return false; _D.RemoveAt(ud); } return true; } public bool FitsSomehow(Metric other) { var _D = new List<float> { other.size.x, other.size.y, other.size.z }; return fits_somehow(_D); } public bool FitsSomehow(Vector2 node) { var _D = new List<float> { node.x, node.y }; return fits_somehow(_D); } /// <summary> /// Returns true if THIS metric fits inside the OTHER metric. /// </summary> /// <param name="this_T">Transform of this metric.</param> /// <param name="other_T">Transform of the other metric.</param> /// <param name="other">Metric acting as a container.</param> /// <param name="offset">Places the center of THIS metric at the offset in this_T coordinates</param> public bool FitsAligned(Transform this_T, Transform other_T, Metric other, Vector3 offset = default(Vector3)) { offset -= center; var verts = hull != null ? hull.Points.ToArray() : Utils.BoundCorners(bounds); for(int i = 0; i < verts.Length; i++) { var v = other_T.InverseTransformPoint(this_T.position + this_T.TransformDirection(verts[i] + offset)); if(other.hull != null) { if(!other.hull.Contains(v)) return false; } else if(!other.bounds.Contains(v)) return false; } return true; } /// <summary> /// Returns true if THIS metric fits inside the given CONTAINER mesh. /// </summary> /// <param name="this_T">Transform of this metric.</param> /// <param name="container_T">Transform of the given mesh.</param> /// <param name="container">Mesh acting as a container.</param> /// <param name="offset">Places the center of THIS metric at the offset in this_T coordinates</param> /// Implemeted using algorithm described at /// http://answers.unity3d.com/questions/611947/am-i-inside-a-volume-without-colliders.html public bool FitsAligned(Transform this_T, Transform container_T, Mesh container, Vector3 offset = default(Vector3)) { offset -= center; //get vertices in containers reference frame var verts = hull != null ? hull.Points.ToArray() : Utils.BoundCorners(bounds); //check each triangle of container var c_verts = container.vertices; var triangles = container.triangles; var ntris = triangles.Length / 3; if(ntris > verts.Length) { for(int i = 0, len = verts.Length; i < len; i++) verts[i] = container_T.InverseTransformPoint(this_T.position + this_T.TransformDirection(verts[i] + offset)); for(int i = 0; i < ntris; i++) { int j = i * 3; var V1 = c_verts[triangles[j]]; var V2 = c_verts[triangles[j + 1]]; var V3 = c_verts[triangles[j + 2]]; var P = new Plane(V1, V2, V3); for(int k = 0, vertsLength = verts.Length; k < vertsLength; k++) { if(!P.GetSide(verts[k])) return false; } } } else { var planes = new Plane[triangles.Length / 3]; for(int i = 0; i < ntris; i++) { int j = i * 3; var V1 = c_verts[triangles[j]]; var V2 = c_verts[triangles[j + 1]]; var V3 = c_verts[triangles[j + 2]]; planes[i] = new Plane(V1, V2, V3); } for(int i = 0, len = verts.Length; i < len; i++) { var v = container_T.InverseTransformPoint(this_T.position + this_T.TransformDirection(verts[i] + offset)); for(int j = 0, planesLength = planes.Length; j < planesLength; j++) { if(!planes[j].GetSide(v)) return false; } } } return true; } #endregion #region Operators public static Metric operator *(Metric m, float scale) { var _new = new Metric(m); _new.Scale(scale); return _new; } public static Metric operator /(Metric m, float scale) => m * (1.0f / scale); //convenience functions public static float BoundsVolume(Part part) => (new Metric(part)).bounds_volume; public static float BoundsVolume(Vessel vessel) => (new Metric(vessel)).bounds_volume; public static float Volume(Part part) => (new Metric(part, true)).volume; public static float Volume(Vessel vessel) => (new Metric(vessel, true)).volume; #endregion #if DEBUG public void DrawBox(Transform vT) => Utils.GLDrawBounds(bounds, vT, Color.white); public void DrawCenter(Transform vT) => Utils.GLDrawPoint(vT.position + vT.TransformDirection(center), Color.white); public override string ToString() { return Utils.Format("hull: {}\n" + "bounds: {}\n" + "center: {}\n" + "extents: {}\n" + "size: {}\n" + "volume: {}\n" + "area: {}\n" + "mass: {}\n" + "cost: {}\n" + "CrewCapacity: {}\n" + "Empty: {}\n", hull, bounds, center, extents, size, volume, area, mass, cost, CrewCapacity, Empty); } #endif } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text { public static class JsonExtensions { public static T JsonTo<T>(this Dictionary<string, string> map, string key) { return Get<T>(map, key); } /// <summary> /// Get JSON string value converted to T /// </summary> public static T Get<T>(this Dictionary<string, string> map, string key, T defaultValue = default(T)) { return map.TryGetValue(key, out var strVal) ? JsonSerializer.DeserializeFromString<T>(strVal) : defaultValue; } public static T[] GetArray<T>(this Dictionary<string, string> map, string key) { return map.TryGetValue(key, out var value) ? (map is JsonObject obj ? value.FromJson<T[]>() : value.FromJsv<T[]>()) : TypeConstants<T>.EmptyArray; } /// <summary> /// Get JSON string value /// </summary> public static string Get(this Dictionary<string, string> map, string key) { return map.TryGetValue(key, out var strVal) ? JsonTypeSerializer.Instance.UnescapeString(strVal) : null; } public static JsonArrayObjects ArrayObjects(this string json) { return Text.JsonArrayObjects.Parse(json); } public static List<T> ConvertAll<T>(this JsonArrayObjects jsonArrayObjects, Func<JsonObject, T> converter) { var results = new List<T>(); foreach (var jsonObject in jsonArrayObjects) { results.Add(converter(jsonObject)); } return results; } public static T ConvertTo<T>(this JsonObject jsonObject, Func<JsonObject, T> converFn) { return jsonObject == null ? default(T) : converFn(jsonObject); } public static Dictionary<string, string> ToDictionary(this JsonObject jsonObject) { return jsonObject == null ? new Dictionary<string, string>() : new Dictionary<string, string>(jsonObject); } } public class JsonObject : Dictionary<string, string> { /// <summary> /// Get JSON string value /// </summary> public new string this[string key] { get => this.Get(key); set => base[key] = value; } public static JsonObject Parse(string json) { return JsonSerializer.DeserializeFromString<JsonObject>(json); } public static JsonArrayObjects ParseArray(string json) { return JsonArrayObjects.Parse(json); } public JsonArrayObjects ArrayObjects(string propertyName) { return this.TryGetValue(propertyName, out var strValue) ? JsonArrayObjects.Parse(strValue) : null; } public JsonObject Object(string propertyName) { return this.TryGetValue(propertyName, out var strValue) ? Parse(strValue) : null; } /// <summary> /// Get unescaped string value /// </summary> public string GetUnescaped(string key) { return base[key]; } /// <summary> /// Get unescaped string value /// </summary> public string Child(string key) { return base[key]; } /// <summary> /// Write JSON Array, Object, bool or number values as raw string /// </summary> public static void WriteValue(TextWriter writer, object value) { var strValue = value as string; if (!string.IsNullOrEmpty(strValue)) { var firstChar = strValue[0]; var lastChar = strValue[strValue.Length - 1]; if ((firstChar == JsWriter.MapStartChar && lastChar == JsWriter.MapEndChar) || (firstChar == JsWriter.ListStartChar && lastChar == JsWriter.ListEndChar) || JsonUtils.True == strValue || JsonUtils.False == strValue || IsJavaScriptNumber(strValue)) { writer.Write(strValue); return; } } JsonUtils.WriteString(writer, strValue); } private static bool IsJavaScriptNumber(string strValue) { var firstChar = strValue[0]; if (firstChar == '0') { if (strValue.Length == 1) return true; if (!strValue.Contains(".")) return false; } if (!strValue.Contains(".")) { if (long.TryParse(strValue, out var longValue)) { return longValue < JsonUtils.MaxInteger && longValue > JsonUtils.MinInteger; } return false; } if (double.TryParse(strValue, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var doubleValue)) { return doubleValue < JsonUtils.MaxInteger && doubleValue > JsonUtils.MinInteger; } return false; } public T ConvertTo<T>() { return (T)this.ConvertTo(typeof(T)); } public object ConvertTo(Type type) { var map = new Dictionary<string, object>(); foreach (var entry in this) { map[entry.Key] = entry.Value; } return map.FromObjectDictionary(type); } } public class JsonArrayObjects : List<JsonObject> { public static JsonArrayObjects Parse(string json) { return JsonSerializer.DeserializeFromString<JsonArrayObjects>(json); } } public interface IValueWriter { void WriteTo(ITypeSerializer serializer, TextWriter writer); } public struct JsonValue : IValueWriter { private readonly string json; public JsonValue(string json) { this.json = json; } public T As<T>() => JsonSerializer.DeserializeFromString<T>(json); public override string ToString() => json; public void WriteTo(ITypeSerializer serializer, TextWriter writer) => writer.Write(json ?? JsonUtils.Null); } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; namespace OpenQA.Selenium { [TestFixture] public class CorrectEventFiringTest : DriverTestFixture { [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")] public void ShouldFireFocusEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("focus"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ShouldFireClickEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("click"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ShouldFireMouseDownEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousedown"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ShouldFireMouseUpEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseup"); } [Test] [Category("Javascript")] public void ShouldFireMouseOverEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseover"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Firefox, "Firefox does not report mouse move event when clicking")] public void ShouldFireMouseMoveEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousemove"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldNotThrowIfEventHandlerThrows() { driver.Url = javascriptPage; driver.FindElement(By.Id("throwing-mouseover")).Click(); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")] public void ShouldFireEventsInTheRightOrder() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); string text = driver.FindElement(By.Id("result")).Text; int lastIndex = -1; List<string> eventList = new List<string>() { "mousedown", "focus", "mouseup", "click" }; foreach (string eventName in eventList) { int index = text.IndexOf(eventName); Assert.IsTrue(index != -1, eventName + " did not fire at all. Text is " + text); Assert.IsTrue(index > lastIndex, eventName + " did not fire in the correct order. Text is " + text); lastIndex = index; } } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ShouldIssueMouseDownEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mousedown")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] public void ShouldIssueClickEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseclick")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse click"); } [Test] [Category("Javascript")] public void ShouldIssueMouseUpEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseup")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse up"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] public void MouseEventsShouldBubbleUpToContainingElements() { driver.Url = javascriptPage; driver.FindElement(By.Id("child")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] public void ShouldEmitOnChangeEventsWhenSelectingElements() { driver.Url = javascriptPage; //Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector']//option")); String initialTextValue = driver.FindElement(By.Id("result")).Text; IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, initialTextValue); bar.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "IE does not fire change event when clicking on checkbox")] public void ShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox() { driver.Url = javascriptPage; IWebElement checkbox = driver.FindElement(By.Id("checkbox")); checkbox.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "checkbox thing"); } [Test] [Category("Javascript")] public void ShouldEmitClickEventWhenClickingOnATextInputElement() { driver.Url = javascriptPage; IWebElement clicker = driver.FindElement(By.Id("clickField")); clicker.Click(); Assert.AreEqual(clicker.GetAttribute("value"), "Clicked"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ShouldFireTwoClickEventsWhenClickingOnALabel() { driver.Url = javascriptPage; driver.FindElement(By.Id("labelForCheckbox")).Click(); IWebElement result = driver.FindElement(By.Id("result")); Assert.IsTrue(WaitFor(() => { return result.Text.Contains("labelclick chboxclick"); }, "Did not find text: " + result.Text)); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Android)] public void ClearingAnElementShouldCauseTheOnChangeHandlerToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("clearMe")); element.Clear(); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual(result.Text, "Cleared"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")] [IgnoreBrowser(Browser.Android)] public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); IWebElement element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")] [IgnoreBrowser(Browser.Android)] public void SendingKeysToAnElementShouldCauseTheFocusEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); AssertEventFired("focus"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "Input elements are blurred when the keyboard is closed.")] public void SendingKeysToAFocusedElementShouldNotBlurThatElement() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.Click(); //Wait until focused bool focused = false; IWebElement result = driver.FindElement(By.Id("result")); for (int i = 0; i < 5; ++i) { string fired = result.Text; if (fired.Contains("focus")) { focused = true; break; } try { System.Threading.Thread.Sleep(200); } catch (Exception e) { throw e; } } if (!focused) { Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing"); } element.SendKeys("a"); AssertEventNotFired("blur"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement formElement = driver.FindElement(By.Id("submitListeningForm")); formElement.Submit(); AssertEventFired("form-onsubmit"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormInputSubmitElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormInputTextElementShouldFireOnSubmitForThatFormAndNotClickOnThatInput() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit"); AssertEventNotFired("text-onclick"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void UploadingFileShouldFireOnChangeEvent() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); IWebElement result = driver.FindElement(By.Id("fileResults")); Assert.AreEqual(string.Empty, result.Text); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); // Shift focus to something else because send key doesn't make the focus leave driver.FindElement(By.Id("id-name1")).Click(); inputFile.Delete(); Assert.AreEqual("changed", result.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldReportTheXAndYCoordinatesWhenClicking() { driver.Url = clickEventPage; IWebElement element = driver.FindElement(By.Id("eventish")); element.Click(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2)); string clientX = driver.FindElement(By.Id("clientX")).Text; string clientY = driver.FindElement(By.Id("clientY")).Text; driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0)); Assert.AreNotEqual("0", clientX); Assert.AreNotEqual("0", clientY); } private void AssertEventNotFired(string eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsFalse(text.Contains(eventName), eventName + " fired: " + text); } private void ClickOnElementWhichRecordsEvents() { driver.FindElement(By.Id("plainButton")).Click(); } private void AssertEventFired(String eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains(eventName), "No " + eventName + " fired: " + text); } } }
using System; using System.Text; using System.Threading.Tasks; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NFluent; using WireMock.Handlers; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; using WireMock.Types; using WireMock.Util; using Xunit; namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsJsonPathTests { private const string ClientIp = "::1"; private readonly Mock<IFileSystemHandler> _filesystemHandlerMock; private readonly WireMockServerSettings _settings = new WireMockServerSettings(); public ResponseWithHandlebarsJsonPathTests() { _filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); _filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc"); _settings.FileSystemHandler = _filesystemHandlerMock.Object; } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Object_ResponseBodyAsJson() { // Assign var body = new BodyData { BodyAsString = @"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" }) .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson); Check.That(j["x"]).IsNotNull(); Check.That(j["x"]["Name"].ToString()).Equals("Acme Co"); } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Number_ResponseBodyAsJson() { // Assign var body = new BodyData { BodyAsString = "{ \"Price\": 99 }", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"..Price\"}}" }) .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson); Check.That(j["x"].Value<long>()).Equals(99); } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsJObject() { // Assign var body = new BodyData { BodyAsJson = JObject.Parse(@"{ 'Stores': [ 'Lambton Quay', 'Willis Street' ], 'Manufacturers': [ { 'Name': 'Acme Co', 'Products': [ { 'Name': 'Anvil', 'Price': 50 } ] }, { 'Name': 'Contoso', 'Products': [ { 'Name': 'Elbow Grease', 'Price': 99.95 }, { 'Name': 'Headlight Fluid', 'Price': 4 } ] } ] }"), DetectedBodyType = BodyType.Json }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{JsonPath.SelectToken request.bodyAsJson \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsString() { // Assign var body = new BodyData { BodyAsString = @"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }", DetectedBodyType = BodyType.String }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%"); } [Fact] public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsJObject() { // Assign var body = new BodyData { BodyAsJson = JObject.Parse(@"{ 'Stores': [ 'Lambton Quay', 'Willis Street' ], 'Manufacturers': [ { 'Name': 'Acme Co', 'Products': [ { 'Name': 'Anvil', 'Price': 50 } ] }, { 'Name': 'Contoso', 'Products': [ { 'Name': 'Elbow Grease', 'Price': 99.95 }, { 'Name': 'Headlight Fluid', 'Price': 4 } ] } ] }"), DetectedBodyType = BodyType.Json }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{#JsonPath.SelectTokens request.bodyAsJson \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}") .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%"); } [Fact] public void Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Throws() { // Assign var body = new BodyData { BodyAsJson = JObject.Parse(@"{ 'Stores': [ 'Lambton Quay', 'Willis Street' ] }"), DetectedBodyType = BodyType.Json }; var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var responseBuilder = Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{id}} {{value}},{{/JsonPath.SelectTokens}}") .WithTransformer(); // Act Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<ArgumentNullException>(); } [Fact] public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath() { // Assign string jsonString = "{ \"MyUniqueNumber\": \"1\" }"; var bodyData = new BodyData { BodyAsString = jsonString, BodyAsJson = JsonConvert.DeserializeObject(jsonString), DetectedBodyType = BodyType.Json, DetectedBodyTypeFromContentType = BodyType.Json, Encoding = Encoding.UTF8 }; var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData); string jsonPath = "\"$.MyUniqueNumber\""; var responseBuilder = Response.Create() .WithTransformer() .WithBodyFromFile(@"c:\\{{JsonPath.SelectToken request.body " + jsonPath + "}}\\test.json"); // why use a \\ here ? // Act var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false); // Assert Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.json"); } } }
//////////////////////////////////////////////////////////////////////////////// // // @module Android Native Plugin for Unity3D // @author Osipov Stanislav (Stan's Assets) // @support stans.assets@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; public class AndroidAdMobController : Singletone<AndroidAdMobController>, GoogleMobileAdInterface { private bool _IsInited = false ; private Dictionary<int, AndroidADBanner> _banners; private string _BannersUunitId; private string _InterstisialUnitId; //-------------------------------------- // INITIALIZE //-------------------------------------- void Awake() { DontDestroyOnLoad(gameObject); } public void Init(string ad_unit_id) { if(_IsInited) { Debug.LogWarning ("Init shoudl be called only once. Call ignored"); return; } _IsInited = true; _BannersUunitId = ad_unit_id; _InterstisialUnitId = ad_unit_id; _banners = new Dictionary<int, AndroidADBanner>(); AndroidNative.InitMobileAd(ad_unit_id); } public void Init(string banners_unit_id, string interstisial_unit_id) { if(_IsInited) { Debug.LogWarning ("Init shoudl be called only once. Call ignored"); return; } Init(banners_unit_id); SetInterstisialsUnitID(interstisial_unit_id); } public void SetBannersUnitID(string ad_unit_id) { _BannersUunitId = ad_unit_id; AndroidNative.ChangeBannersUnitID(ad_unit_id); } public void SetInterstisialsUnitID(string ad_unit_id) { _InterstisialUnitId = ad_unit_id; AndroidNative.ChangeInterstisialsUnitID(ad_unit_id); } //-------------------------------------- // BUILDER METHODS //-------------------------------------- //Add a keyword for targeting purposes. public void AddKeyword(string keyword) { if(!_IsInited) { Debug.LogWarning ("AddKeyword shoudl be called only after Init function. Call ignored"); return; } AndroidNative.AddKeyword(keyword); } //Causes a device to receive test ads. The deviceId can be obtained by viewing the logcat output after creating a new ad. public void AddTestDevice(string deviceId) { if(!_IsInited) { Debug.LogWarning ("AddTestDevice shoudl be called only after Init function. Call ignored"); return; } AndroidNative.AddTestDevice(deviceId); } //Set the user's gender for targeting purposes. This should be GADGenger.GENDER_MALE, GADGenger.GENDER_FEMALE, or GADGenger.GENDER_UNKNOWN public void SetGender(GoogleGenger gender) { if(!_IsInited) { Debug.LogWarning ("SetGender shoudl be called only after Init function. Call ignored"); return; } AndroidNative.SetGender((int) gender); } //-------------------------------------- // PUBLIC METHODS //-------------------------------------- public GoogleMobileAdBanner CreateAdBanner(TextAnchor anchor, GADBannerSize size) { if(!_IsInited) { Debug.LogWarning ("CreateBannerAd shoudl be called only after Init function. Call ignored"); return null; } AndroidADBanner bannner = new AndroidADBanner(anchor, size, GADBannerIdFactory.nextId); _banners.Add(bannner.id, bannner); return bannner; } public GoogleMobileAdBanner CreateAdBanner(int x, int y, GADBannerSize size) { if(!_IsInited) { Debug.LogWarning ("CreateBannerAd shoudl be called only after Init function. Call ignored"); return null; } AndroidADBanner bannner = new AndroidADBanner(x, y, size, GADBannerIdFactory.nextId); _banners.Add(bannner.id, bannner); return bannner; } public void DestroyBanner(int id) { if(_banners != null) { if(_banners.ContainsKey(id)) { _banners.Remove(id); AndroidNative.DestroyBanner(id); } } } public void StartInterstitialAd() { if(!_IsInited) { Debug.LogWarning ("StartInterstitialAd shoudl be called only after Init function. Call ignored"); return; } AndroidNative.StartInterstitialAd(); } public void LoadInterstitialAd() { if(!_IsInited) { Debug.LogWarning ("LoadInterstitialAd shoudl be called only after Init function. Call ignored"); return; } AndroidNative.LoadInterstitialAd(); } public void ShowInterstitialAd() { if(!_IsInited) { Debug.LogWarning ("ShowInterstitialAd shoudl be called only after Init function. Call ignored"); return; } AndroidNative.ShowInterstitialAd(); } //-------------------------------------- // GET/SET //-------------------------------------- public GoogleMobileAdBanner GetBanner(int id) { if(_banners.ContainsKey(id)) { return _banners[id]; } else { Debug.LogWarning("Banner id: " + id.ToString() + " not found"); return null; } } public List<GoogleMobileAdBanner> banners { get { List<GoogleMobileAdBanner> allBanners = new List<GoogleMobileAdBanner>(); if(_banners == null) { return allBanners; } foreach(KeyValuePair<int, AndroidADBanner> entry in _banners) { allBanners.Add(entry.Value); } return allBanners; } } public bool IsInited { get { return _IsInited; } } public string BannersUunitId { get { return _BannersUunitId; } } public string InterstisialUnitId { get { return _InterstisialUnitId; } } //-------------------------------------- // EVENTS BANNER AD //-------------------------------------- private void OnBannerAdLoaded(string bannerID) { int id = System.Convert.ToInt32(bannerID); AndroidADBanner banner = GetBanner(id) as AndroidADBanner; if(banner != null) { banner.OnBannerAdLoaded(); } } private void OnBannerAdFailedToLoad(string bannerID) { int id = System.Convert.ToInt32(bannerID); AndroidADBanner banner = GetBanner(id) as AndroidADBanner; if(banner != null) { banner.OnBannerAdFailedToLoad(); } } private void OnBannerAdOpened(string bannerID) { int id = System.Convert.ToInt32(bannerID); AndroidADBanner banner = GetBanner(id) as AndroidADBanner; if(banner != null) { banner.OnBannerAdOpened(); } } private void OnBannerAdClosed(string bannerID) { int id = System.Convert.ToInt32(bannerID); AndroidADBanner banner = GetBanner(id) as AndroidADBanner; if(banner != null) { banner.OnBannerAdClosed(); } } private void OnBannerAdLeftApplication(string bannerID) { int id = System.Convert.ToInt32(bannerID); AndroidADBanner banner = GetBanner(id) as AndroidADBanner; if(banner != null) { banner.OnBannerAdLeftApplication(); } } //-------------------------------------- // EVENTS INTERSTITIAL AD //-------------------------------------- private void OnInterstitialAdLoaded() { dispatch(GoogleMobileAdEvents.ON_INTERSTITIAL_AD_LOADED); } private void OnInterstitialAdFailedToLoad() { dispatch(GoogleMobileAdEvents.ON_INTERSTITIAL_AD_FAILED_LOADING); } private void OnInterstitialAdOpened() { dispatch(GoogleMobileAdEvents.ON_INTERSTITIAL_AD_OPENED); } private void OnInterstitialAdClosed() { dispatch(GoogleMobileAdEvents.ON_INTERSTITIAL_AD_CLOSED); } private void OnInterstitialAdLeftApplication() { dispatch(GoogleMobileAdEvents.ON_INTERSTITIAL_AD_LEFT_APPLICATION); } //-------------------------------------- // PRIVATE METHODS //-------------------------------------- //-------------------------------------- // DESTROY //-------------------------------------- }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; using Orleans.Runtime; using Orleans.Runtime.Messaging; namespace Orleans.Messaging { /// <summary> /// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways. /// /// The known list can come from one of two places: the full list may appear in the client configuration object, or /// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority. /// </summary> internal class GatewayManager : IDisposable { private readonly object lockable = new object(); private readonly Dictionary<SiloAddress, DateTime> knownDead = new Dictionary<SiloAddress, DateTime>(); private readonly Dictionary<SiloAddress, DateTime> knownMasked = new Dictionary<SiloAddress, DateTime>(); private readonly IGatewayListProvider gatewayListProvider; private readonly ILogger logger; private readonly ConnectionManager connectionManager; private readonly GatewayOptions gatewayOptions; private AsyncTaskSafeTimer gatewayRefreshTimer; private List<SiloAddress> cachedLiveGateways; private HashSet<SiloAddress> cachedLiveGatewaysSet; private List<SiloAddress> knownGateways; private DateTime lastRefreshTime; private int roundRobinCounter; private bool gatewayRefreshCallInitiated; private bool gatewayListProviderInitialized; public GatewayManager( IOptions<GatewayOptions> gatewayOptions, IGatewayListProvider gatewayListProvider, ILoggerFactory loggerFactory, ConnectionManager connectionManager) { this.gatewayOptions = gatewayOptions.Value; this.logger = loggerFactory.CreateLogger<GatewayManager>(); this.connectionManager = connectionManager; this.gatewayListProvider = gatewayListProvider; this.gatewayRefreshTimer = new AsyncTaskSafeTimer( loggerFactory.CreateLogger<SafeTimer>(), RefreshSnapshotLiveGateways_TimerCallback, null, this.gatewayOptions.GatewayListRefreshPeriod, this.gatewayOptions.GatewayListRefreshPeriod); } public async Task StartAsync(CancellationToken cancellationToken) { if (!gatewayListProviderInitialized) { await this.gatewayListProvider.InitializeGatewayListProvider(); gatewayListProviderInitialized = true; } var knownGateways = await this.gatewayListProvider.GetGateways(); if (knownGateways.Count == 0) { var err = $"Could not find any gateway in {this.gatewayListProvider.GetType().FullName}. Orleans client cannot initialize."; this.logger.LogError((int)ErrorCode.GatewayManager_NoGateways, err); throw new SiloUnavailableException(err); } this.logger.LogInformation( (int)ErrorCode.GatewayManager_FoundKnownGateways, "Found {GatewayCount} gateways: {Gateways}", knownGateways.Count, Utils.EnumerableToString(knownGateways)); this.roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : ThreadSafeRandom.Next(knownGateways.Count); this.knownGateways = this.cachedLiveGateways = knownGateways.Select(gw => gw.ToGatewayAddress()).ToList(); this.cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); this.lastRefreshTime = DateTime.UtcNow; } public void Stop() { if (gatewayRefreshTimer != null) { Utils.SafeExecute(gatewayRefreshTimer.Dispose, logger); } gatewayRefreshTimer = null; } public void MarkAsDead(SiloAddress gateway) { lock (lockable) { knownDead[gateway] = DateTime.UtcNow; var copy = new List<SiloAddress>(cachedLiveGateways); copy.Remove(gateway); // swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock. cachedLiveGateways = copy; cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); } } public void MarkAsUnavailableForSend(SiloAddress gateway) { lock (lockable) { knownMasked[gateway] = DateTime.UtcNow; var copy = new List<SiloAddress>(cachedLiveGateways); copy.Remove(gateway); // swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock. cachedLiveGateways = copy; cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); } } public override string ToString() { var sb = new StringBuilder(); sb.Append("GatewayManager: "); lock (lockable) { if (cachedLiveGateways != null) { sb.Append(cachedLiveGateways.Count); sb.Append(" cachedLiveGateways, "); } if (knownDead != null) { sb.Append(knownDead.Count); sb.Append(" known dead gateways."); } } return sb.ToString(); } /// <summary> /// Selects a gateway to use for a new bucket. /// /// Note that if a list provider delegate was given, the delegate is invoked every time this method is called. /// This method performs caching to avoid hammering the ultimate data source. /// /// This implementation does a simple round robin selection. It assumes that the gateway list from the provider /// is in the same order every time. /// </summary> /// <returns></returns> public SiloAddress GetLiveGateway() { List<SiloAddress> live = GetLiveGateways(); int count = live.Count; if (count > 0) { lock (lockable) { // Round-robin through the known gateways and take the next live one, starting from where we last left off roundRobinCounter = (roundRobinCounter + 1) % count; return live[roundRobinCounter]; } } // If we drop through, then all of the known gateways are presumed dead return null; } public List<SiloAddress> GetLiveGateways() { // Never takes a lock and returns the cachedLiveGateways list quickly without any operation. // Asynchronously starts gateway refresh only when it is empty. if (cachedLiveGateways.Count == 0) { ExpediteUpdateLiveGatewaysSnapshot(); if (knownGateways.Count > 0) { lock (this.lockable) { if (cachedLiveGateways.Count == 0 && knownGateways.Count > 0) { this.logger.LogWarning("All known gateways have been marked dead locally. Expediting gateway refresh and resetting all gateways to live status."); cachedLiveGateways = knownGateways; cachedLiveGatewaysSet = new HashSet<SiloAddress>(knownGateways); } } } } return cachedLiveGateways; } public bool IsGatewayAvailable(SiloAddress siloAddress) { return cachedLiveGatewaysSet.Contains(siloAddress); } internal void ExpediteUpdateLiveGatewaysSnapshot() { // If there is already an expedited refresh call in place, don't call again, until the previous one is finished. // We don't want to issue too many Gateway refresh calls. if (gatewayListProvider == null || gatewayRefreshCallInitiated) return; // Initiate gateway list refresh asynchronously. The Refresh timer will keep ticking regardless. // We don't want to block the client with synchronously Refresh call. // Client's call will fail with "No Gateways found" but we will try to refresh the list quickly. gatewayRefreshCallInitiated = true; _ = Task.Run(async () => { try { await RefreshSnapshotLiveGateways_TimerCallback(null); gatewayRefreshCallInitiated = false; } catch { // Intentionally ignore any exceptions here. } }); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal async Task RefreshSnapshotLiveGateways_TimerCallback(object context) { try { if (gatewayListProvider is null) return; // the listProvider.GetGateways() is not under lock. var allGateways = await gatewayListProvider.GetGateways(); var refreshedGateways = allGateways.Select(gw => gw.ToGatewayAddress()).ToList(); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Discovered {GatewayCount} gateways: {Gateways}", refreshedGateways.Count, Utils.EnumerableToString(refreshedGateways)); } await UpdateLiveGatewaysSnapshot(refreshedGateways, gatewayListProvider.MaxStaleness); } catch (Exception exc) { logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during RefreshSnapshotLiveGateways_TimerCallback -> listProvider.GetGateways()", exc); } } // This function is called asynchronously from gateway refresh timer. private async Task UpdateLiveGatewaysSnapshot(IEnumerable<SiloAddress> refreshedGateways, TimeSpan maxStaleness) { List<SiloAddress> connectionsToKeepAlive; // This is a short lock, protecting the access to knownDead, knownMasked and cachedLiveGateways. lock (lockable) { // now take whatever listProvider gave us and exclude those we think are dead. var live = new List<SiloAddress>(); var now = DateTime.UtcNow; this.knownGateways = refreshedGateways as List<SiloAddress> ?? refreshedGateways.ToList(); foreach (SiloAddress trial in knownGateways) { var address = trial.Generation == 0 ? trial : SiloAddress.New(trial.Endpoint, 0); // We consider a node to be dead if we recorded it is dead due to socket error // and it was recorded (diedAt) not too long ago (less than maxStaleness ago). // The latter is to cover the case when the Gateway provider returns an outdated list that does not yet reflect the actually recently died Gateway. // If it has passed more than maxStaleness - we assume maxStaleness is the upper bound on Gateway provider freshness. var isDead = false; if (knownDead.TryGetValue(address, out var diedAt)) { if (now.Subtract(diedAt) < maxStaleness) { isDead = true; } else { // Remove stale entries. knownDead.Remove(address); } } if (knownMasked.TryGetValue(address, out var maskedAt)) { if (now.Subtract(maskedAt) < maxStaleness) { isDead = true; } else { // Remove stale entries. knownMasked.Remove(address); } } if (!isDead) { live.Add(address); } } if (live.Count == 0) { logger.Warn( ErrorCode.GatewayManager_AllGatewaysDead, "All gateways have previously been marked as dead. Clearing the list of dead gateways to expedite reconnection."); live.AddRange(knownGateways); knownDead.Clear(); } // swap cachedLiveGateways pointer in one atomic operation cachedLiveGateways = live; cachedLiveGatewaysSet = new HashSet<SiloAddress>(live); DateTime prevRefresh = lastRefreshTime; lastRefreshTime = now; if (logger.IsEnabled(LogLevel.Information)) { logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Refreshed the live gateway list. Found {0} gateways from gateway list provider: {1}. Picked only known live out of them. Now has {2} live gateways: {3}. Previous refresh time was = {4}", knownGateways.Count, Utils.EnumerableToString(knownGateways), cachedLiveGateways.Count, Utils.EnumerableToString(cachedLiveGateways), prevRefresh); } // Close connections to known dead connections, but keep the "masked" ones. // Client will not send any new request to the "masked" connections, but might still // receive responses connectionsToKeepAlive = new List<SiloAddress>(live); connectionsToKeepAlive.AddRange(knownMasked.Select(e => e.Key)); } await this.CloseEvictedGatewayConnections(connectionsToKeepAlive); } private async Task CloseEvictedGatewayConnections(List<SiloAddress> liveGateways) { if (this.connectionManager == null) return; var connectedGateways = this.connectionManager.GetConnectedAddresses(); foreach (var address in connectedGateways) { var isLiveGateway = false; foreach (var live in liveGateways) { if (live.Matches(address)) { isLiveGateway = true; break; } } if (!isLiveGateway) { if (logger.IsEnabled(LogLevel.Information)) { this.logger.LogInformation("Closing connection to {Endpoint} because it has been marked as dead", address); } await this.connectionManager.CloseAsync(address); } } } public void Dispose() { this.gatewayRefreshTimer?.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.Serialization; namespace System.Xml { public interface IXmlBinaryReaderInitializer { void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); } internal class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer { private bool _isTextWithEndElement; private bool _buffered; private ArrayState _arrayState; private int _arrayCount; private int _maxBytesPerRead; private XmlBinaryNodeType _arrayNodeType; public XmlBinaryReader() { } public void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (buffer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer)); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative)); if (count > buffer.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); MoveToInitial(quotas, session, null); BufferReader.SetBuffer(buffer, offset, count, dictionary, session); _buffered = true; } public void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); MoveToInitial(quotas, session, null); BufferReader.SetBuffer(stream, dictionary, session); _buffered = false; } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; _arrayState = ArrayState.None; _isTextWithEndElement = false; } public override void Close() { base.Close(); } public override string ReadElementContentAsString() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsString(); string value; switch (GetNodeType()) { case XmlBinaryNodeType.Chars8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadUTF8String(ReadUInt8()); ReadTextWithEndElement(); break; case XmlBinaryNodeType.DictionaryTextWithEndElement: SkipNodeType(); value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value; ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsString(); break; } if (value.Length > Quotas.MaxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength); return value; } public override bool ReadElementContentAsBoolean() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsBoolean(); bool value; switch (GetNodeType()) { case XmlBinaryNodeType.TrueTextWithEndElement: SkipNodeType(); value = true; ReadTextWithEndElement(); break; case XmlBinaryNodeType.FalseTextWithEndElement: SkipNodeType(); value = false; ReadTextWithEndElement(); break; case XmlBinaryNodeType.BoolTextWithEndElement: SkipNodeType(); value = (BufferReader.ReadUInt8() != 0); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsBoolean(); break; } return value; } public override int ReadElementContentAsInt() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsInt(); int value; switch (GetNodeType()) { case XmlBinaryNodeType.ZeroTextWithEndElement: SkipNodeType(); value = 0; ReadTextWithEndElement(); break; case XmlBinaryNodeType.OneTextWithEndElement: SkipNodeType(); value = 1; ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt8(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int16TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt16(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int32TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt32(); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsInt(); break; } return value; } private bool CanOptimizeReadElementContent() { return (_arrayState == ArrayState.None && !Signing); } public override float ReadElementContentAsFloat() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement) { SkipNodeType(); float value = BufferReader.ReadSingle(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsFloat(); } public override double ReadElementContentAsDouble() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement) { SkipNodeType(); double value = BufferReader.ReadDouble(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDouble(); } public override decimal ReadElementContentAsDecimal() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement) { SkipNodeType(); decimal value = BufferReader.ReadDecimal(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDecimal(); } public override DateTime ReadElementContentAsDateTime() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement) { SkipNodeType(); DateTime value = BufferReader.ReadDateTime(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDateTime(); } public override TimeSpan ReadElementContentAsTimeSpan() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement) { SkipNodeType(); TimeSpan value = BufferReader.ReadTimeSpan(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsTimeSpan(); } public override Guid ReadElementContentAsGuid() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement) { SkipNodeType(); Guid value = BufferReader.ReadGuid(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsGuid(); } public override UniqueId ReadElementContentAsUniqueId() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement) { SkipNodeType(); UniqueId value = BufferReader.ReadUniqueId(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsUniqueId(); } public override bool TryGetBase64ContentLength(out int length) { length = 0; if (!_buffered) return false; if (_arrayState != ArrayState.None) return false; int totalLength; if (!this.Node.Value.TryGetByteArrayLength(out totalLength)) return false; int offset = BufferReader.Offset; try { bool done = false; while (!done && !BufferReader.EndOfFile) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); int actual; switch (nodeType) { case XmlBinaryNodeType.Bytes8TextWithEndElement: actual = BufferReader.ReadUInt8(); done = true; break; case XmlBinaryNodeType.Bytes16TextWithEndElement: actual = BufferReader.ReadUInt16(); done = true; break; case XmlBinaryNodeType.Bytes32TextWithEndElement: actual = BufferReader.ReadUInt31(); done = true; break; case XmlBinaryNodeType.EndElement: actual = 0; done = true; break; case XmlBinaryNodeType.Bytes8Text: actual = BufferReader.ReadUInt8(); break; case XmlBinaryNodeType.Bytes16Text: actual = BufferReader.ReadUInt16(); break; case XmlBinaryNodeType.Bytes32Text: actual = BufferReader.ReadUInt31(); break; default: // Non-optimal or unexpected node - fallback return false; } BufferReader.Advance(actual); if (totalLength > int.MaxValue - actual) return false; totalLength += actual; } length = totalLength; return true; } finally { BufferReader.Offset = offset; } } private void ReadTextWithEndElement() { ExitScope(); ReadNode(); } private XmlAtomicTextNode MoveToAtomicTextWithEndElement() { _isTextWithEndElement = true; return MoveToAtomicText(); } public override bool Read() { if (this.Node.ReadState == ReadState.Closed) return false; SignNode(); if (_isTextWithEndElement) { _isTextWithEndElement = false; MoveToEndElement(); return true; } if (_arrayState == ArrayState.Content) { if (_arrayCount != 0) { MoveToArrayElement(); return true; } _arrayState = ArrayState.None; } if (this.Node.ExitScope) { ExitScope(); } return ReadNode(); } private bool ReadNode() { if (!_buffered) BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead); if (BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } XmlBinaryNodeType nodeType; if (_arrayState == ArrayState.None) { nodeType = GetNodeType(); SkipNodeType(); } else { DiagnosticUtility.DebugAssert(_arrayState == ArrayState.Element, ""); nodeType = _arrayNodeType; _arrayCount--; _arrayState = ArrayState.Content; } XmlElementNode elementNode; PrefixHandleType prefix; switch (nodeType) { case XmlBinaryNodeType.ShortElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.Element: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.ShortDictionaryElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.DictionaryElement: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixElementA: case XmlBinaryNodeType.PrefixElementB: case XmlBinaryNodeType.PrefixElementC: case XmlBinaryNodeType.PrefixElementD: case XmlBinaryNodeType.PrefixElementE: case XmlBinaryNodeType.PrefixElementF: case XmlBinaryNodeType.PrefixElementG: case XmlBinaryNodeType.PrefixElementH: case XmlBinaryNodeType.PrefixElementI: case XmlBinaryNodeType.PrefixElementJ: case XmlBinaryNodeType.PrefixElementK: case XmlBinaryNodeType.PrefixElementL: case XmlBinaryNodeType.PrefixElementM: case XmlBinaryNodeType.PrefixElementN: case XmlBinaryNodeType.PrefixElementO: case XmlBinaryNodeType.PrefixElementP: case XmlBinaryNodeType.PrefixElementQ: case XmlBinaryNodeType.PrefixElementR: case XmlBinaryNodeType.PrefixElementS: case XmlBinaryNodeType.PrefixElementT: case XmlBinaryNodeType.PrefixElementU: case XmlBinaryNodeType.PrefixElementV: case XmlBinaryNodeType.PrefixElementW: case XmlBinaryNodeType.PrefixElementX: case XmlBinaryNodeType.PrefixElementY: case XmlBinaryNodeType.PrefixElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA); elementNode.Prefix.SetValue(prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixDictionaryElementA: case XmlBinaryNodeType.PrefixDictionaryElementB: case XmlBinaryNodeType.PrefixDictionaryElementC: case XmlBinaryNodeType.PrefixDictionaryElementD: case XmlBinaryNodeType.PrefixDictionaryElementE: case XmlBinaryNodeType.PrefixDictionaryElementF: case XmlBinaryNodeType.PrefixDictionaryElementG: case XmlBinaryNodeType.PrefixDictionaryElementH: case XmlBinaryNodeType.PrefixDictionaryElementI: case XmlBinaryNodeType.PrefixDictionaryElementJ: case XmlBinaryNodeType.PrefixDictionaryElementK: case XmlBinaryNodeType.PrefixDictionaryElementL: case XmlBinaryNodeType.PrefixDictionaryElementM: case XmlBinaryNodeType.PrefixDictionaryElementN: case XmlBinaryNodeType.PrefixDictionaryElementO: case XmlBinaryNodeType.PrefixDictionaryElementP: case XmlBinaryNodeType.PrefixDictionaryElementQ: case XmlBinaryNodeType.PrefixDictionaryElementR: case XmlBinaryNodeType.PrefixDictionaryElementS: case XmlBinaryNodeType.PrefixDictionaryElementT: case XmlBinaryNodeType.PrefixDictionaryElementU: case XmlBinaryNodeType.PrefixDictionaryElementV: case XmlBinaryNodeType.PrefixDictionaryElementW: case XmlBinaryNodeType.PrefixDictionaryElementX: case XmlBinaryNodeType.PrefixDictionaryElementY: case XmlBinaryNodeType.PrefixDictionaryElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA); elementNode.Prefix.SetValue(prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.EndElement: MoveToEndElement(); return true; case XmlBinaryNodeType.Comment: ReadName(MoveToComment().Value); return true; case XmlBinaryNodeType.EmptyTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.ZeroTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.OneTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.TrueTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.FalseTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.BoolTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.Chars8TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(true, ReadUInt8()); return true; case XmlBinaryNodeType.Chars8Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(false, ReadUInt8()); return true; case XmlBinaryNodeType.Chars16TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(true, ReadUInt16()); return true; case XmlBinaryNodeType.Chars16Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(false, ReadUInt16()); return true; case XmlBinaryNodeType.Chars32TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(true, ReadUInt31()); return true; case XmlBinaryNodeType.Chars32Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(false, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars8TextWithEndElement: ReadUnicodeText(true, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeText(false, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars16TextWithEndElement: ReadUnicodeText(true, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeText(false, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars32TextWithEndElement: ReadUnicodeText(true, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeText(false, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes8TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8()); else ReadPartialBinaryText(true, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes8Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt8()); else ReadPartialBinaryText(false, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes16TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16()); else ReadPartialBinaryText(true, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes16Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt16()); else ReadPartialBinaryText(false, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes32TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31()); else ReadPartialBinaryText(true, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes32Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt31()); else ReadPartialBinaryText(false, ReadUInt31()); return true; case XmlBinaryNodeType.DictionaryTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey()); return true; case XmlBinaryNodeType.UniqueIdTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId); return true; case XmlBinaryNodeType.GuidTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid); return true; case XmlBinaryNodeType.DecimalTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal); return true; case XmlBinaryNodeType.Int8TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8); return true; case XmlBinaryNodeType.Int16TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16); return true; case XmlBinaryNodeType.Int32TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32); return true; case XmlBinaryNodeType.Int64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64); return true; case XmlBinaryNodeType.UInt64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64); return true; case XmlBinaryNodeType.FloatTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single); return true; case XmlBinaryNodeType.DoubleTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double); return true; case XmlBinaryNodeType.TimeSpanTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan); return true; case XmlBinaryNodeType.DateTimeTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime); return true; case XmlBinaryNodeType.QNameDictionaryTextWithEndElement: BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value); return true; case XmlBinaryNodeType.Array: ReadArray(); return true; default: BufferReader.ReadValue(nodeType, MoveToComplexText().Value); return true; } } private void VerifyWhitespace() { if (!this.Node.Value.IsWhitespace()) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } private void ReadAttributes() { XmlBinaryNodeType nodeType = GetNodeType(); if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute) return; ReadAttributes2(); } private void ReadAttributes2() { int startOffset = 0; if (_buffered) startOffset = BufferReader.Offset; while (true) { XmlAttributeNode attributeNode; Namespace nameSpace; PrefixHandleType prefix; XmlBinaryNodeType nodeType = GetNodeType(); switch (nodeType) { case XmlBinaryNodeType.ShortAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.Attribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); FixXmlAttribute(attributeNode); break; case XmlBinaryNodeType.ShortDictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.DictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.XmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.DictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.PrefixDictionaryAttributeA: case XmlBinaryNodeType.PrefixDictionaryAttributeB: case XmlBinaryNodeType.PrefixDictionaryAttributeC: case XmlBinaryNodeType.PrefixDictionaryAttributeD: case XmlBinaryNodeType.PrefixDictionaryAttributeE: case XmlBinaryNodeType.PrefixDictionaryAttributeF: case XmlBinaryNodeType.PrefixDictionaryAttributeG: case XmlBinaryNodeType.PrefixDictionaryAttributeH: case XmlBinaryNodeType.PrefixDictionaryAttributeI: case XmlBinaryNodeType.PrefixDictionaryAttributeJ: case XmlBinaryNodeType.PrefixDictionaryAttributeK: case XmlBinaryNodeType.PrefixDictionaryAttributeL: case XmlBinaryNodeType.PrefixDictionaryAttributeM: case XmlBinaryNodeType.PrefixDictionaryAttributeN: case XmlBinaryNodeType.PrefixDictionaryAttributeO: case XmlBinaryNodeType.PrefixDictionaryAttributeP: case XmlBinaryNodeType.PrefixDictionaryAttributeQ: case XmlBinaryNodeType.PrefixDictionaryAttributeR: case XmlBinaryNodeType.PrefixDictionaryAttributeS: case XmlBinaryNodeType.PrefixDictionaryAttributeT: case XmlBinaryNodeType.PrefixDictionaryAttributeU: case XmlBinaryNodeType.PrefixDictionaryAttributeV: case XmlBinaryNodeType.PrefixDictionaryAttributeW: case XmlBinaryNodeType.PrefixDictionaryAttributeX: case XmlBinaryNodeType.PrefixDictionaryAttributeY: case XmlBinaryNodeType.PrefixDictionaryAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA); attributeNode.Prefix.SetValue(prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.PrefixAttributeA: case XmlBinaryNodeType.PrefixAttributeB: case XmlBinaryNodeType.PrefixAttributeC: case XmlBinaryNodeType.PrefixAttributeD: case XmlBinaryNodeType.PrefixAttributeE: case XmlBinaryNodeType.PrefixAttributeF: case XmlBinaryNodeType.PrefixAttributeG: case XmlBinaryNodeType.PrefixAttributeH: case XmlBinaryNodeType.PrefixAttributeI: case XmlBinaryNodeType.PrefixAttributeJ: case XmlBinaryNodeType.PrefixAttributeK: case XmlBinaryNodeType.PrefixAttributeL: case XmlBinaryNodeType.PrefixAttributeM: case XmlBinaryNodeType.PrefixAttributeN: case XmlBinaryNodeType.PrefixAttributeO: case XmlBinaryNodeType.PrefixAttributeP: case XmlBinaryNodeType.PrefixAttributeQ: case XmlBinaryNodeType.PrefixAttributeR: case XmlBinaryNodeType.PrefixAttributeS: case XmlBinaryNodeType.PrefixAttributeT: case XmlBinaryNodeType.PrefixAttributeU: case XmlBinaryNodeType.PrefixAttributeV: case XmlBinaryNodeType.PrefixAttributeW: case XmlBinaryNodeType.PrefixAttributeX: case XmlBinaryNodeType.PrefixAttributeY: case XmlBinaryNodeType.PrefixAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA); attributeNode.Prefix.SetValue(prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; default: ProcessAttributes(); return; } } } private void ReadText(XmlTextNode textNode, ValueHandleType type, int length) { int offset = BufferReader.ReadBytes(length); textNode.Value.SetValue(type, offset, length); if (this.OutsideRootElement) VerifyWhitespace(); } private void ReadBinaryText(XmlTextNode textNode, int length) { ReadText(textNode, ValueHandleType.Base64, length); } private void ReadPartialUTF8Text(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length); else ReadText(MoveToComplexText(), ValueHandleType.UTF8, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a utf8 character, so scan backwards for a // character boundary. We'll actually always push off at least one character since // although we find the character boundary, we don't bother to figure out if we have // all the bytes that comprise the character. int i; for (i = offset + actual - 1; i >= offset; i--) { byte b = BufferReader.GetByte(i); // The first byte of UTF8 character sequence has either the high bit off, or the // two high bits set. if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0) break; } // Move any split characters so we can insert the node int byteCount = (offset + actual - i); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text); InsertNode(nodeType, length - actual); } } private void ReadUnicodeText(bool withEndElement, int length) { if ((length & 1) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (_buffered) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } } else { ReadPartialUnicodeText(withEndElement, length); } } private void ReadPartialUnicodeText(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); else ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); // Make sure we break on a char boundary if ((actual & 1) != 0) actual--; int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a Unicode surrogate character int byteCount = 0; char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char)); // If the last char is a high surrogate char, then move back if (ch >= 0xD800 && ch < 0xDC00) byteCount = sizeof(char); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text); InsertNode(nodeType, length - actual); } } private void ReadPartialBinaryText(bool withEndElement, int length) { const int nodeLength = 5; int maxBytesPerRead = Math.Max(_maxBytesPerRead - nodeLength, 0); if (length <= maxBytesPerRead) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length); else ReadText(MoveToComplexText(), ValueHandleType.Base64, length); } else { int actual = maxBytesPerRead; if (actual > 3) actual -= (actual % 3); ReadText(MoveToComplexText(), ValueHandleType.Base64, actual); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text); InsertNode(nodeType, length - actual); } } private void InsertNode(XmlBinaryNodeType nodeType, int length) { byte[] buffer = new byte[5]; buffer[0] = (byte)nodeType; unchecked { buffer[1] = (byte)length; length >>= 8; buffer[2] = (byte)length; length >>= 8; buffer[3] = (byte)length; } length >>= 8; buffer[4] = (byte)length; BufferReader.InsertBytes(buffer, 0, buffer.Length); } private void ReadAttributeText(XmlAttributeTextNode textNode) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); BufferReader.ReadValue(nodeType, textNode.Value); } private void ReadName(ValueHandle value) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); value.SetValue(ValueHandleType.UTF8, offset, length); } private void ReadName(StringHandle handle) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); handle.SetValue(offset, length); } private void ReadName(PrefixHandle prefix) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); prefix.SetValue(offset, length); } private void ReadDictionaryName(StringHandle s) { int key = ReadDictionaryKey(); s.SetValue(key); } private XmlBinaryNodeType GetNodeType() { return BufferReader.GetNodeType(); } private void SkipNodeType() { BufferReader.SkipNodeType(); } private int ReadDictionaryKey() { return BufferReader.ReadDictionaryKey(); } private int ReadMultiByteUInt31() { return BufferReader.ReadMultiByteUInt31(); } private int ReadUInt8() { return BufferReader.ReadUInt8(); } private int ReadUInt16() { return BufferReader.ReadUInt16(); } private int ReadUInt31() { return BufferReader.ReadUInt31(); } private bool IsValidArrayType(XmlBinaryNodeType nodeType) { switch (nodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: case XmlBinaryNodeType.Int16TextWithEndElement: case XmlBinaryNodeType.Int32TextWithEndElement: case XmlBinaryNodeType.Int64TextWithEndElement: case XmlBinaryNodeType.FloatTextWithEndElement: case XmlBinaryNodeType.DoubleTextWithEndElement: case XmlBinaryNodeType.DecimalTextWithEndElement: case XmlBinaryNodeType.DateTimeTextWithEndElement: case XmlBinaryNodeType.TimeSpanTextWithEndElement: case XmlBinaryNodeType.GuidTextWithEndElement: return true; default: return false; } } private void ReadArray() { if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadStartElement if (this.Node.NodeType != XmlNodeType.Element) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadEndElement if (this.Node.NodeType != XmlNodeType.EndElement) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); _arrayState = ArrayState.Element; _arrayNodeType = GetNodeType(); if (!IsValidArrayType(_arrayNodeType)) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); SkipNodeType(); _arrayCount = ReadMultiByteUInt31(); if (_arrayCount == 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); MoveToArrayElement(); } private void MoveToArrayElement() { _arrayState = ArrayState.Element; MoveToNode(ElementNode); } private void SkipArrayElements(int count) { _arrayCount -= count; if (_arrayCount == 0) { _arrayState = ArrayState.None; ExitScope(); ReadNode(); } } public override bool IsStartArray(out Type type) { type = null; if (_arrayState != ArrayState.Element) return false; switch (_arrayNodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: type = typeof(bool); break; case XmlBinaryNodeType.Int16TextWithEndElement: type = typeof(short); break; case XmlBinaryNodeType.Int32TextWithEndElement: type = typeof(int); break; case XmlBinaryNodeType.Int64TextWithEndElement: type = typeof(long); break; case XmlBinaryNodeType.FloatTextWithEndElement: type = typeof(float); break; case XmlBinaryNodeType.DoubleTextWithEndElement: type = typeof(double); break; case XmlBinaryNodeType.DecimalTextWithEndElement: type = typeof(decimal); break; case XmlBinaryNodeType.DateTimeTextWithEndElement: type = typeof(DateTime); break; case XmlBinaryNodeType.GuidTextWithEndElement: type = typeof(Guid); break; case XmlBinaryNodeType.TimeSpanTextWithEndElement: type = typeof(TimeSpan); break; case XmlBinaryNodeType.UniqueIdTextWithEndElement: type = typeof(UniqueId); break; default: return false; } return true; } public override bool TryGetArrayLength(out int count) { count = 0; if (!_buffered) return false; if (_arrayState != ArrayState.Element) return false; count = _arrayCount; return true; } private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing; } private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing; } private void CheckArray(Array array, int offset, int count) { if (array == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array))); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative)); if (count > array.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } private unsafe int ReadArray(bool[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (bool* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(short[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (short* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(int[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (int* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(long[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (long* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(float[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (float* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(double[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (double* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private unsafe int ReadArray(decimal[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (decimal* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // DateTime private int ReadArray(DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadDateTime(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Guid private int ReadArray(Guid[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadGuid(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // TimeSpan private int ReadArray(TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadTimeSpan(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private enum ArrayState { None, Element, Content } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(false); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class TakesScreenshotTest : DriverTestFixture { [TearDown] public void SwitchToTop() { driver.SwitchTo().DefaultContent(); } [Test] public void GetScreenshotAsFile() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png"); Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); screenImage.SaveAsFile(filename, ScreenshotImageFormat.Png); Assert.That(File.Exists(filename), Is.True); Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0)); File.Delete(filename); } [Test] public void GetScreenshotAsBase64() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); string base64 = screenImage.AsBase64EncodedString; Assert.That(base64.Length, Is.GreaterThan(0)); } [Test] public void GetScreenshotAsBinary() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); byte[] bytes = screenImage.AsByteArray; Assert.That(bytes.Length, Is.GreaterThan(0)); } [Test] public void ShouldCaptureScreenshotOfCurrentViewport() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldTakeScreenshotsOfAnElement() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); IWebElement element = driver.FindElement(By.Id("cell11")); ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot; if (screenshotCapableElement == null) { return; } Screenshot screenImage = screenshotCapableElement.GetScreenshot(); byte[] imageData = screenImage.AsByteArray; Assert.That(imageData, Is.Not.Null); Assert.That(imageData.Length, Is.GreaterThan(0)); Color pixelColor = GetPixelColor(screenImage, 1, 1); string pixelColorString = FormatColorToHex(pixelColor.ToArgb()); Assert.AreEqual("#0f12f7", pixelColorString); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongXandY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldCaptureScreenshotAtFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(TitleToBe("screen test"), "Title was not expected value"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page CompareColors(expectedColors, actualColors); } [Test] public void ShouldCaptureScreenshotAtIFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); // Resize the window to avoid scrollbars in screenshot Size originalSize = driver.Manage().Window.Size; driver.Manage().Window.Size = new Size(1040, 700); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); driver.Manage().Window.Size = originalSize; HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtIFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); // Resize the window to avoid scrollbars in screenshot Size originalSize = driver.Manage().Window.Size; driver.Manage().Window.Size = new Size(1040, 700); driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); driver.Manage().Window.Size = originalSize; HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page CompareColors(expectedColors, actualColors); } private string FormatColorToHex(int colorValue) { string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF)); return pixelColorString; } private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors) { // Ignore black and white for further comparison actualColors.Remove("#000000"); actualColors.Remove("#ffffff"); Assert.That(actualColors, Is.EquivalentTo(expectedColors)); } private HashSet<string> GenerateExpectedColors(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY) { HashSet<string> colors = new HashSet<string>(); int count = 1; for (int i = 1; i < numberOfSamplesX; i++) { for (int j = 1; j < numberOfSamplesY; j++) { int color = initialColor + (count * stepColor); string hex = FormatColorToHex(color); colors.Add(hex); count++; } } return colors; } private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY) { HashSet<string> colors = new HashSet<string>(); #if !NETCOREAPP2_1 && !NETSTANDARD2_1 && !NET5_0 try { Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); int height = bitmap.Height; int width = bitmap.Width; Assert.That(width, Is.GreaterThan(0)); Assert.That(height, Is.GreaterThan(0)); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb()); colors.Add(hex); } } } catch (Exception e) { Assert.Fail("Unable to get actual colors from screenshot: " + e.Message); } Assert.That(colors.Count, Is.GreaterThan(0)); #endif return colors; } private Color GetPixelColor(Screenshot screenshot, int x, int y) { Color pixelColor = Color.Black; #if !NETCOREAPP2_1 && !NETSTANDARD2_1 && !NET5_0 Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); pixelColor = bitmap.GetPixel(1, 1); #endif return pixelColor; } private Func<bool> FrameToBeAvailableAndSwitchedTo(string frameId) { return () => { try { IWebElement frameElement = driver.FindElement(By.Id(frameId)); driver.SwitchTo().Frame(frameElement); } catch(Exception) { return false; } return true; }; } private Func<bool> ElementToBeVisibleWithId(string elementId) { return () => { try { IWebElement element = driver.FindElement(By.Id(elementId)); return element.Displayed; } catch(Exception) { return false; } }; } private Func<bool> TitleToBe(string desiredTitle) { return () => driver.Title == desiredTitle; } } }
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Text; using Hazelcast.Client.Protocol.Util; using Hazelcast.IO; using Hazelcast.Net.Ext; using Hazelcast.Util; namespace Hazelcast.Client.Protocol { /// <summary> /// Client Message is the carrier framed data as defined below. /// </summary> /// <remarks> /// <p> /// Client Message is the carrier framed data as defined below. /// </p> /// <p> /// Any request parameter, response or event data will be carried in /// the payload. /// </p> /// <p /> /// <pre> /// 0 1 2 3 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// |R| Frame Length | /// +-------------+---------------+---------------------------------+ /// | Version |B|E| Flags | Type | /// +-------------+---------------+---------------------------------+ /// | | /// + CorrelationId + /// | | /// +---------------------------------------------------------------+ /// | PartitionId | /// +-----------------------------+---------------------------------+ /// | Data Offset | | /// +-----------------------------+ | /// | Message Payload Data ... /// | ... /// </pre> /// </remarks> internal class ClientMessage : MessageFlyweight, ISocketWritable, ISocketReadable, IClientMessage { /// <summary>Current protocol version</summary> public const short Version = 0; /// <summary>Begin Flag</summary> public const short BeginFlag = unchecked(0x80); /// <summary>End Flag</summary> public const short EndFlag = unchecked(0x40); /// <summary>Begin and End Flags</summary> public const short BeginAndEndFlags = BeginFlag | EndFlag; /// <summary>Listener Event Flag</summary> public const short ListenerEventFlag = unchecked(0x01); private const int InitialBufferSize = 1024; private const int FrameLengthFieldOffset = 0; private const int VersionFieldOffset = FrameLengthFieldOffset + Bits.IntSizeInBytes; private const int FlagsFieldOffset = VersionFieldOffset + Bits.ByteSizeInBytes; private const int TypeFieldOffset = FlagsFieldOffset + Bits.ByteSizeInBytes; private const int CorrelationIdFieldOffset = TypeFieldOffset + Bits.ShortSizeInBytes; private const int PartitionIdFieldOffset = CorrelationIdFieldOffset + Bits.LongSizeInBytes; private const int DataOffsetFieldOffset = PartitionIdFieldOffset + Bits.IntSizeInBytes; /// <summary>ClientMessage Fixed Header size in bytes</summary> public const int HeaderSize = DataOffsetFieldOffset + Bits.ShortSizeInBytes; private bool _isRetryable; private int _writeOffset; /// <param name="flag">Check this flag to see if it is set.</param> /// <returns>true if the given flag is set, false otherwise.</returns> public virtual bool IsFlagSet(short flag) { var i = GetFlags() & flag; return i == flag; } /// <summary>Sets the flags field value.</summary> /// <param name="flags">The value to set in the flags field.</param> /// <returns>The ClientMessage with the new flags field value.</returns> public virtual IClientMessage AddFlag(short flags) { Uint8Put(FlagsFieldOffset, (short) (GetFlags() | flags)); return this; } /// <summary>Returns the message type field.</summary> /// <returns>The message type field value.</returns> public virtual int GetMessageType() { return Uint16Get(TypeFieldOffset); } /// <summary>Returns the correlation id field.</summary> /// <returns>The correlation id field.</returns> public virtual long GetCorrelationId() { return Int64Get(CorrelationIdFieldOffset); } /// <summary>Sets the correlation id field.</summary> /// <param name="correlationId">The value to set in the correlation id field.</param> /// <returns>The ClientMessage with the new correlation id field value.</returns> public virtual IClientMessage SetCorrelationId(long correlationId) { Int64Set(CorrelationIdFieldOffset, correlationId); return this; } /// <summary>Returns the partition id field.</summary> /// <returns>The partition id field.</returns> public virtual int GetPartitionId() { return Int32Get(PartitionIdFieldOffset); } /// <summary>Sets the partition id field.</summary> /// <param name="partitionId">The value to set in the partitions id field.</param> /// <returns>The ClientMessage with the new partitions id field value.</returns> public virtual IClientMessage SetPartitionId(int partitionId) { Int32Set(PartitionIdFieldOffset, partitionId); return this; } public virtual bool IsRetryable() { return _isRetryable; } public virtual bool ReadFrom(ByteBuffer source) { var frameLength = 0; if (Buffer == null) { //init internal buffer var remaining = source.Remaining(); if (remaining < Bits.IntSizeInBytes) { //we don't have even the frame length ready return false; } frameLength = Bits.ReadIntL(source.Array(), source.Position); if (frameLength < HeaderSize) { throw new InvalidDataException("Client message frame length cannot be smaller than header size."); } Wrap(new SafeBuffer(new byte[frameLength]), 0); } frameLength = frameLength > 0 ? frameLength : GetFrameLength(); Accumulate(source, frameLength - Index()); return IsComplete(); } public virtual bool WriteTo(ByteBuffer destination) { var byteArray = Buffer.ByteArray(); var size = GetFrameLength(); // the number of bytes that can be written to the bb. var bytesWritable = destination.Remaining(); // the number of bytes that need to be written. var bytesNeeded = size - _writeOffset; int bytesWrite; bool done; if (bytesWritable >= bytesNeeded) { // All bytes for the value are available. bytesWrite = bytesNeeded; done = true; } else { // Not all bytes for the value are available. Write as much as is available. bytesWrite = bytesWritable; done = false; } destination.Put(byteArray, _writeOffset, bytesWrite); _writeOffset += bytesWrite; if (done) { //clear the write offset so that same client message can be resend if needed. _writeOffset = 0; } return done; } public virtual bool IsUrgent() { return false; } public static ClientMessage Create() { return new ClientMessage(); } public static ClientMessage CreateForDecode(IClientProtocolBuffer buffer, int offset) { var clientMessage = new ClientMessage(); clientMessage.WrapForDecode(buffer, offset); return clientMessage; } public static ClientMessage CreateForEncode(int initialCapacity) { initialCapacity = QuickMath.NextPowerOfTwo(initialCapacity); return CreateForEncode(new SafeBuffer(new byte[initialCapacity]), 0); } public static ClientMessage CreateForEncode(IClientProtocolBuffer buffer, int offset) { var clientMessage = new ClientMessage(); clientMessage.WrapForEncode(buffer, offset); return clientMessage; } /// <summary>Returns the setDataOffset field.</summary> /// <returns>The setDataOffset type field value.</returns> public virtual int GetDataOffset() { return Uint16Get(DataOffsetFieldOffset); } /// <summary>Returns the flags field value.</summary> /// <returns>The flags field value.</returns> public virtual short GetFlags() { return Uint8Get(FlagsFieldOffset); } /// <summary>Returns the frame length field.</summary> /// <returns>The frame length field.</returns> public virtual int GetFrameLength() { return Int32Get(FrameLengthFieldOffset); } /// <summary>Returns the version field value.</summary> /// <returns>The version field value.</returns> public virtual short GetVersion() { return Uint8Get(VersionFieldOffset); } /// <summary>Checks the frame size and total data size to validate the message size.</summary> /// <returns>true if the message is constructed.</returns> public virtual bool IsComplete() { return (Index() >= HeaderSize) && (Index() == GetFrameLength()); } /// <summary>Sets the dataOffset field.</summary> /// <param name="dataOffset">The value to set in the dataOffset field.</param> /// <returns>The ClientMessage with the new dataOffset field value.</returns> public virtual ClientMessage SetDataOffset(int dataOffset) { Uint16Put(DataOffsetFieldOffset, dataOffset); return this; } /// <summary>Sets the frame length field.</summary> /// <param name="length">The value to set in the frame length field.</param> /// <returns>The ClientMessage with the new frame length field value.</returns> public virtual ClientMessage SetFrameLength(int length) { Int32Set(FrameLengthFieldOffset, length); return this; } /// <summary>Sets the message type field.</summary> /// <param name="type">The value to set in the message type field.</param> /// <returns>The ClientMessage with the new message type field value.</returns> public virtual ClientMessage SetMessageType(int type) { Uint16Put(TypeFieldOffset, type); return this; } public virtual void SetRetryable(bool isRetryable) { _isRetryable = isRetryable; } /// <summary>Sets the version field value.</summary> /// <param name="version">The value to set in the version field.</param> /// <returns>The ClientMessage with the new version field value.</returns> public virtual ClientMessage SetVersion(short version) { Uint8Put(VersionFieldOffset, version); return this; } public override string ToString() { var len = Index(); var sb = new StringBuilder("ClientMessage{"); sb.Append("length=").Append(len); if (len >= HeaderSize) { sb.Append(", correlationId=").Append(GetCorrelationId()); sb.Append(", messageType=").Append(GetMessageType().ToString("X")); sb.Append(", partitionId=").Append(GetPartitionId()); sb.Append(", isComplete=").Append(IsComplete()); sb.Append(", isRetryable=").Append(IsRetryable()); sb.Append(", isEvent=").Append(IsFlagSet(ListenerEventFlag)); sb.Append(", writeOffset=").Append(_writeOffset); } sb.Append('}'); return sb.ToString(); } public virtual ClientMessage UpdateFrameLength() { SetFrameLength(Index()); return this; } protected internal virtual void WrapForDecode(IClientProtocolBuffer buffer, int offset) { EnsureHeaderSize(offset, buffer.Capacity()); Wrap(buffer, offset); Index(GetDataOffset()); } protected internal virtual void WrapForEncode(IClientProtocolBuffer buffer, int offset) { EnsureHeaderSize(offset, buffer.Capacity()); Wrap(buffer, offset); SetDataOffset(HeaderSize); SetFrameLength(HeaderSize); Index(GetDataOffset()); SetPartitionId(-1); } private int Accumulate(ByteBuffer byteBuffer, int length) { var remaining = byteBuffer.Remaining(); var readLength = remaining < length ? remaining : length; if (readLength > 0) { Buffer.PutBytes(Index(), byteBuffer.Array(), byteBuffer.Position, readLength); byteBuffer.Position = byteBuffer.Position + readLength; Index(Index() + readLength); return readLength; } return 0; } private void EnsureHeaderSize(int offset, int length) { if (length - offset < HeaderSize) { throw new IndexOutOfRangeException("ClientMessage buffer must contain at least " + HeaderSize + " bytes! length: " + length + ", offset: " + offset); } } } }
// Copyright 2012 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using JetBrains.Annotations; using NodaTime.Annotations; using NodaTime.Calendars; using NodaTime.Text; using NodaTime.Utility; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using static NodaTime.NodaConstants; namespace NodaTime { /// <summary> /// A local date and time in a particular calendar system, combined with an offset from UTC. This is /// broadly similar to <see cref="DateTimeOffset" /> in the BCL. /// </summary> /// <remarks> /// <para> /// Equality is defined in a component-wise fashion: two values are the same if they represent equal date/time values /// (including being in the same calendar) and equal offsets from UTC. /// Ordering between offset date/time values has no natural definition; see <see cref="Comparer"/> for built-in comparers. /// </para> /// <para> /// A value of this type unambiguously represents both a local time and an instant on the timeline, /// but does not have a well-defined time zone. This means you cannot reliably know what the local /// time would be five minutes later, for example. While this doesn't sound terribly useful, it's very common /// in text representations. /// </para> /// </remarks> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> [TypeConverter(typeof(OffsetDateTimeTypeConverter))] [XmlSchemaProvider(nameof(AddSchema))] public readonly struct OffsetDateTime : IEquatable<OffsetDateTime>, IFormattable, IXmlSerializable { private const int MinBclOffsetMinutes = -14 * MinutesPerHour; private const int MaxBclOffsetMinutes = 14 * MinutesPerHour; // This is effectively a LocalDateTime and an Offset, but by composing it slightly differently, we can save memory. private readonly LocalDate localDate; private readonly OffsetTime offsetTime; internal OffsetDateTime([Trusted] LocalDate localDate, [Trusted] OffsetTime offsetTime) { this.localDate = localDate; this.offsetTime = offsetTime; } /// <summary> /// Optimized conversion from an Instant to an OffsetDateTime in the ISO calendar. /// This is equivalent to <c>new OffsetDateTime(new LocalDateTime(instant.Plus(offset)), offset)</c> /// but with less overhead. /// </summary> internal OffsetDateTime(Instant instant, Offset offset) { unchecked { int days = instant.DaysSinceEpoch; long nanoOfDay = instant.NanosecondOfDay + offset.Nanoseconds; if (nanoOfDay >= NanosecondsPerDay) { days++; nanoOfDay -= NanosecondsPerDay; } else if (nanoOfDay < 0) { days--; nanoOfDay += NanosecondsPerDay; } localDate = new LocalDate(days); offsetTime = new OffsetTime(nanoOfDay, offset.Seconds); } } /// <summary> /// Optimized conversion from an Instant to an OffsetDateTime in the specified calendar. /// This is equivalent to <c>new OffsetDateTime(new LocalDateTime(instant.Plus(offset), calendar), offset)</c> /// but with less overhead. /// </summary> internal OffsetDateTime(Instant instant, Offset offset, CalendarSystem calendar) { unchecked { int days = instant.DaysSinceEpoch; long nanoOfDay = instant.NanosecondOfDay + offset.Nanoseconds; if (nanoOfDay >= NanosecondsPerDay) { days++; nanoOfDay -= NanosecondsPerDay; } else if (nanoOfDay < 0) { days--; nanoOfDay += NanosecondsPerDay; } localDate = new LocalDate(days, calendar); offsetTime = new OffsetTime(nanoOfDay, offset.Seconds); } } /// <summary> /// Constructs a new offset date/time with the given local date and time, and the given offset from UTC. /// </summary> /// <param name="localDateTime">Local date and time to represent</param> /// <param name="offset">Offset from UTC</param> public OffsetDateTime(LocalDateTime localDateTime, Offset offset) : this(localDateTime.Date, new OffsetTime(localDateTime.NanosecondOfDay, offset.Seconds)) { } /// <summary>Gets the calendar system associated with this offset date and time.</summary> /// <value>The calendar system associated with this offset date and time.</value> public CalendarSystem Calendar => localDate.Calendar; /// <summary>Gets the year of this offset date and time.</summary> /// <remarks>This returns the "absolute year", so, for the ISO calendar, /// a value of 0 means 1 BC, for example.</remarks> /// <value>The year of this offset date and time.</value> public int Year => localDate.Year; /// <summary>Gets the month of this offset date and time within the year.</summary> /// <value>The month of this offset date and time within the year.</value> public int Month => localDate.Month; /// <summary>Gets the day of this offset date and time within the month.</summary> /// <value>The day of this offset date and time within the month.</value> public int Day => localDate.Day; internal YearMonthDay YearMonthDay => localDate.YearMonthDay; /// <summary> /// Gets the week day of this offset date and time expressed as an <see cref="NodaTime.IsoDayOfWeek"/> value. /// </summary> /// <value>The week day of this offset date and time expressed as an <c>IsoDayOfWeek</c>.</value> public IsoDayOfWeek DayOfWeek => localDate.DayOfWeek; /// <summary>Gets the year of this offset date and time within the era.</summary> /// <value>The year of this offset date and time within the era.</value> public int YearOfEra => localDate.YearOfEra; /// <summary>Gets the era of this offset date and time.</summary> /// <value>The era of this offset date and time.</value> public Era Era => localDate.Era; /// <summary>Gets the day of this offset date and time within the year.</summary> /// <value>The day of this offset date and time within the year.</value> public int DayOfYear => localDate.DayOfYear; /// <summary> /// Gets the hour of day of this offset date and time, in the range 0 to 23 inclusive. /// </summary> /// <value>The hour of day of this offset date and time, in the range 0 to 23 inclusive.</value> public int Hour => offsetTime.Hour; /// <summary> /// Gets the hour of the half-day of this offset date and time, in the range 1 to 12 inclusive. /// </summary> /// <value>The hour of the half-day of this offset date and time, in the range 1 to 12 inclusive.</value> public int ClockHourOfHalfDay => offsetTime.ClockHourOfHalfDay; /// <summary> /// Gets the minute of this offset date and time, in the range 0 to 59 inclusive. /// </summary> /// <value>The minute of this offset date and time, in the range 0 to 59 inclusive.</value> public int Minute => offsetTime.Minute; /// <summary> /// Gets the second of this offset date and time within the minute, in the range 0 to 59 inclusive. /// </summary> /// <value>The second of this offset date and time within the minute, in the range 0 to 59 inclusive.</value> public int Second => offsetTime.Second; /// <summary> /// Gets the millisecond of this offset date and time within the second, in the range 0 to 999 inclusive. /// </summary> /// <value>The millisecond of this offset date and time within the second, in the range 0 to 999 inclusive.</value> public int Millisecond => offsetTime.Millisecond; /// <summary> /// Gets the tick of this offset date and time within the second, in the range 0 to 9,999,999 inclusive. /// </summary> /// <value>The tick of this offset date and time within the second, in the range 0 to 9,999,999 inclusive.</value> public int TickOfSecond => offsetTime.TickOfSecond; /// <summary> /// Gets the tick of this offset date and time within the day, in the range 0 to 863,999,999,999 inclusive. /// </summary> /// <value>The tick of this offset date and time within the day, in the range 0 to 863,999,999,999 inclusive.</value> public long TickOfDay => offsetTime.TickOfDay; /// <summary> /// Gets the nanosecond of this offset date and time within the second, in the range 0 to 999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this offset date and time within the second, in the range 0 to 999,999,999 inclusive.</value> public int NanosecondOfSecond => offsetTime.NanosecondOfSecond; /// <summary> /// Gets the nanosecond of this offset date and time within the day, in the range 0 to 86,399,999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this offset date and time within the day, in the range 0 to 86,399,999,999,999 inclusive.</value> public long NanosecondOfDay => offsetTime.NanosecondOfDay; /// <summary> /// Returns the local date and time represented within this offset date and time. /// </summary> /// <value>The local date and time represented within this offset date and time.</value> public LocalDateTime LocalDateTime => new LocalDateTime(Date, TimeOfDay); /// <summary> /// Gets the local date represented by this offset date and time. /// </summary> /// <remarks> /// The returned <see cref="LocalDate"/> /// will have the same calendar system and return the same values for each of the date-based calendar /// properties (Year, MonthOfYear and so on), but will not have any offset information. /// </remarks> /// <value>The local date represented by this offset date and time.</value> public LocalDate Date => localDate; /// <summary> /// Gets the time portion of this offset date and time. /// </summary> /// <remarks> /// The returned <see cref="LocalTime"/> will /// return the same values for each of the time-based properties (Hour, Minute and so on), but /// will not have any offset information. /// </remarks> /// <value>The time portion of this offset date and time.</value> public LocalTime TimeOfDay => new LocalTime(NanosecondOfDay); /// <summary> /// Gets the offset from UTC. /// </summary> /// <value>The offset from UTC.</value> public Offset Offset => offsetTime.Offset; /// <summary> /// Converts this offset date and time to an instant in time by subtracting the offset from the local date and time. /// </summary> /// <returns>The instant represented by this offset date and time</returns> [Pure] public Instant ToInstant() => Instant.FromUntrustedDuration(ToElapsedTimeSinceEpoch()); private Duration ToElapsedTimeSinceEpoch() { // Equivalent to LocalDateTime.ToLocalInstant().Minus(offset) int days = localDate.DaysSinceEpoch; Duration elapsedTime = new Duration(days, NanosecondOfDay).MinusSmallNanoseconds(offsetTime.OffsetNanoseconds); return elapsedTime; } /// <summary> /// Returns this value as a <see cref="ZonedDateTime"/>. /// </summary> /// <remarks> /// <para> /// This method returns a <see cref="ZonedDateTime"/> with the same local date and time as this value, using a /// fixed time zone with the same offset as the offset for this value. /// </para> /// <para> /// Note that because the resulting <c>ZonedDateTime</c> has a fixed time zone, it is generally not useful to /// use this result for arithmetic operations, as the zone will not adjust to account for daylight savings. /// </para> /// </remarks> /// <returns>A zoned date/time with the same local time and a fixed time zone using the offset from this value.</returns> [Pure] public ZonedDateTime InFixedZone() => new ZonedDateTime(this, DateTimeZone.ForOffset(Offset)); /// <summary> /// Returns this value in ths specified time zone. This method does not expect /// the offset in the zone to be the same as for the current value; it simply converts /// this value into an <see cref="Instant"/> and finds the <see cref="ZonedDateTime"/> /// for that instant in the specified zone. /// </summary> /// <param name="zone">The time zone of the new value.</param> /// <returns>The instant represented by this value, in the specified time zone.</returns> [Pure] public ZonedDateTime InZone(DateTimeZone zone) { Preconditions.CheckNotNull(zone, nameof(zone)); return ToInstant().InZone(zone); } /// <summary> /// Returns the BCL <see cref="DateTimeOffset"/> corresponding to this offset date and time. /// </summary> /// <remarks> /// <para> /// If the date and time is not on a tick boundary (the unit of granularity of DateTime) the value will be truncated /// towards the start of time. /// </para> /// <para> /// If the offset has a non-zero second component, this is truncated as <c>DateTimeOffset</c> has an offset /// granularity of minutes. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">The date/time is outside the range of <c>DateTimeOffset</c>, /// or the offset is outside the range of +/-14 hours (the range supported by <c>DateTimeOffset</c>).</exception> /// <returns>A DateTimeOffset with the same local date/time and offset as this. The <see cref="DateTime"/> part of /// the result always has a "kind" of Unspecified.</returns> [Pure] public DateTimeOffset ToDateTimeOffset() { int offsetMinutes = Offset.Seconds / 60; if (offsetMinutes < MinBclOffsetMinutes || offsetMinutes > MaxBclOffsetMinutes) { throw new InvalidOperationException("Offset out of range for DateTimeOffset"); } return new DateTimeOffset(LocalDateTime.ToDateTimeUnspecified(), TimeSpan.FromMinutes(offsetMinutes)); } /// <summary> /// Builds an <see cref="OffsetDateTime"/> from a BCL <see cref="DateTimeOffset"/> by converting /// the <see cref="DateTime"/> part to a <see cref="LocalDateTime"/>, and the offset part to an <see cref="Offset"/>. /// </summary> /// <param name="dateTimeOffset">DateTimeOffset to convert</param> /// <returns>The converted offset date and time</returns> [Pure] public static OffsetDateTime FromDateTimeOffset(DateTimeOffset dateTimeOffset) => new OffsetDateTime(LocalDateTime.FromDateTime(dateTimeOffset.DateTime), Offset.FromTimeSpan(dateTimeOffset.Offset)); /// <summary> /// Creates a new OffsetDateTime representing the same physical date, time and offset, but in a different calendar. /// The returned OffsetDateTime is likely to have different date field values to this one. /// For example, January 1st 1970 in the Gregorian calendar was December 19th 1969 in the Julian calendar. /// </summary> /// <param name="calendar">The calendar system to convert this offset date and time to.</param> /// <returns>The converted OffsetDateTime.</returns> [Pure] public OffsetDateTime WithCalendar(CalendarSystem calendar) { LocalDate newDate = Date.WithCalendar(calendar); return new OffsetDateTime(newDate, offsetTime); } /// <summary> /// Returns this offset date/time, with the given date adjuster applied to it, maintaining the existing time of day and offset. /// </summary> /// <remarks> /// If the adjuster attempts to construct an /// invalid date (such as by trying to set a day-of-month of 30 in February), any exception thrown by /// that construction attempt will be propagated through this method. /// </remarks> /// <param name="adjuster">The adjuster to apply.</param> /// <returns>The adjusted offset date/time.</returns> [Pure] public OffsetDateTime With(Func<LocalDate, LocalDate> adjuster) => new OffsetDateTime(localDate.With(adjuster), offsetTime); /// <summary> /// Returns this date/time, with the given time adjuster applied to it, maintaining the existing date and offset. /// </summary> /// <remarks> /// If the adjuster attempts to construct an invalid time, any exception thrown by /// that construction attempt will be propagated through this method. /// </remarks> /// <param name="adjuster">The adjuster to apply.</param> /// <returns>The adjusted offset date/time.</returns> [Pure] public OffsetDateTime With(Func<LocalTime, LocalTime> adjuster) { LocalTime newTime = TimeOfDay.With(adjuster); return new OffsetDateTime(localDate, new OffsetTime(newTime.NanosecondOfDay, offsetTime.OffsetSeconds)); } /// <summary> /// Creates a new OffsetDateTime representing the instant in time in the same calendar, /// but with a different offset. The local date and time is adjusted accordingly. /// </summary> /// <param name="offset">The new offset to use.</param> /// <returns>The converted OffsetDateTime.</returns> [Pure] public OffsetDateTime WithOffset(Offset offset) { unchecked { // Slight change to the normal operation, as it's *just* about plausible that we change day // twice in one direction or the other. int days = 0; long nanos = offsetTime.NanosecondOfDay + offset.Nanoseconds - offsetTime.OffsetNanoseconds; if (nanos >= NanosecondsPerDay) { days++; nanos -= NanosecondsPerDay; if (nanos >= NanosecondsPerDay) { days++; nanos -= NanosecondsPerDay; } } else if (nanos < 0) { days--; nanos += NanosecondsPerDay; if (nanos < 0) { days--; nanos += NanosecondsPerDay; } } return new OffsetDateTime( days == 0 ? localDate : localDate.PlusDays(days), new OffsetTime(nanos, offset.Seconds)); } } /// <summary> /// Constructs a new <see cref="OffsetDate"/> from the date and offset of this value, /// but omitting the time-of-day. /// </summary> /// <returns>A value representing the date and offset aspects of this value.</returns> [Pure] public OffsetDate ToOffsetDate() => new OffsetDate(Date, Offset); /// <summary> /// Constructs a new <see cref="OffsetTime"/> from the time and offset of this value, /// but omitting the date. /// </summary> /// <returns>A value representing the time and offset aspects of this value.</returns> [Pure] public OffsetTime ToOffsetTime() => offsetTime; /// <summary> /// Returns a hash code for this offset date and time. /// See the type documentation for a description of equality semantics. /// </summary> /// <returns>A hash code for this offset date and time.</returns> public override int GetHashCode() => HashCodeHelper.Hash(localDate, offsetTime); /// <summary> /// Compares two <see cref="OffsetDateTime"/> values for equality. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="obj">The object to compare this date with.</param> /// <returns>True if the given value is another offset date/time equal to this one; false otherwise.</returns> public override bool Equals(object? obj) => obj is OffsetDateTime other && this == other; /// <summary> /// Compares two <see cref="OffsetDateTime"/> values for equality. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="other">The value to compare this offset date/time with.</param> /// <returns>True if the given value is another offset date/time equal to this one; false otherwise.</returns> public bool Equals(OffsetDateTime other) => this.localDate == other.localDate && this.offsetTime == other.offsetTime; /// <summary> /// Deconstruct this <see cref="OffsetDateTime"/> into its components. /// </summary> /// <param name="localDateTime">The <see cref="LocalDateTime"/> component.</param> /// <param name="offset">The <see cref="Offset"/> component.</param> [Pure] public void Deconstruct(out LocalDateTime localDateTime, out Offset offset) { localDateTime = LocalDateTime; offset = Offset; } /// <summary> /// Deconstruct this <see cref="OffsetDateTime"/> into its components. /// </summary> /// <param name="localDate">The <see cref="LocalDate"/> component.</param> /// <param name="localTime">The <see cref="LocalTime"/> component.</param> /// <param name="offset">The <see cref="Offset"/> component.</param> [Pure] public void Deconstruct(out LocalDate localDate, out LocalTime localTime, out Offset offset) { localDate = LocalDateTime.Date; localTime = LocalDateTime.TimeOfDay; offset = Offset; } #region Formatting /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// The value of the current instance in the default format pattern ("G"), using the current thread's /// culture to obtain a format provider. /// </returns> public override string ToString() => OffsetDateTimePattern.Patterns.BclSupport.Format(this, null, CultureInfo.CurrentCulture); /// <summary> /// Formats the value of the current instance using the specified pattern. /// </summary> /// <returns> /// A <see cref="T:System.String" /> containing the value of the current instance in the specified format. /// </returns> /// <param name="patternText">The <see cref="T:System.String" /> specifying the pattern to use, /// or null to use the default format pattern ("G"). /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when formatting the value, /// or null to use the current thread's culture to obtain a format provider. /// </param> /// <filterpriority>2</filterpriority> public string ToString(string? patternText, IFormatProvider? formatProvider) => OffsetDateTimePattern.Patterns.BclSupport.Format(this, patternText, formatProvider); #endregion Formatting #region Operators /// <summary> /// Adds a duration to an offset date and time. /// </summary> /// <remarks> /// This is an alternative way of calling <see cref="op_Addition(OffsetDateTime, Duration)"/>. /// </remarks> /// <param name="offsetDateTime">The value to add the duration to.</param> /// <param name="duration">The duration to add</param> /// <returns>A new value with the time advanced by the given duration, in the same calendar system and with the same offset.</returns> public static OffsetDateTime Add(OffsetDateTime offsetDateTime, Duration duration) => offsetDateTime + duration; /// <summary> /// Returns the result of adding a duration to this offset date and time. /// </summary> /// <remarks> /// This is an alternative way of calling <see cref="op_Addition(OffsetDateTime, Duration)"/>. /// </remarks> /// <param name="duration">The duration to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime Plus(Duration duration) => this + duration; /// <summary> /// Returns the result of adding a increment of hours to this offset date and time /// </summary> /// <param name="hours">The number of hours to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusHours(int hours) => this + Duration.FromHours(hours); /// <summary> /// Returns the result of adding an increment of minutes to this offset date and time /// </summary> /// <param name="minutes">The number of minutes to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusMinutes(int minutes) => this + Duration.FromMinutes(minutes); /// <summary> /// Returns the result of adding an increment of seconds to this offset date and time /// </summary> /// <param name="seconds">The number of seconds to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusSeconds(long seconds) => this + Duration.FromSeconds(seconds); /// <summary> /// Returns the result of adding an increment of milliseconds to this offset date and time /// </summary> /// <param name="milliseconds">The number of milliseconds to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusMilliseconds(long milliseconds) => this + Duration.FromMilliseconds(milliseconds); /// <summary> /// Returns the result of adding an increment of ticks to this offset date and time /// </summary> /// <param name="ticks">The number of ticks to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusTicks(long ticks) => this + Duration.FromTicks(ticks); /// <summary> /// Returns the result of adding an increment of nanoseconds to this offset date and time /// </summary> /// <param name="nanoseconds">The number of nanoseconds to add</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the addition.</returns> [Pure] public OffsetDateTime PlusNanoseconds(long nanoseconds) => this + Duration.FromNanoseconds(nanoseconds); /// <summary> /// Returns a new <see cref="OffsetDateTime"/> with the time advanced by the given duration. /// </summary> /// <remarks> /// The returned value retains the calendar system and offset of the <paramref name="offsetDateTime"/>. /// </remarks> /// <param name="offsetDateTime">The <see cref="OffsetDateTime"/> to add the duration to.</param> /// <param name="duration">The duration to add.</param> /// <returns>A new value with the time advanced by the given duration, in the same calendar system and with the same offset.</returns> public static OffsetDateTime operator +(OffsetDateTime offsetDateTime, Duration duration) => new OffsetDateTime(offsetDateTime.ToInstant() + duration, offsetDateTime.Offset); /// <summary> /// Subtracts a duration from an offset date and time. /// </summary> /// <remarks> /// This is an alternative way of calling <see cref="op_Subtraction(OffsetDateTime, Duration)"/>. /// </remarks> /// <param name="offsetDateTime">The value to subtract the duration from.</param> /// <param name="duration">The duration to subtract.</param> /// <returns>A new value with the time "rewound" by the given duration, in the same calendar system and with the same offset.</returns> public static OffsetDateTime Subtract(OffsetDateTime offsetDateTime, Duration duration) => offsetDateTime - duration; /// <summary> /// Returns the result of subtracting a duration from this offset date and time, for a fluent alternative to /// <see cref="op_Subtraction(OffsetDateTime, Duration)"/> /// </summary> /// <param name="duration">The duration to subtract</param> /// <returns>A new <see cref="OffsetDateTime" /> representing the result of the subtraction.</returns> [Pure] public OffsetDateTime Minus(Duration duration) => this - duration; /// <summary> /// Returns a new <see cref="OffsetDateTime"/> with the duration subtracted. /// </summary> /// <remarks> /// The returned value retains the calendar system and offset of the <paramref name="offsetDateTime"/>. /// </remarks> /// <param name="offsetDateTime">The value to subtract the duration from.</param> /// <param name="duration">The duration to subtract.</param> /// <returns>A new value with the time "rewound" by the given duration, in the same calendar system and with the same offset.</returns> public static OffsetDateTime operator -(OffsetDateTime offsetDateTime, Duration duration) => new OffsetDateTime(offsetDateTime.ToInstant() - duration, offsetDateTime.Offset); /// <summary> /// Subtracts one offset date and time from another, returning an elapsed duration. /// </summary> /// <remarks> /// This is an alternative way of calling <see cref="op_Subtraction(OffsetDateTime, OffsetDateTime)"/>. /// </remarks> /// <param name="end">The offset date and time value to subtract from; if this is later than <paramref name="start"/> /// then the result will be positive.</param> /// <param name="start">The offset date and time to subtract from <paramref name="end"/>.</param> /// <returns>The elapsed duration from <paramref name="start"/> to <paramref name="end"/>.</returns> public static Duration Subtract(OffsetDateTime end, OffsetDateTime start) => end - start; /// <summary> /// Returns the result of subtracting another offset date and time from this one, resulting in the elapsed duration /// between the two instants represented in the values. /// </summary> /// <remarks> /// This is an alternative way of calling <see cref="op_Subtraction(OffsetDateTime, OffsetDateTime)"/>. /// </remarks> /// <param name="other">The offset date and time to subtract from this one.</param> /// <returns>The elapsed duration from <paramref name="other"/> to this value.</returns> [Pure] public Duration Minus(OffsetDateTime other) => this - other; /// <summary> /// Subtracts one <see cref="OffsetDateTime"/> from another, resulting in the elapsed time between /// the two values. /// </summary> /// <remarks> /// This is equivalent to <c>end.ToInstant() - start.ToInstant()</c>; in particular: /// <list type="bullet"> /// <item><description>The two values can use different calendar systems</description></item> /// <item><description>The two values can have different UTC offsets</description></item> /// </list> /// </remarks> /// <param name="end">The offset date and time value to subtract from; if this is later than <paramref name="start"/> /// then the result will be positive.</param> /// <param name="start">The offset date and time to subtract from <paramref name="end"/>.</param> /// <returns>The elapsed duration from <paramref name="start"/> to <paramref name="end"/>.</returns> public static Duration operator -(OffsetDateTime end, OffsetDateTime start) => end.ToInstant() - start.ToInstant(); /// <summary> /// Implements the operator == (equality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are equal to each other, otherwise <c>false</c>.</returns> public static bool operator ==(OffsetDateTime left, OffsetDateTime right) => left.Equals(right); /// <summary> /// Implements the operator != (inequality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are not equal to each other, otherwise <c>false</c>.</returns> public static bool operator !=(OffsetDateTime left, OffsetDateTime right) => !(left == right); #endregion #region Comparers /// <summary> /// Base class for <see cref="OffsetDateTime"/> comparers. /// </summary> /// <remarks> /// Use the static properties of this class to obtain instances. This type is exposed so that the /// same value can be used for both equality and ordering comparisons. /// </remarks> [Immutable] public abstract class Comparer : IComparer<OffsetDateTime>, IEqualityComparer<OffsetDateTime> { // TODO(feature): Should we have a comparer which is calendar-sensitive (so will fail if the calendars are different) // but still uses the offset? /// <summary> /// Gets a comparer which compares <see cref="OffsetDateTime"/> values by their local date/time, without reference to /// the offset. Comparisons between two values of different calendar systems will fail with <see cref="ArgumentException"/>. /// </summary> /// <remarks> /// <para>For example, this comparer considers 2013-03-04T20:21:00+0100 to be later than 2013-03-04T19:21:00-0700 even though /// the second value represents a later instant in time.</para> /// <para>This property will return a reference to the same instance every time it is called.</para> /// </remarks> /// <value>A comparer which compares values by their local date/time, without reference to the offset.</value> public static Comparer Local => LocalComparer.Instance; /// <summary> /// Returns a comparer which compares <see cref="OffsetDateTime"/> values by the instant values obtained by applying the offset to /// the local date/time, ignoring the calendar system. /// </summary> /// <remarks> /// <para>For example, this comparer considers 2013-03-04T20:21:00+0100 to be earlier than 2013-03-04T19:21:00-0700 even though /// the second value has a local time which is earlier.</para> /// <para>This property will return a reference to the same instance every time it is called.</para> /// </remarks> /// <value>A comparer which compares values by the instant values obtained by applying the offset to /// the local date/time, ignoring the calendar system.</value> public static Comparer Instant => InstantComparer.Instance; /// <summary> /// Internal constructor to prevent external classes from deriving from this. /// (That means we can add more abstract members in the future.) /// </summary> internal Comparer() { } /// <summary> /// Compares two <see cref="OffsetDateTime"/> values and returns a value indicating whether one is less than, equal to, or greater than the other. /// </summary> /// <param name="x">The first value to compare.</param> /// <param name="y">The second value to compare.</param> /// <returns>A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown in the following table. /// <list type = "table"> /// <listheader> /// <term>Value</term> /// <description>Meaning</description> /// </listheader> /// <item> /// <term>Less than zero</term> /// <description><paramref name="x"/> is less than <paramref name="y"/>.</description> /// </item> /// <item> /// <term>Zero</term> /// <description><paramref name="x"/> is equals to <paramref name="y"/>.</description> /// </item> /// <item> /// <term>Greater than zero</term> /// <description><paramref name="x"/> is greater than <paramref name="y"/>.</description> /// </item> /// </list> /// </returns> public abstract int Compare(OffsetDateTime x, OffsetDateTime y); /// <summary> /// Determines whether the specified <c>OffsetDateTime</c> values are equal. /// </summary> /// <param name="x">The first <c>OffsetDateTime</c> to compare.</param> /// <param name="y">The second <c>OffsetDateTime</c> to compare.</param> /// <returns><c>true</c> if the specified objects are equal; otherwise, <c>false</c>.</returns> public abstract bool Equals(OffsetDateTime x, OffsetDateTime y); /// <summary> /// Returns a hash code for the specified <c>OffsetDateTime</c>. /// </summary> /// <param name="obj">The <c>OffsetDateTime</c> for which a hash code is to be returned.</param> /// <returns>A hash code for the specified value.</returns> public abstract int GetHashCode(OffsetDateTime obj); } /// <summary> /// Implementation for <see cref="Comparer.Local"/> /// </summary> private sealed class LocalComparer : Comparer { internal static readonly Comparer Instance = new LocalComparer(); private LocalComparer() { } /// <inheritdoc /> public override int Compare(OffsetDateTime x, OffsetDateTime y) { Preconditions.CheckArgument(x.Calendar.Equals(y.Calendar), nameof(y), "Only values with the same calendar system can be compared"); int dateComparison = x.Calendar.Compare(x.YearMonthDay, y.YearMonthDay); if (dateComparison != 0) { return dateComparison; } return x.NanosecondOfDay.CompareTo(y.NanosecondOfDay); } /// <inheritdoc /> public override bool Equals(OffsetDateTime x, OffsetDateTime y) => x.localDate == y.localDate && x.NanosecondOfDay == y.NanosecondOfDay; /// <inheritdoc /> public override int GetHashCode(OffsetDateTime obj) => HashCodeHelper.Hash(obj.localDate, obj.NanosecondOfDay); } /// <summary> /// Implementation for <see cref="Comparer.Instant"/>. /// </summary> private sealed class InstantComparer : Comparer { internal static readonly Comparer Instance = new InstantComparer(); private InstantComparer() { } /// <inheritdoc /> public override int Compare(OffsetDateTime x, OffsetDateTime y) => // TODO(optimization): Optimize cases which are more than 2 days apart, by avoiding the arithmetic? x.ToElapsedTimeSinceEpoch().CompareTo(y.ToElapsedTimeSinceEpoch()); /// <inheritdoc /> public override bool Equals(OffsetDateTime x, OffsetDateTime y) => x.ToElapsedTimeSinceEpoch() == y.ToElapsedTimeSinceEpoch(); /// <inheritdoc /> public override int GetHashCode(OffsetDateTime obj) => obj.ToElapsedTimeSinceEpoch().GetHashCode(); } #endregion #region XML serialization /// <summary> /// Adds the XML schema type describing the structure of the <see cref="OffsetDateTime"/> XML serialization to the given <paramref name="xmlSchemaSet"/>. /// </summary> /// <param name="xmlSchemaSet">The XML schema set provided by <see cref="XmlSchemaExporter"/>.</param> /// <returns>The qualified name of the schema type that was added to the <paramref name="xmlSchemaSet"/>.</returns> public static XmlQualifiedName AddSchema(XmlSchemaSet xmlSchemaSet) => Xml.XmlSchemaDefinition.AddOffsetDateTimeSchemaType(xmlSchemaSet); /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that /// <inheritdoc /> void IXmlSerializable.ReadXml(XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = OffsetDateTimePattern.Rfc3339; if (reader.MoveToAttribute("calendar")) { string newCalendarId = reader.Value; CalendarSystem newCalendar = CalendarSystem.ForId(newCalendarId); var newTemplateValue = pattern.TemplateValue.WithCalendar(newCalendar); pattern = pattern.WithTemplateValue(newTemplateValue); reader.MoveToElement(); } string text = reader.ReadElementContentAsString(); Unsafe.AsRef(this) = pattern.Parse(text).Value; } /// <inheritdoc /> void IXmlSerializable.WriteXml(XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); if (Calendar != CalendarSystem.Iso) { writer.WriteAttributeString("calendar", Calendar.Id); } writer.WriteString(OffsetDateTimePattern.Rfc3339.Format(this)); } #endregion } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { using static MethodDebugInfoValidation; public class UsingDebugInfoTests : ExpressionCompilerTestBase { #region Grouped import strings [Fact] public void SimplestCase() { var source = @" using System; class C { void M() { } } "; var comp = CreateCompilationWithMscorlib(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M").ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedScopes() { var source = @" using System; class C { void M() { int i = 1; { int j = 2; } } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0, //i int V_1) //j IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldc.i4.2 IL_0005: stloc.1 IL_0006: nop IL_0007: ret } "); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M", ilOffset: 0x0004).ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedNamespaces() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { void M() { } } } "; var comp = CreateCompilationWithMscorlib(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void Forward() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { // One of these methods will forward to the other since they're adjacent. void M1() { } void M2() { } } } "; var comp = CreateCompilationWithMscorlib(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M1").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); GetMethodDebugInfo(runtime, "A.C.M2").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void ImportKinds() { var source = @" extern alias A; using S = System; namespace B { using F = S.IO.File; using System.Text; class C { void M() { } } } "; var aliasedRef = CreateCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' Type: alias='F' type='System.IO.File' } { Assembly: alias='A' Namespace: alias='S' string='System' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportKinds_StaticType() { var libSource = @" namespace N { public static class Static { } } "; var source = @" extern alias A; using static System.Math; namespace B { using static A::N.Static; class C { void M() { } } } "; var aliasedRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Type: type='N.Static' } { Assembly: alias='A' Type: type='System.Math' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [Fact] public void ForwardToModule() { var source = @" extern alias A; namespace B { using System; class C { void M1() { } } } namespace D { using System.Text; // Different using to prevent normal forwarding. class E { void M2() { } } } "; var aliasedRef = CreateCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var debugInfo1 = GetMethodDebugInfo(runtime, "B.C.M1"); debugInfo1.ImportRecordGroups.Verify(@" { Namespace: string='System' } { Assembly: alias='A' }"); debugInfo1.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); var debugInfo2 = GetMethodDebugInfo(runtime, "D.E.M2"); debugInfo2.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' } { Assembly: alias='A' }"); debugInfo2.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } #endregion #region Invalid PDBs [Fact] public void BadPdb_ForwardChain() { const int methodVersion = 1; const int methodToken1 = 0x600057a; // Forwards to 2 const int methodToken2 = 0x600055d; // Forwards to 3 const int methodToken3 = 0x6000540; // Has a using const string importString = "USystem"; var symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build() }, { methodToken2, new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build() }, { methodToken3, new MethodDebugInfoBytes.Builder(new [] { new [] { importString } }).Build() }, }.ToImmutableDictionary()); ImmutableArray<string> externAliasStrings; var importStrings = symReader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); importStrings = symReader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); importStrings = symReader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); } [Fact] public void BadPdb_Cycle() { const int methodVersion = 1; const int methodToken1 = 0x600057a; // Forwards to itself var symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build() }, }.ToImmutableDictionary()); ImmutableArray<string> externAliasStrings; var importStrings = symReader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_InvalidAliasSyntax() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilationWithMscorlib(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_DotInAlias() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilationWithMscorlib(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooMany() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilationWithMscorlib(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooFew() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilationWithMscorlib(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void BadPdb_NonStaticTypeImport() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilationWithMscorlib(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } #endregion Invalid PDBs #region Binder chain [Fact] public void ImportsForSimpleUsing() { var source = @" using System; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal("System", actualNamespace.ToTestDisplayString()); }); } [Fact] public void ImportsForMultipleUsings() { var source = @" using System; using System.IO; using System.Text; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray(); Assert.Equal(3, usings.Length); var expectedNames = new[] { "System", "System.IO", "System.Text" }; for (int i = 0; i < usings.Length; i++) { var actualNamespace = usings[i]; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNestedNamespaces() { var source = @" using System; namespace A { using System.IO; class C { int M() { return 1; } } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "A.C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()).AsEnumerable().ToArray(); Assert.Equal(2, importsList.Length); var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost for (int i = 0; i < importsList.Length; i++) { var imports = importsList[i]; Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNamespaceAlias() { var source = @" using S = System; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("S", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("S", aliasSymbol.Name); var namespaceSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind); Assert.Equal("System", namespaceSymbol.ToTestDisplayString()); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportsForStaticType() { var source = @" using static System.Math; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualType = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.NamedType, actualType.Kind); Assert.Equal("System.Math", actualType.ToTestDisplayString()); }); } [Fact] public void ImportsForTypeAlias() { var source = @" using I = System.Int32; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType); }); } [Fact] public void ImportsForVerbatimIdentifiers() { var source = @" using @namespace; using @object = @namespace; using @string = @namespace.@class<@namespace.@interface>.@struct; namespace @namespace { public class @class<T> { public struct @struct { } } public interface @interface { } } class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("namespace", importedNamespace.Name); var usingAliases = imports.UsingAliases; const string keyword1 = "object"; const string keyword2 = "string"; AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2); var namespaceAlias = usingAliases[keyword1]; var typeAlias = usingAliases[keyword2]; Assert.Equal(keyword1, namespaceAlias.Alias.Name); var aliasedNamespace = namespaceAlias.Alias.Target; Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind); Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString()); Assert.Equal(keyword2, typeAlias.Alias.Name); var aliasedType = typeAlias.Alias.Target; Assert.Equal(SymbolKind.NamedType, aliasedType.Kind); Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString()); }); } [Fact] public void ImportsForGenericTypeAlias() { var source = @" using I = System.Collections.Generic.IEnumerable<string>; class C { int M() { return 1; } } "; var comp = CreateCompilationWithMscorlib(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString()); }); } [Fact] public void ImportsForExternAlias() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.VerifyDiagnostics(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.UsingAliases.Count); var externAliases = imports.ExternAliases; Assert.Equal(1, externAliases.Length); var aliasSymbol = externAliases.Single().Alias; Assert.Equal("X", aliasSymbol.Name); var targetSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind); Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace); Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name); }); } [Fact] public void ImportsForUsingsConsumingExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(1, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString()); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO"); var typeAlias = usingAliases["SXL"].Alias; Assert.Equal("SXL", typeAlias.Name); Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString()); var namespaceAlias = usingAliases["LO"].Alias; Assert.Equal("LO", namespaceAlias.Name); Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString()); }); } [Fact] public void ImportsForUsingsConsumingExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(1, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "A", "B"); var aliasA = usingAliases["A"].Alias; Assert.Equal("A", aliasA.Name); Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString()); var aliasB = usingAliases["B"].Alias; Assert.Equal("B", aliasB.Name); Assert.Equal(aliasA.Target, aliasB.Target); }); } private static ImportChain GetImports(RuntimeInstance runtime, string methodName, Syntax.ExpressionSyntax syntax) { var evalContext = CreateMethodContext(runtime, methodName); var compContext = evalContext.CreateCompilationContext(syntax); return compContext.NamespaceBinder.ImportChain; } #endregion Binder chain [Fact] public void NoSymbols() { var source = @"using N; class A { static void M() { } } namespace N { class B { static void M() { } } }"; ResultProperties resultProperties; string error; // With symbols, type reference without namespace qualifier. var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference without namespace qualifier. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Equal(error, "error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)"); // With symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Null(error); } [WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")] [Fact] public void AssemblyQualifiedNameResolutionWithUnification() { var source1 = @" using SI = System.Int32; public class C1 { void M() { } } "; var source2 = @" public class C2 : C1 { } "; var comp1 = CreateCompilation(source1, new[] { MscorlibRef_v20 }, TestOptions.DebugDll); var module1 = comp1.ToModuleInstance(); var comp2 = CreateCompilation(source2, new[] { MscorlibRef_v4_0_30316_17626, module1.GetReference() }, TestOptions.DebugDll); var module2 = comp2.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C1.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(SI)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } } internal static class ImportChainExtensions { internal static Imports Single(this ImportChain importChain) { return importChain.AsEnumerable().Single(); } internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain) { for (var chain = importChain; chain != null; chain = chain.ParentOpt) { yield return chain.Imports; } } } }
/* * 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.Diagnostics; using System.Net; using System.IO; using System.Net.Sockets; using Xunit; using System.Collections; using System.Text.RegularExpressions; using System.Collections.Generic; using Xunit.Abstractions; namespace Apache.Geode.Client.IntegrationTests { public class GfshExecute : Gfsh { private String connectionCommand_ = null; private ITestOutputHelper output; public GfshExecute(ITestOutputHelper output) { this.output = output; } private void ExtractConnectionCommand(String command) { if (command.StartsWith("connect")) { connectionCommand_ = command; } else if (command.StartsWith("start locator")) { if (command.Contains("--connect=false")) { return; } var jmxManagerHost = "localhost"; var jmxManagerPort = "1099"; var jmxManagerHostRegex = new Regex(@"\bbind-address=([^\s])\b"); var jmxManagerHostMatch = jmxManagerHostRegex.Match(command); if (jmxManagerHostMatch.Success) { jmxManagerHost = jmxManagerHostMatch.Groups[1].Value; } var jmxManagerPortRegex = new Regex(@"\bjmx-manager-port=(\d+)\b"); var jmxManagerPortMatch = jmxManagerPortRegex.Match(command); if (jmxManagerPortMatch.Success) { jmxManagerPort = jmxManagerPortMatch.Groups[1].Value; } connectionCommand_ = new Connect(this).withJmxManager(jmxManagerHost, int.Parse(jmxManagerPort)).ToString(); } } public override int execute(string cmd) { var commands = new List<string>(); if (null != connectionCommand_) { commands.Add("-e"); commands.Add(connectionCommand_); } commands.Add("-e"); commands.Add(cmd); // TODO escape commands var fullCmd = "\"" + string.Join("\" \"", commands) + "\""; var gfsh = new Process { StartInfo = { FileName = Config.GeodeGfsh, Arguments = fullCmd, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = false } }; gfsh.OutputDataReceived += (sender, args) => { if (args.Data != null) { WriteLine("GfshExecute: " + args.Data); } }; gfsh.ErrorDataReceived += (sender, args) => { if (args.Data != null) { WriteLine("GfshExecute: ERROR: " + args.Data); } }; gfsh.Start(); gfsh.BeginOutputReadLine(); gfsh.BeginErrorReadLine(); if (gfsh.WaitForExit(60000)) { WriteLine("GeodeServer Start: gfsh.HasExited = {0}, gfsh.ExitCode = {1}", gfsh.HasExited, gfsh.ExitCode); } else { WriteLine("GeodeServer Start: gfsh failed to exit, force killing."); KillAndIgnore(gfsh); } CancelErrorReadAndIgnore(gfsh); CancelOutputReadAndIgnore(gfsh); ExtractConnectionCommand(cmd); return gfsh.ExitCode; } private static void CancelOutputReadAndIgnore(Process gfsh) { try { gfsh.CancelOutputRead(); } catch { // ignored } } private static void CancelErrorReadAndIgnore(Process gfsh) { try { gfsh.CancelErrorRead(); } catch { // ignored } } private static void KillAndIgnore(Process gfsh) { try { gfsh.Kill(); } catch { // ignored } } private void WriteLine(string format, params object[] args) { if (null == output) { Debug.WriteLine(format, args); } else { output.WriteLine(format, args); } } private void WriteLine(string message) { if (null == output) { Debug.WriteLine(message); } else { output.WriteLine(message); } } } }
using System; using System.Collections.Generic; using System.IO; using SharpDX; namespace AssetStudio { public interface IImported { List<ImportedFrame> FrameList { get; } List<ImportedMesh> MeshList { get; } List<ImportedMaterial> MaterialList { get; } List<ImportedTexture> TextureList { get; } List<ImportedAnimation> AnimationList { get; } List<ImportedMorph> MorphList { get; } } public class ImportedFrame : ObjChildren<ImportedFrame>, IObjChild { public string Name { get; set; } public Matrix Matrix { get; set; } public dynamic Parent { get; set; } } public class ImportedMesh { public string Name { get; set; } public List<ImportedSubmesh> SubmeshList { get; set; } public List<ImportedBone> BoneList { get; set; } } public class ImportedSubmesh { public List<ImportedVertex> VertexList { get; set; } public List<ImportedFace> FaceList { get; set; } public string Material { get; set; } public int Index { get; set; } public bool WorldCoords { get; set; } public bool Visible { get; set; } } public class ImportedVertex { public Vector3 Position { get; set; } public float[] Weights { get; set; } public byte[] BoneIndices { get; set; } public Vector3 Normal { get; set; } public float[] UV { get; set; } public Vector4 Tangent { get; set; } } public class ImportedVertexWithColour : ImportedVertex { public Color4 Colour { get; set; } } public class ImportedFace { public int[] VertexIndices { get; set; } } public class ImportedBone { public string Name { get; set; } public Matrix Matrix { get; set; } } public class ImportedMaterial { public string Name { get; set; } public Color4 Diffuse { get; set; } public Color4 Ambient { get; set; } public Color4 Specular { get; set; } public Color4 Emissive { get; set; } public float Power { get; set; } public string[] Textures { get; set; } public Vector2[] TexOffsets { get; set; } public Vector2[] TexScales { get; set; } } public class ImportedTexture { public string Name { get; set; } public byte[] Data { get; set; } public ImportedTexture(MemoryStream stream, string name) { Name = name; Data = stream.ToArray(); } } public abstract class ImportedAnimation { public string Name { get; set; } } public abstract class ImportedAnimationTrackContainer<TrackType> : ImportedAnimation where TrackType : ImportedAnimationTrack { public List<TrackType> TrackList { get; set; } public TrackType FindTrack(string name) { return TrackList.Find(track => track.Name == name); } } public class ImportedKeyframedAnimation : ImportedAnimationTrackContainer<ImportedAnimationKeyframedTrack> { } public class ImportedSampledAnimation : ImportedAnimationTrackContainer<ImportedAnimationSampledTrack> { public float SampleRate { get; set; } } public abstract class ImportedAnimationTrack { public string Name { get; set; } } public class ImportedKeyframe<T> { public float time { get; set; } public T value { get; set; } public T inSlope { get; set; } public T outSlope { get; set; } public ImportedKeyframe(float time, T value, T inSlope, T outSlope) { this.time = time; this.value = value; this.inSlope = inSlope; this.outSlope = outSlope; } } public class ImportedAnimationKeyframedTrack : ImportedAnimationTrack { public List<ImportedKeyframe<Vector3>> Scalings = new List<ImportedKeyframe<Vector3>>(); public List<ImportedKeyframe<Vector3>> Rotations = new List<ImportedKeyframe<Vector3>>(); public List<ImportedKeyframe<Vector3>> Translations = new List<ImportedKeyframe<Vector3>>(); } public class ImportedAnimationSampledTrack : ImportedAnimationTrack { public Vector3?[] Scalings; public Quaternion?[] Rotations; public Vector3?[] Translations; public float?[] Curve; } public class ImportedMorph { public string Name { get; set; } public string ClipName { get; set; } public List<Tuple<float, int, int>> Channels { get; set; } public List<ImportedMorphKeyframe> KeyframeList { get; set; } public List<ushort> MorphedVertexIndices { get; set; } } public class ImportedMorphKeyframe { public string Name { get; set; } public List<ImportedVertex> VertexList { get; set; } public List<ushort> MorphedVertexIndices { get; set; } public float Weight { get; set; } } public static class ImportedHelpers { public static ImportedFrame FindFrame(String name, ImportedFrame root) { ImportedFrame frame = root; if ((frame != null) && (frame.Name == name)) { return frame; } for (int i = 0; i < root.Count; i++) { if ((frame = FindFrame(name, root[i])) != null) { return frame; } } return null; } public static ImportedMesh FindMesh(String frameName, List<ImportedMesh> importedMeshList) { foreach (ImportedMesh mesh in importedMeshList) { if (mesh.Name == frameName) { return mesh; } } return null; } public static ImportedMesh FindMesh(ImportedFrame frame, List<ImportedMesh> importedMeshList) { string framePath = frame.Name; ImportedFrame root = frame; while (root.Parent != null) { root = root.Parent; framePath = root.Name + "/" + framePath; } foreach (ImportedMesh mesh in importedMeshList) { if (mesh.Name == framePath) { return mesh; } } return null; } public static ImportedMaterial FindMaterial(String name, List<ImportedMaterial> importedMats) { foreach (ImportedMaterial mat in importedMats) { if (mat.Name == name) { return mat; } } return null; } public static ImportedTexture FindTexture(string name, List<ImportedTexture> importedTextureList) { if (string.IsNullOrEmpty(name)) { return null; } foreach (ImportedTexture tex in importedTextureList) { if (tex.Name == name) { return tex; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Razor.Language.Legacy; using Microsoft.AspNetCore.Razor.Language.Syntax; using Xunit; namespace Microsoft.AspNetCore.Razor.Language.Test.Legacy { public class CSharpCodeParserTest { public static TheoryData InvalidTagHelperPrefixData { get { var directiveLocation = new SourceLocation(1, 2, 3); RazorDiagnostic InvalidPrefixError(int length, char character, string prefix) { return RazorDiagnosticFactory.CreateParsing_InvalidTagHelperPrefixValue( new SourceSpan(directiveLocation, length), SyntaxConstants.CSharp.TagHelperPrefixKeyword, character, prefix); } return new TheoryData<string, SourceLocation, IEnumerable<RazorDiagnostic>> { { "th ", directiveLocation, new[] { InvalidPrefixError(3, ' ', "th "), } }, { "th\t", directiveLocation, new[] { InvalidPrefixError(3, '\t', "th\t"), } }, { "th" + Environment.NewLine, directiveLocation, new[] { InvalidPrefixError(2 + Environment.NewLine.Length, Environment.NewLine[0], "th" + Environment.NewLine), } }, { " th ", directiveLocation, new[] { InvalidPrefixError(4, ' ', " th "), } }, { "@", directiveLocation, new[] { InvalidPrefixError(1, '@', "@"), } }, { "t@h", directiveLocation, new[] { InvalidPrefixError(3, '@', "t@h"), } }, { "!", directiveLocation, new[] { InvalidPrefixError(1, '!', "!"), } }, { "!th", directiveLocation, new[] { InvalidPrefixError(3, '!', "!th"), } }, }; } } [Theory] [MemberData(nameof(InvalidTagHelperPrefixData))] public void ValidateTagHelperPrefix_ValidatesPrefix( string directiveText, SourceLocation directiveLocation, object expectedErrors) { // Arrange var expectedDiagnostics = (IEnumerable<RazorDiagnostic>)expectedErrors; var source = TestRazorSourceDocument.Create(); var options = RazorParserOptions.CreateDefault(); var context = new ParserContext(source, options); var parser = new CSharpCodeParser(context); var diagnostics = new List<RazorDiagnostic>(); // Act parser.ValidateTagHelperPrefix(directiveText, directiveLocation, diagnostics); // Assert Assert.Equal(expectedDiagnostics, diagnostics); } [Theory] [InlineData("foo,assemblyName", 4)] [InlineData("foo, assemblyName", 5)] [InlineData(" foo, assemblyName", 8)] [InlineData(" foo , assemblyName", 11)] [InlineData("foo, assemblyName", 8)] [InlineData(" foo , assemblyName ", 14)] public void ParseAddOrRemoveDirective_CalculatesAssemblyLocationInLookupText(string text, int assemblyLocation) { // Arrange var source = TestRazorSourceDocument.Create(); var options = RazorParserOptions.CreateDefault(); var context = new ParserContext(source, options); var parser = new CSharpCodeParser(context); var directive = new CSharpCodeParser.ParsedDirective() { DirectiveText = text, }; var diagnostics = new List<RazorDiagnostic>(); var expected = new SourceLocation(assemblyLocation, 0, assemblyLocation); // Act var result = parser.ParseAddOrRemoveDirective(directive, SourceLocation.Zero, diagnostics); // Assert Assert.Empty(diagnostics); Assert.Equal("foo", result.TypePattern); Assert.Equal("assemblyName", result.AssemblyName); } [Theory] [InlineData("", 1)] [InlineData("*,", 2)] [InlineData("?,", 2)] [InlineData(",", 1)] [InlineData(",,,", 3)] [InlineData("First, ", 7)] [InlineData("First , ", 8)] [InlineData(" ,Second", 8)] [InlineData(" , Second", 9)] [InlineData("SomeType,", 9)] [InlineData("SomeAssembly", 12)] [InlineData("First,Second,Third", 18)] public void ParseAddOrRemoveDirective_CreatesErrorIfInvalidLookupText_DoesNotThrow(string directiveText, int errorLength) { // Arrange var source = TestRazorSourceDocument.Create(); var options = RazorParserOptions.CreateDefault(); var context = new ParserContext(source, options); var parser = new CSharpCodeParser(context); var directive = new CSharpCodeParser.ParsedDirective() { DirectiveText = directiveText }; var diagnostics = new List<RazorDiagnostic>(); var expectedError = RazorDiagnosticFactory.CreateParsing_InvalidTagHelperLookupText( new SourceSpan(new SourceLocation(1, 2, 3), errorLength), directiveText); // Act var result = parser.ParseAddOrRemoveDirective(directive, new SourceLocation(1, 2, 3), diagnostics); // Assert Assert.Same(directive, result); var error = Assert.Single(diagnostics); Assert.Equal(expectedError, error); } [Fact] public void TagHelperPrefixDirective_DuplicatesCauseError() { // Arrange var expectedDiagnostic = RazorDiagnosticFactory.CreateParsing_DuplicateDirective( new SourceSpan(null, 22 + Environment.NewLine.Length, 1, 0, 16), "tagHelperPrefix"); var source = TestRazorSourceDocument.Create( @"@tagHelperPrefix ""th:"" @tagHelperPrefix ""th""", filePath: null); // Act var document = RazorSyntaxTree.Parse(source); // Assert var erroredNode = document.Root.DescendantNodes().Last(n => n.GetSpanContext()?.ChunkGenerator is TagHelperPrefixDirectiveChunkGenerator); var chunkGenerator = Assert.IsType<TagHelperPrefixDirectiveChunkGenerator>(erroredNode.GetSpanContext().ChunkGenerator); var diagnostic = Assert.Single(chunkGenerator.Diagnostics); Assert.Equal(expectedDiagnostic, diagnostic); } [Fact] public void MapDirectives_HandlesDuplicates() { // Arrange var source = TestRazorSourceDocument.Create(); var options = RazorParserOptions.CreateDefault(); var context = new ParserContext(source, options); var parser = new CSharpCodeParser(context); // Act & Assert (Does not throw) parser.MapDirectives((b, t) => { }, "test"); parser.MapDirectives((b, t) => { }, "test"); } } }
// 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.Data.Common; using System.Data.SqlTypes; using System.IO; using System.Linq; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class SqlServerTypesTest { [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void GetSchemaTableTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn)) { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo)) { DataTable schemaTable = reader.GetSchemaTable(); DataTestUtility.AssertEqualsWithDescription(1, schemaTable.Rows.Count, "Unexpected schema table row count."); string columnName = (string)(string)schemaTable.Rows[0][schemaTable.Columns["ColumnName"]]; DataTestUtility.AssertEqualsWithDescription("col0", columnName, "Unexpected column name."); string dataTypeName = (string)schemaTable.Rows[0][schemaTable.Columns["DataTypeName"]]; DataTestUtility.AssertEqualsWithDescription("Northwind.sys.hierarchyid", dataTypeName, "Unexpected data type name."); string udtAssemblyName = (string)schemaTable.Rows[0][schemaTable.Columns["UdtAssemblyQualifiedName"]]; Assert.True(udtAssemblyName?.StartsWith("Microsoft.SqlServer.Types.SqlHierarchyId"), "Unexpected UDT assembly name: " + udtAssemblyName); } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void GetValueTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn)) { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.True(reader.Read()); // SqlHierarchyId is part of Microsoft.SqlServer.Types, which is not supported in Core Assert.Throws<FileNotFoundException>(() => reader.GetValue(0)); Assert.Throws<FileNotFoundException>(() => reader.GetSqlValue(0)); } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtZeroByte() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/') as col0"; using (SqlDataReader reader = command.ExecuteReader()) { Assert.True(reader.Read()); Assert.False(reader.IsDBNull(0)); SqlBytes sqlBytes = reader.GetSqlBytes(0); Assert.False(sqlBytes.IsNull, "Expected a zero length byte array"); Assert.True(sqlBytes.Length == 0, "Expected a zero length byte array"); } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetSqlBytesSequentialAccess() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.SequentialAccess); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetSqlBytes() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetSqlBytes(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); SqlBytes sqlBytes = null; sqlBytes = reader.GetSqlBytes(0); Assert.Equal("5ade", ToHexString(sqlBytes.Value)); sqlBytes = reader.GetSqlBytes(1); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(sqlBytes.Value)); sqlBytes = reader.GetSqlBytes(2); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(sqlBytes.Value)); if (behavior == CommandBehavior.Default) { sqlBytes = reader.GetSqlBytes(0); Assert.Equal("5ade", ToHexString(sqlBytes.Value)); } } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetBytesSequentialAccess() { TestUdtSqlDataReaderGetBytes(CommandBehavior.SequentialAccess); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetBytes() { TestUdtSqlDataReaderGetBytes(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetBytes(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); int byteCount = 0; byte[] bytes = null; byteCount = (int)reader.GetBytes(0, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(0, 0, bytes, 0, bytes.Length); Assert.Equal("5ade", ToHexString(bytes)); byteCount = (int)reader.GetBytes(1, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(1, 0, bytes, 0, bytes.Length); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes)); byteCount = (int)reader.GetBytes(2, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(2, 0, bytes, 0, bytes.Length); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes)); if (behavior == CommandBehavior.Default) { byteCount = (int)reader.GetBytes(0, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(0, 0, bytes, 0, bytes.Length); Assert.Equal("5ade", ToHexString(bytes)); } } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetStreamSequentialAccess() { TestUdtSqlDataReaderGetStream(CommandBehavior.SequentialAccess); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSqlDataReaderGetStream() { TestUdtSqlDataReaderGetStream(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetStream(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); MemoryStream buffer = null; byte[] bytes = null; buffer = new MemoryStream(); using (Stream stream = reader.GetStream(0)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("5ade", ToHexString(bytes)); buffer = new MemoryStream(); using (Stream stream = reader.GetStream(1)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes)); buffer = new MemoryStream(); using (Stream stream = reader.GetStream(2)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes)); if (behavior == CommandBehavior.Default) { buffer = new MemoryStream(); using (Stream stream = reader.GetStream(0)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("5ade", ToHexString(bytes)); } } } } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtSchemaMetadata() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly)) { ReadOnlyCollection<DbColumn> columns = reader.GetColumnSchema(); DbColumn column = null; // Validate Microsoft.SqlServer.Types.SqlHierarchyId, Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91 column = columns[0]; Assert.Equal("col0", column.ColumnName); Assert.True(column.DataTypeName.EndsWith(".hierarchyid"), $"Unexpected DataTypeName \"{column.DataTypeName}\""); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlHierarchyId"); // Validate Microsoft.SqlServer.Types.SqlGeometry, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91 column = columns[1]; Assert.Equal("col1", column.ColumnName); Assert.True(column.DataTypeName.EndsWith(".geometry"), $"Unexpected DataTypeName \"{column.DataTypeName}\""); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeometry"); // Validate Microsoft.SqlServer.Types.SqlGeography, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91 column = columns[2]; Assert.Equal("col2", column.ColumnName); Assert.True(column.DataTypeName.EndsWith(".geography"), $"Unexpected DataTypeName \"{column.DataTypeName}\""); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeography"); } } } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtParameterSetSqlByteValue() { const string ExpectedPointValue = "POINT (1 1)"; SqlBytes geometrySqlBytes = null; string actualtPointValue = null; using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')"; using (var reader = command.ExecuteReader()) { reader.Read(); geometrySqlBytes = reader.GetSqlBytes(0); } } using (var command = connection.CreateCommand()) { command.CommandText = "SELECT @geometry.STAsText()"; var parameter = command.Parameters.AddWithValue("@geometry", geometrySqlBytes); parameter.SqlDbType = SqlDbType.Udt; parameter.UdtTypeName = "geometry"; actualtPointValue = Convert.ToString(command.ExecuteScalar()); } Assert.Equal(ExpectedPointValue, actualtPointValue); } } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void TestUdtParameterSetRawByteValue() { const string ExpectedPointValue = "POINT (1 1)"; byte[] geometryBytes = null; string actualtPointValue = null; using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')"; using (var reader = command.ExecuteReader()) { reader.Read(); geometryBytes = reader.GetSqlBytes(0).Buffer; } } using (var command = connection.CreateCommand()) { command.CommandText = "SELECT @geometry.STAsText()"; var parameter = command.Parameters.AddWithValue("@geometry", geometryBytes); parameter.SqlDbType = SqlDbType.Udt; parameter.UdtTypeName = "geometry"; actualtPointValue = Convert.ToString(command.ExecuteScalar()); } Assert.Equal(ExpectedPointValue, actualtPointValue); } } private static void AssertSqlUdtAssemblyQualifiedName(string assemblyQualifiedName, string expectedType) { List<string> parts = assemblyQualifiedName.Split(',').Select(x => x.Trim()).ToList(); string type = parts[0]; string assembly = parts.Count < 2 ? string.Empty : parts[1]; string version = parts.Count < 3 ? string.Empty : parts[2]; string culture = parts.Count < 4 ? string.Empty : parts[3]; string token = parts.Count < 5 ? string.Empty : parts[4]; Assert.Equal(expectedType, type); Assert.Equal("Microsoft.SqlServer.Types", assembly); Assert.StartsWith("Version", version); Assert.StartsWith("Culture", culture); Assert.StartsWith("PublicKeyToken", token); } private static string ToHexString(byte[] bytes) { StringBuilder hex = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { hex.AppendFormat("{0:x2}", b); } return hex.ToString(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Stream ** ** <OWNER>gpaperin</OWNER> ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ /* * https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/stream.cs */ using System; using System.Runtime; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.Contracts; using System.Reflection; namespace System.IO { public abstract class Stream : IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920; public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } [ComVisible(false)] public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } [ComVisible(false)] public virtual int ReadTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } [ComVisible(false)] public virtual int WriteTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { if (destination == null) throw new ArgumentNullException("destination"); if (!CanRead && !CanWrite) throw new Exception(); if (!destination.CanRead && !destination.CanWrite) throw new Exception("destination"); if (!CanRead) throw new NotSupportedException(); if (!destination.CanWrite) throw new NotSupportedException(); Contract.EndContractBlock(); InternalCopyTo(destination, _DefaultCopyBufferSize); } public void CopyTo(Stream destination, int bufferSize) { if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); if (!CanRead && !CanWrite) throw new Exception(); if (!destination.CanRead && !destination.CanWrite) throw new Exception("destination"); if (!CanRead) throw new NotSupportedException(); if (!destination.CanWrite) throw new NotSupportedException(); Contract.EndContractBlock(); InternalCopyTo(destination, bufferSize); } private void InternalCopyTo(Stream destination, int bufferSize) { Contract.Requires(destination != null); Contract.Requires(CanRead); Contract.Requires(destination.CanWrite); Contract.Requires(bufferSize > 0); byte[] buffer = new byte[bufferSize]; int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) destination.Write(buffer, 0, read); } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Dispose(true); } public void Dispose() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); [HostProtection(ExternalThreading = true)] public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginReadInternal(byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanRead) __Error.ReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginWriteInternal(byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanWrite) __Error.WriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read([In, Out] byte[] buffer, int offset, int count); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < 256); byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) return -1; return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } public static Stream Synchronized(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); Contract.Ensures(Contract.Result<Stream>() != null); Contract.EndContractBlock(); return stream; } internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { int numRead = Read(buffer, offset, count); asyncResult = new SynchronousAsyncResult(numRead, state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static int BlockingEndRead(IAsyncResult asyncResult) { Contract.Ensures(Contract.Result<int>() >= 0); return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating ---- // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { Write(buffer, offset, count); asyncResult = new SynchronousAsyncResult(state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static void BlockingEndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult.EndWrite(asyncResult); } [Serializable] private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) __Error.ReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanWrite) __Error.WriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } public override int Read([In, Out] byte[] buffer, int offset, int count) { return 0; } public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary> internal sealed class SynchronousAsyncResult : IAsyncResult { private readonly Object _stateObject; private readonly bool _isWrite; //private ManualResetEvent _waitHandle; private Exception _exceptionInfo; private bool _endXxxCalled; private Int32 _bytesRead; internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) { _bytesRead = bytesRead; _stateObject = asyncStateObject; //_isWrite = false; } internal SynchronousAsyncResult(Object asyncStateObject) { _stateObject = asyncStateObject; _isWrite = true; } internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) { _exceptionInfo = ex; _stateObject = asyncStateObject; _isWrite = isWrite; } public bool IsCompleted { // We never hand out objects of this type to the user before the synchronous IO completed: get { return true; } } /*public WaitHandle AsyncWaitHandle { get { return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); } }*/ public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal void ThrowIfError() { if (_exceptionInfo != null) throw _exceptionInfo; } internal static Int32 EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndReadCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); return ar._bytesRead; } internal static void EndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || !ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndWriteCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); } } // class SynchronousAsyncResult } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, 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. // namespace NLog.Common { using JetBrains.Annotations; using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using NLog.Internal; using NLog.Time; /// <summary> /// NLog internal logger. /// /// Writes to file, console or custom textwriter (see <see cref="InternalLogger.LogWriter"/>) /// </summary> /// <remarks> /// Don't use <see cref="ExceptionHelper.MustBeRethrown"/> as that can lead to recursive calls - stackoverflows /// </remarks> public static partial class InternalLogger { private static readonly object LockObject = new object(); private static string _logFile; /// <summary> /// Initializes static members of the InternalLogger class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")] static InternalLogger() { Reset(); } /// <summary> /// Set the config of the InternalLogger with defaults and config. /// </summary> public static void Reset() { // TODO: Extract class - InternalLoggerConfigurationReader #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false); LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false); LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Info); LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty); LogToTrace = GetSetting("nlog.internalLogToTrace", "NLOG_INTERNAL_LOG_TO_TRACE", false); IncludeTimestamp = GetSetting("nlog.internalLogIncludeTimestamp", "NLOG_INTERNAL_INCLUDE_TIMESTAMP", true); Info("NLog internal logger initialized."); #else LogLevel = LogLevel.Info; LogToConsole = false; LogToConsoleError = false; LogFile = string.Empty; IncludeTimestamp = true; #endif ExceptionThrowWhenWriting = false; LogWriter = null; } /// <summary> /// Gets or sets the minimal internal log level. /// </summary> /// <example>If set to <see cref="NLog.LogLevel.Info"/>, then messages of the levels <see cref="NLog.LogLevel.Info"/>, <see cref="NLog.LogLevel.Error"/> and <see cref="NLog.LogLevel.Fatal"/> will be written.</example> public static LogLevel LogLevel { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console output stream. /// </summary> /// <remarks>Your application must be a console application.</remarks> public static bool LogToConsole { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console error stream. /// </summary> /// <remarks>Your application must be a console application.</remarks> public static bool LogToConsoleError { get; set; } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the <see cref="System.Diagnostics"/>.Trace /// </summary> public static bool LogToTrace { get; set; } #endif /// <summary> /// Gets or sets the file path of the internal log file. /// </summary> /// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks> public static string LogFile { get { return _logFile; } set { _logFile = value; #if !SILVERLIGHT if (!string.IsNullOrEmpty(_logFile)) { CreateDirectoriesIfNeeded(_logFile); } #endif } } /// <summary> /// Gets or sets the text writer that will receive internal logs. /// </summary> public static TextWriter LogWriter { get; set; } /// <summary> /// Gets or sets a value indicating whether timestamp should be included in internal log output. /// </summary> public static bool IncludeTimestamp { get; set; } /// <summary> /// Is there an <see cref="Exception"/> thrown when writing the message? /// </summary> internal static bool ExceptionThrowWhenWriting { get; private set; } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Log(LogLevel level, [Localizable(false)] string message, params object[] args) { Write(null, level, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Log message.</param> public static void Log(LogLevel level, [Localizable(false)] string message) { Write(null, level, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>. /// </summary> /// <param name="level">Log level.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Log(LogLevel level, [Localizable(false)] Func<string> messageFunc) { if (level >= LogLevel) { Write(null, level, messageFunc(), null); } } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="messageFunc">Function that returns the log message.</param> [StringFormatMethod("message")] public static void Log(Exception ex, LogLevel level, [Localizable(false)] Func<string> messageFunc) { if (level >= LogLevel) { Write(ex, level, messageFunc(), null); } } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message, params object[] args) { Write(ex, level, message, args); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="message">Log message.</param> public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message) { Write(ex, level, message, null); } /// <summary> /// Write to internallogger. /// </summary> /// <param name="ex">optional exception to be logged.</param> /// <param name="level">level</param> /// <param name="message">message</param> /// <param name="args">optional args for <paramref name="message"/></param> private static void Write([CanBeNull]Exception ex, LogLevel level, string message, [CanBeNull]object[] args) { if (IsSeriousException(ex)) { //no logging! return; } if (!IsLoggingEnabled(level)) { return; } try { string msg = FormatMessage(ex, level, message, args); WriteToLogFile(msg); WriteToTextWriter(msg); #if !NETSTANDARD1_3 WriteToConsole(msg); WriteToErrorConsole(msg); #endif #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 WriteToTrace(msg); #endif } catch (Exception exception) { ExceptionThrowWhenWriting = true; // no log looping. // we have no place to log the message to so we ignore it if (exception.MustBeRethrownImmediately()) { throw; } } } private static string FormatMessage([CanBeNull]Exception ex, LogLevel level, string message, [CanBeNull]object[] args) { const string TimeStampFormat = "yyyy-MM-dd HH:mm:ss.ffff"; const string FieldSeparator = " "; var formattedMessage = (args == null) ? message : string.Format(CultureInfo.InvariantCulture, message, args); var builder = new StringBuilder(formattedMessage.Length + TimeStampFormat.Length + (ex?.ToString()?.Length ?? 0) + 25); if (IncludeTimestamp) { builder .Append(TimeSource.Current.Time.ToString(TimeStampFormat, CultureInfo.InvariantCulture)) .Append(FieldSeparator); } builder .Append(level) .Append(FieldSeparator) .Append(formattedMessage); if (ex != null) { ex.MarkAsLoggedToInternalLogger(); builder .Append(FieldSeparator) .Append("Exception: ") .Append(ex); } return builder.ToString(); } /// <summary> /// Determine if logging should be avoided because of exception type. /// </summary> /// <param name="exception">The exception to check.</param> /// <returns><c>true</c> if logging should be avoided; otherwise, <c>false</c>.</returns> private static bool IsSeriousException(Exception exception) { return exception != null && exception.MustBeRethrownImmediately(); } /// <summary> /// Determine if logging is enabled. /// </summary> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param> /// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns> private static bool IsLoggingEnabled(LogLevel logLevel) { if (logLevel == LogLevel.Off || logLevel < LogLevel) { return false; } return !string.IsNullOrEmpty(LogFile) || LogToConsole || LogToConsoleError || #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ LogToTrace || #endif LogWriter != null; } /// <summary> /// Write internal messages to the log file defined in <see cref="LogFile"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogFile"/> is not <c>null</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToLogFile(string message) { var logFile = LogFile; if (string.IsNullOrEmpty(logFile)) { return; } lock (LockObject) { using (var textWriter = File.AppendText(logFile)) { textWriter.WriteLine(message); } } } /// <summary> /// Write internal messages to the <see cref="System.IO.TextWriter"/> defined in <see cref="LogWriter"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogWriter"/> is not <c>null</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToTextWriter(string message) { var writer = LogWriter; if (writer == null) { return; } lock (LockObject) { writer.WriteLine(message); } } #if !NETSTANDARD1_3 /// <summary> /// Write internal messages to the <see cref="System.Console"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogToConsole"/> is <c>true</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToConsole(string message) { if (!LogToConsole) { return; } lock (LockObject) { Console.WriteLine(message); } } #endif #if !NETSTANDARD1_3 /// <summary> /// Write internal messages to the <see cref="System.Console.Error"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged when the property <see cref="LogToConsoleError"/> is <c>true</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToErrorConsole(string message) { if (!LogToConsoleError) { return; } lock (LockObject) { Console.Error.WriteLine(message); } } #endif #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 /// <summary> /// Write internal messages to the <see cref="System.Diagnostics.Trace"/>. /// </summary> /// <param name="message">A message to write.</param> /// <remarks> /// Works when property <see cref="LogToTrace"/> set to true. /// The <see cref="System.Diagnostics.Trace"/> is used in Debug and Relese configuration. /// The <see cref="System.Diagnostics.Debug"/> works only in Debug configuration and this is reason why is replaced by <see cref="System.Diagnostics.Trace"/>. /// in DEBUG /// </remarks> private static void WriteToTrace(string message) { if (!LogToTrace) { return; } System.Diagnostics.Trace.WriteLine(message, "NLog"); } #endif /// <summary> /// Logs the assembly version and file version of the given Assembly. /// </summary> /// <param name="assembly">The assembly to log.</param> public static void LogAssemblyVersion(Assembly assembly) { try { #if SILVERLIGHT || __IOS__ || __ANDROID__ || NETSTANDARD1_0 Info(assembly.FullName); #else var fileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location); Info("{0}. File version: {1}. Product version: {2}.", assembly.FullName, fileVersionInfo.FileVersion, fileVersionInfo.ProductVersion); #endif } catch (Exception ex) { Error(ex, "Error logging version of assembly {0}.", assembly.FullName); } } private static string GetAppSettings(string configName) { #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD try { return System.Configuration.ConfigurationManager.AppSettings[configName]; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } #endif return null; } private static string GetSettingString(string configName, string envName) { try { string settingValue = GetAppSettings(configName); if (settingValue != null) return settingValue; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } try { string settingValue = EnvironmentHelper.GetSafeEnvironmentVariable(envName); if (!string.IsNullOrEmpty(settingValue)) return settingValue; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } return null; } private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue) { string value = GetSettingString(configName, envName); if (value == null) { return defaultValue; } try { return LogLevel.FromString(value); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } private static T GetSetting<T>(string configName, string envName, T defaultValue) { string value = GetSettingString(configName, envName); if (value == null) { return defaultValue; } try { return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } #if !SILVERLIGHT private static void CreateDirectoriesIfNeeded(string filename) { try { if (LogLevel == LogLevel.Off) { return; } string parentDirectory = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(parentDirectory)) { Directory.CreateDirectory(parentDirectory); } } catch (Exception exception) { Error(exception, "Cannot create needed directories to '{0}'.", filename); if (exception.MustBeRethrownImmediately()) { throw; } } } #endif } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Lounge.Components { public class DrawableRoom : OsuClickableContainer, IStateful<SelectionState>, IFilterable { public const float SELECTION_BORDER_WIDTH = 4; private const float corner_radius = 5; private const float transition_duration = 60; private const float content_padding = 10; private const float height = 110; private const float side_strip_width = 5; private const float cover_width = 145; public event Action<SelectionState> StateChanged; private readonly Box selectionBox; private CachedModelDependencyContainer<Room> dependencies; [Resolved] private BeatmapManager beatmaps { get; set; } public readonly Room Room; private SelectionState state; public SelectionState State { get => state; set { if (value == state) return; state = value; if (state == SelectionState.Selected) selectionBox.FadeIn(transition_duration); else selectionBox.FadeOut(transition_duration); StateChanged?.Invoke(State); } } public IEnumerable<string> FilterTerms => new[] { Room.Name.Value }; private bool matchingFilter; public bool MatchingFilter { get => matchingFilter; set { matchingFilter = value; this.FadeTo(MatchingFilter ? 1 : 0, 200); } } public DrawableRoom(Room room) { Room = room; RelativeSizeAxes = Axes.X; Height = height + SELECTION_BORDER_WIDTH * 2; CornerRadius = corner_radius + SELECTION_BORDER_WIDTH / 2; Masking = true; // create selectionBox here so State can be set before being loaded selectionBox = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0f, }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Both, Child = selectionBox }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(SELECTION_BORDER_WIDTH), Child = new Container { RelativeSizeAxes = Axes.Both, Masking = true, CornerRadius = corner_radius, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.FromHex(@"212121"), }, new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Y, Width = side_strip_width, Child = new Box { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Y, Width = cover_width, Masking = true, Margin = new MarginPadding { Left = side_strip_width }, Child = new MultiplayerBackgroundSprite { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Vertical = content_padding, Left = side_strip_width + cover_width + content_padding, Right = content_padding, }, Children = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Children = new Drawable[] { new RoomName { Font = OsuFont.GetFont(size: 18) }, new ParticipantInfo(), }, }, new FillFlowContainer { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 5), Children = new Drawable[] { new RoomStatusInfo(), new BeatmapTitle { TextSize = 14 }, }, }, new ModeTypeInfo { Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, }, }, }, }, }, }, }; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent)); dependencies.Model.Value = Room; return dependencies; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(transition_duration); } private class RoomName : OsuSpriteText { [Resolved(typeof(Room), nameof(Online.Multiplayer.Room.Name))] private Bindable<string> name { get; set; } [BackgroundDependencyLoader] private void load() { Current = name; } } } }
/* **************************************************************************** * * 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 * dlr@microsoft.com. 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_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Types; using IronPython.Runtime.Binding; namespace IronPython.Runtime.Operations { // These operations get linked into all new-style classes. public static class UserTypeOps { public static string ToStringReturnHelper(object o) { if (o is string && o != null) { return (string)o; } throw PythonOps.TypeError("__str__ returned non-string type ({0})", PythonTypeOps.GetName(o)); } public static PythonDictionary SetDictHelper(ref PythonDictionary dict, PythonDictionary value) { if (System.Threading.Interlocked.CompareExchange<PythonDictionary>(ref dict, value, null) == null) return value; return dict; } public static object GetPropertyHelper(object prop, object instance, string name) { PythonTypeSlot desc = prop as PythonTypeSlot; if (desc == null) { throw PythonOps.TypeError("Expected property for {0}, but found {1}", name.ToString(), DynamicHelpers.GetPythonType(prop).Name); } object value; desc.TryGetValue(DefaultContext.Default, instance, DynamicHelpers.GetPythonType(instance), out value); return value; } public static void SetPropertyHelper(object prop, object instance, object newValue, string name) { PythonTypeSlot desc = prop as PythonTypeSlot; if (desc == null) { throw PythonOps.TypeError("Expected settable property for {0}, but found {1}", name.ToString(), DynamicHelpers.GetPythonType(prop).Name); } desc.TrySetValue(DefaultContext.Default, instance, DynamicHelpers.GetPythonType(instance), newValue); } public static bool SetWeakRefHelper(IPythonObject obj, WeakRefTracker value) { if (!obj.PythonType.IsWeakReferencable) { return false; } object[] slots = obj.GetSlotsCreate(); slots[slots.Length - 1] = value; return true; } public static WeakRefTracker GetWeakRefHelper(IPythonObject obj) { object[] slots = obj.GetSlots(); if (slots == null) { return null; } return (WeakRefTracker)slots[slots.Length - 1]; } public static void SetFinalizerHelper(IPythonObject obj, WeakRefTracker value) { object[] slots = obj.GetSlotsCreate(); if (Interlocked.CompareExchange(ref slots[slots.Length - 1], value, null) != null) { GC.SuppressFinalize(value); } } public static object[] GetSlotsCreate(IPythonObject obj, ref object[] slots) { if (slots != null) { return slots; } Interlocked.CompareExchange( ref slots, new object[obj.PythonType.SlotCount + 1], // weakref is stored at the end null); return slots; } public static void AddRemoveEventHelper(object method, IPythonObject instance, object eventValue, string name) { object callable = method; // TODO: dt gives us a PythonContext which we should use PythonType dt = instance.PythonType; PythonTypeSlot dts = method as PythonTypeSlot; if (dts != null) { if (!dts.TryGetValue(DefaultContext.Default, instance, dt, out callable)) throw PythonOps.AttributeErrorForMissingAttribute(dt.Name, name); } if (!PythonOps.IsCallable(DefaultContext.Default, callable)) { throw PythonOps.TypeError("Expected callable value for {0}, but found {1}", name.ToString(), PythonTypeOps.GetName(method)); } PythonCalls.Call(callable, eventValue); } public static DynamicMetaObject/*!*/ GetMetaObjectHelper(IPythonObject self, Expression/*!*/ parameter, DynamicMetaObject baseMetaObject) { return new Binding.MetaUserObject(parameter, BindingRestrictions.Empty, baseMetaObject, self); } public static bool TryGetMixedNewStyleOldStyleSlot(CodeContext context, object instance, string name, out object value) { IPythonObject sdo = instance as IPythonObject; if (sdo != null) { PythonDictionary dict = sdo.Dict; if (dict != null && dict.TryGetValue(name, out value)) { return true; } } PythonType dt = DynamicHelpers.GetPythonType(instance); foreach (PythonType type in dt.ResolutionOrder) { PythonTypeSlot dts; if (type.TryLookupSlot(context, name, out dts)) { // we're a dynamic type, check the dynamic type way return dts.TryGetValue(context, instance, dt, out value); } } value = null; return false; } public static bool TryGetDictionaryValue(PythonDictionary dict, string name, int keyVersion, int keyIndex, out object res) { CustomInstanceDictionaryStorage dictStorage; if (dict != null) { if ((dictStorage = dict._storage as CustomInstanceDictionaryStorage) != null && dictStorage.KeyVersion == keyVersion) { if (dictStorage.TryGetValue(keyIndex, out res)) { return true; } } else if (dict.TryGetValue(name, out res)) { return true; } } res = null; return false; } public static object SetDictionaryValue(IPythonObject self, string name, object value) { PythonDictionary dict = GetDictionary(self); return dict[name] = value; } public static object SetDictionaryValueOptimized(IPythonObject ipo, string name, object value, int keysVersion, int index) { var dict = UserTypeOps.GetDictionary(ipo); CustomInstanceDictionaryStorage storage; if ((storage = dict._storage as CustomInstanceDictionaryStorage) != null && storage.KeyVersion == keysVersion) { storage.SetExtraValue(index, value); } else { dict[name] = value; } return value; } public static object FastSetDictionaryValue(ref PythonDictionary dict, string name, object value) { if (dict == null) { Interlocked.CompareExchange(ref dict, PythonDictionary.MakeSymbolDictionary(), null); } return dict[name] = value; } public static object FastSetDictionaryValueOptimized(PythonType type, ref PythonDictionary dict, string name, object value, int keysVersion, int index) { if (dict == null) { Interlocked.CompareExchange(ref dict, type.MakeDictionary(), null); } CustomInstanceDictionaryStorage storage; if ((storage = dict._storage as CustomInstanceDictionaryStorage) != null && storage.KeyVersion == keysVersion) { storage.SetExtraValue(index, value); return value; } else { return dict[name] = value; } } public static object RemoveDictionaryValue(IPythonObject self, string name) { PythonDictionary dict = self.Dict; if (dict != null) { if (dict.Remove(name)) { return null; } } throw PythonOps.AttributeErrorForMissingAttribute(self.PythonType, name); } internal static PythonDictionary GetDictionary(IPythonObject self) { PythonDictionary dict = self.Dict; if (dict == null && self.PythonType.HasDictionary) { dict = self.SetDict(self.PythonType.MakeDictionary()); } return dict; } /// <summary> /// Object.ToString() displays the CLI type name. But we want to display the class name (e.g. /// '&lt;foo object at 0x000000000000002C&gt;' unless we've overridden __repr__ but not __str__ in /// which case we'll display the result of __repr__. /// </summary> public static string ToStringHelper(IPythonObject o) { return ObjectOps.__str__(DefaultContext.Default, o); } public static bool TryGetNonInheritedMethodHelper(PythonType dt, object instance, string name, out object callTarget) { // search MRO for other user-types in the chain that are overriding the method foreach (PythonType type in dt.ResolutionOrder) { if (type.IsSystemType) break; // hit the .NET types, we're done if (LookupValue(type, instance, name, out callTarget)) { return true; } } // check instance IPythonObject isdo = instance as IPythonObject; PythonDictionary dict; if (isdo != null && (dict = isdo.Dict) != null) { if (dict.TryGetValue(name, out callTarget)) return true; } callTarget = null; return false; } private static bool LookupValue(PythonType dt, object instance, string name, out object value) { PythonTypeSlot dts; if (dt.TryLookupSlot(DefaultContext.Default, name, out dts) && dts.TryGetValue(DefaultContext.Default, instance, dt, out value)) { return true; } value = null; return false; } public static bool TryGetNonInheritedValueHelper(IPythonObject instance, string name, out object callTarget) { PythonType dt = instance.PythonType; PythonTypeSlot dts; // search MRO for other user-types in the chain that are overriding the method foreach (PythonType type in dt.ResolutionOrder) { if (type.IsSystemType) break; // hit the .NET types, we're done if (type.TryLookupSlot(DefaultContext.Default, name, out dts)) { callTarget = dts; return true; } } // check instance IPythonObject isdo = instance as IPythonObject; PythonDictionary dict; if (isdo != null && (dict = isdo.Dict) != null) { if (dict.TryGetValue(name, out callTarget)) return true; } callTarget = null; return false; } public static object GetAttribute(CodeContext/*!*/ context, object self, string name, PythonTypeSlot getAttributeSlot, PythonTypeSlot getAttrSlot, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>/*!*/ callSite) { object value; if (callSite.Data == null) { callSite.Data = MakeGetAttrSite(context); } try { if (getAttributeSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } } catch (MissingMemberException) { if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } throw; } if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } throw PythonOps.AttributeError(name); } public static object GetAttributeNoThrow(CodeContext/*!*/ context, object self, string name, PythonTypeSlot getAttributeSlot, PythonTypeSlot getAttrSlot, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>/*!*/ callSite) { object value; if (callSite.Data == null) { callSite.Data = MakeGetAttrSite(context); } try { if (getAttributeSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } } catch (MissingMemberException) { try { if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } return OperationFailed.Value; } catch (MissingMemberException) { return OperationFailed.Value; } } try { if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) { return callSite.Data.Target(callSite.Data, context, value, name); } } catch (MissingMemberException) { } return OperationFailed.Value; } private static CallSite<Func<CallSite, CodeContext, object, string, object>> MakeGetAttrSite(CodeContext context) { return CallSite<Func<CallSite, CodeContext, object, string, object>>.Create( PythonContext.GetContext(context).InvokeOne ); } #region IValueEquality Helpers #if CLR2 public static int GetValueHashCodeHelper(object self) { // new-style classes only lookup in slots, not in instance // members object func; if (DynamicHelpers.GetPythonType(self).TryGetBoundMember(DefaultContext.Default, self, "__hash__", out func)) { return Converter.ConvertToInt32(PythonCalls.Call(func)); } return self.GetHashCode(); } public static bool ValueEqualsHelper(object self, object other) { object res = RichEqualsHelper(self, other); if (res != NotImplementedType.Value && res != null && res.GetType() == typeof(bool)) return (bool)res; return false; } private static object RichEqualsHelper(object self, object other) { object res; if (PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, self, other, "__eq__", out res)) return res; return NotImplementedType.Value; } #endif #endregion internal static Binding.FastBindResult<T> MakeGetBinding<T>(CodeContext codeContext, CallSite<T> site, IPythonObject self, Binding.PythonGetMemberBinder getBinder) where T : class { Type finalType = self.PythonType.FinalSystemType; if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType) && !(self is IFastGettable)) { // very tricky, user is inheriting from a class which implements IDO, we // don't optimize this yet. return new Binding.FastBindResult<T>(); } return (Binding.FastBindResult<T>)(object)new Binding.MetaUserObject.FastGetBinderHelper( codeContext, (CallSite<Func<CallSite, object, CodeContext, object>>)(object)site, self, getBinder).GetBinding(codeContext, getBinder.Name); } internal static FastBindResult<T> MakeSetBinding<T>(CodeContext codeContext, CallSite<T> site, IPythonObject self, object value, Binding.PythonSetMemberBinder setBinder) where T : class { if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(self.GetType().BaseType)) { // very tricky, user is inheriting from a class which implements IDO, we // don't optimize this yet. return new FastBindResult<T>(); } // optimized versions for possible literals that can show up in code. Type setType = typeof(T); if (setType == typeof(Func<CallSite, object, object, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<object>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, string, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<string>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, int, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<int>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, double, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<double>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, List, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<List>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, PythonTuple, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<PythonTuple>( codeContext, self, value, setBinder).MakeSet(); } else if (setType == typeof(Func<CallSite, object, PythonDictionary, object>)) { return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<PythonDictionary>( codeContext, self, value, setBinder).MakeSet(); } return new FastBindResult<T>(); } } /// <summary> /// Provides a debug view for user defined types. This class is declared as public /// because it is referred to from generated code. You should not use this class. /// </summary> public class UserTypeDebugView { private readonly IPythonObject _userObject; public UserTypeDebugView(IPythonObject userObject) { _userObject = userObject; } public PythonType __class__ { get { return _userObject.PythonType; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); if (_userObject.Dict != null) { foreach (var v in _userObject.Dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } } // collect any slots on the object object[] slots = _userObject.GetSlots(); if (slots != null) { var mro = _userObject.PythonType.ResolutionOrder; List<string> slotNames = new List<string>(); for(int i = mro.Count - 1; i>= 0; i--) { slotNames.AddRange(mro[i].GetTypeSlots()); } for (int i = 0; i < slots.Length - 1; i++) { if (slots[i] != Uninitialized.Instance) { res.Add(new ObjectDebugView(slotNames[i], slots[i])); } } } return res; } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using NServiceBus; namespace System.Quality { /// <summary> /// INServiceBus /// </summary> public interface INServiceBus : IPublishingServiceBus { void Reply<TMessage>(Action<TMessage> messageBuilder) where TMessage : IServiceMessage; void Reply(params IServiceMessage[] messages); void Return<T>(T value); IBus Bus { get; } } /// <summary> /// NServiceBusAbstractor /// </summary> public class NServiceBusAbstractor : INServiceBus { private static readonly Type s_domainServiceMessageType = typeof(INServiceMessage); public NServiceBusAbstractor() : this(GetCurrentBus()) { } public NServiceBusAbstractor(IBus bus) { if (bus == null) throw new ArgumentNullException("bus", "The specified NServiceBus bus cannot be null."); Bus = bus; } public static IBus GetCurrentBus() { var bus = Configure.Instance.Builder.Build<IBus>(); if (bus == null) throw new InvalidOperationException("Need to start bus first"); return bus; } public TMessage MakeMessage<TMessage>() where TMessage : IServiceMessage, new() { return MessageCaster<TMessage>.MakeMessage(); } public void SendSelf<TMessage>(Action<TMessage> messageBuilder) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { var mb = (messageBuilder as Action<IMessage>); if (mb != null) Bus.SendLocal(mb); else MessageCaster<TMessage>.SendLocal(Bus, messageBuilder); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void SendSelf(params IServiceMessage[] messages) { try { Bus.SendLocal(MessageCaster.Cast(messages)); } catch (Exception ex) { throw new ServiceBusException(ex); } } public IServiceBusCallback SendTo<TMessage>(string destination, Action<TMessage> messageBuilder) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { if (destination == null) { var mb = (messageBuilder as Action<IMessage>); return (mb != null ? MessageCaster.Cast(Bus.Send(mb)) : MessageCaster<TMessage>.Send(Bus, messageBuilder)); } var mb2 = (messageBuilder as Action<IMessage>); return (mb2 != null ? MessageCaster.Cast(Bus.Send(destination, mb2)) : MessageCaster<TMessage>.Send(Bus, destination, messageBuilder)); } catch (Exception ex) { throw new ServiceBusException(ex); } } public IServiceBusCallback SendTo(string destination, params IServiceMessage[] messages) { try { if (destination == null) return MessageCaster.Cast(Bus.Send(MessageCaster.Cast(messages))); return MessageCaster.Cast(Bus.Send(destination, MessageCaster.Cast(messages))); } catch (Exception ex) { throw new ServiceBusException(ex); } } #region Publishing ServiceBus public void Publish<TMessage>(Action<TMessage> messageBuilder) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Publish(Bus, messageBuilder); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Publish<TMessage>(params TMessage[] messages) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Publish(Bus, messages); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Subscribe<TMessage>() where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Subscribe(Bus); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Subscribe<TMessage>(Predicate<TMessage> condition) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Subscribe(Bus, condition); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Subscribe(Type messageType) { try { Bus.Subscribe(MessageCaster.Cast(messageType)); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Subscribe(Type messageType, Predicate<IServiceMessage> condition) { try { Bus.Subscribe(MessageCaster.Cast(messageType), MessageCaster.Cast(condition)); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Unsubscribe<TMessage>() where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Unsubscribe(Bus); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Unsubscribe(Type messageType) { try { Bus.Unsubscribe(MessageCaster.Cast(messageType)); } catch (Exception ex) { throw new ServiceBusException(ex); } } #endregion #region Domain-specific public IBus Bus { get; private set; } public void Reply<TMessage>(Action<TMessage> messageBuilder) where TMessage : IServiceMessage { if (!typeof(TMessage).IsAssignableFrom(s_domainServiceMessageType)) throw new ArgumentException("TMessage"); try { MessageCaster<TMessage>.Reply(Bus, messageBuilder); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Reply(params IServiceMessage[] messages) { try { Bus.Reply(MessageCaster.Cast(messages)); } catch (Exception ex) { throw new ServiceBusException(ex); } } public void Return<T>(T value) { if (typeof(T) != typeof(int)) throw new NotSupportedException(); try { Bus.Return(Convert.ToInt32(value)); } catch (Exception ex) { throw new ServiceBusException(ex); } } #endregion } }
using UnityEngine; using System.Collections; using System; namespace RootMotion.FinalIK { /// <summary> /// Analytic %IK solver based on the Law of Cosines. /// </summary> [System.Serializable] public class IKSolverTrigonometric: IKSolver { #region Main Interface /// <summary> /// The target Transform. /// </summary> public Transform target; /// <summary> /// The %IK rotation weight (rotation of the last bone). /// </summary> [Range(0f, 1f)] public float IKRotationWeight = 1f; /// <summary> /// The %IK rotation target. /// </summary> public Quaternion IKRotation = Quaternion.identity; /// <summary> /// The bend plane normal. /// </summary> public Vector3 bendNormal = Vector3.right; /// <summary> /// The first bone (upper arm or thigh). /// </summary> public TrigonometricBone bone1 = new TrigonometricBone(); /// <summary> /// The second bone (forearm or calf). /// </summary> public TrigonometricBone bone2 = new TrigonometricBone(); /// <summary> /// The third bone (hand or foot). /// </summary> public TrigonometricBone bone3 = new TrigonometricBone(); /// <summary> /// Sets the bend goal position. /// </summary> /// <param name='goalPosition'> /// Goal position. /// </param> public void SetBendGoalPosition(Vector3 goalPosition, float weight) { if (!initiated) return; if (weight <= 0f) return; Vector3 normal = Vector3.Cross(goalPosition - bone1.transform.position, IKPosition - bone1.transform.position); if (normal != Vector3.zero) { if (weight >= 1f) { bendNormal = normal; return; } bendNormal = Vector3.Lerp(bendNormal, normal, weight); } } /// <summary> /// Sets the bend plane to match current bone rotations. /// </summary> public void SetBendPlaneToCurrent() { if (!initiated) return; Vector3 normal = Vector3.Cross(bone2.transform.position - bone1.transform.position, bone3.transform.position - bone2.transform.position); if (normal != Vector3.zero) bendNormal = normal; } /// <summary> /// Sets the %IK rotation. /// </summary> public void SetIKRotation(Quaternion rotation) { IKRotation = rotation; } /// <summary> /// Sets the %IK rotation weight. /// </summary> public void SetIKRotationWeight(float weight) { IKRotationWeight = Mathf.Clamp(weight, 0f, 1f); } /// <summary> /// Gets the %IK rotation. /// </summary> public Quaternion GetIKRotation() { return IKRotation; } /// <summary> /// Gets the %IK rotation weight. /// </summary> public float GetIKRotationWeight() { return IKRotationWeight; } public override IKSolver.Point[] GetPoints() { return new IKSolver.Point[3] { (IKSolver.Point)bone1, (IKSolver.Point)bone2, (IKSolver.Point)bone3 }; } public override IKSolver.Point GetPoint(Transform transform) { if (bone1.transform == transform) return (IKSolver.Point)bone1; if (bone2.transform == transform) return (IKSolver.Point)bone2; if (bone3.transform == transform) return (IKSolver.Point)bone3; return null; } public override void StoreDefaultLocalState() { bone1.StoreDefaultLocalState(); bone2.StoreDefaultLocalState(); bone3.StoreDefaultLocalState(); } public override void FixTransforms() { bone1.FixTransform(); bone2.FixTransform(); bone3.FixTransform(); } public override bool IsValid(ref string message) { if (bone1.transform == null || bone2.transform == null || bone3.transform == null) { message = "Please assign all Bones to the IK solver."; return false; } Transform duplicate = (Transform)Hierarchy.ContainsDuplicate(new Transform[3] { bone1.transform, bone2.transform, bone3.transform }); if (duplicate != null) { message = duplicate.name + " is represented multiple times in the Bones."; return false; } if (bone1.transform.position == bone2.transform.position) { message = "first bone position is the same as second bone position."; return false; } if (bone2.transform.position == bone3.transform.position) { message = "second bone position is the same as third bone position."; return false; } return true; } /// <summary> /// Bone type used by IKSolverTrigonometric. /// </summary> [System.Serializable] public class TrigonometricBone: IKSolver.Bone { private Quaternion targetToLocalSpace; private Vector3 defaultLocalBendNormal; #region Public methods /* * Initiates the bone, precalculates values. * */ public void Initiate(Vector3 childPosition, Vector3 bendNormal) { // Get default target rotation that looks at child position with bendNormal as up Quaternion defaultTargetRotation = Quaternion.LookRotation(childPosition - transform.position, bendNormal); // Covert default target rotation to local space targetToLocalSpace = QuaTools.RotationToLocalSpace(transform.rotation, defaultTargetRotation); defaultLocalBendNormal = Quaternion.Inverse(transform.rotation) * bendNormal; } /* * Calculates the rotation of this bone to targetPosition. * */ public Quaternion GetRotation(Vector3 direction, Vector3 bendNormal) { return Quaternion.LookRotation(direction, bendNormal) * targetToLocalSpace; } /* * Gets the bend normal from current bone rotation. * */ public Vector3 GetBendNormalFromCurrentRotation() { return transform.rotation * defaultLocalBendNormal; } #endregion Public methods } /// <summary> /// Reinitiate the solver with new bone Transforms. /// </summary> /// <returns> /// Returns true if the new chain is valid. /// </returns> public bool SetChain(Transform bone1, Transform bone2, Transform bone3, Transform root) { this.bone1.transform = bone1; this.bone2.transform = bone2; this.bone3.transform = bone3; Initiate(root); return initiated; } #endregion Main Interface #region Class Methods /// <summary> /// Solve the bone chain. /// </summary> public static void Solve(Transform bone1, Transform bone2, Transform bone3, Vector3 targetPosition, Vector3 bendNormal, float weight) { if (weight <= 0f) return; // Direction of the limb in solver targetPosition = Vector3.Lerp(bone3.position, targetPosition, weight); Vector3 dir = targetPosition - bone1.position; // Distance between the first and the last node solver positions float length = dir.magnitude; if (length == 0f) return; float sqrMag1 = (bone2.position - bone1.position).sqrMagnitude; float sqrMag2 = (bone3.position - bone2.position).sqrMagnitude; // Get the general world space bending direction Vector3 bendDir = Vector3.Cross(dir, bendNormal); // Get the direction to the trigonometrically solved position of the second node Vector3 toBendPoint = GetDirectionToBendPoint(dir, length, bendDir, sqrMag1, sqrMag2); // Position the second node Quaternion q1 = Quaternion.FromToRotation(bone2.position - bone1.position, toBendPoint); if (weight < 1f) q1 = Quaternion.Lerp(Quaternion.identity, q1, weight); bone1.rotation = q1 * bone1.rotation; Quaternion q2 = Quaternion.FromToRotation(bone3.position - bone2.position, targetPosition - bone2.position); if (weight < 1f) q2 = Quaternion.Lerp(Quaternion.identity, q2, weight); bone2.rotation = q2 * bone2.rotation; } //Calculates the bend direction based on the law of cosines. NB! Magnitude of the returned vector does not equal to the length of the first bone! private static Vector3 GetDirectionToBendPoint(Vector3 direction, float directionMag, Vector3 bendDirection, float sqrMag1, float sqrMag2) { float x = ((directionMag * directionMag) + (sqrMag1 - sqrMag2)) / 2f / directionMag; float y = (float)Math.Sqrt(Mathf.Clamp(sqrMag1 - x * x, 0, Mathf.Infinity)); if (direction == Vector3.zero) return Vector3.zero; return Quaternion.LookRotation(direction, bendDirection) * new Vector3(0f, y, x); } #endregion Class Methods protected override void OnInitiate() { if (bendNormal == Vector3.zero) bendNormal = Vector3.right; OnInitiateVirtual(); IKPosition = bone3.transform.position; IKRotation = bone3.transform.rotation; // Initiating bones InitiateBones(); directHierarchy = IsDirectHierarchy(); } // Are the bones parented directly to each other? private bool IsDirectHierarchy() { if (bone3.transform.parent != bone2.transform) return false; if (bone2.transform.parent != bone1.transform) return false; return true; } // Set the defaults for the bones private void InitiateBones() { bone1.Initiate(bone2.transform.position, bendNormal); bone2.Initiate(bone3.transform.position, bendNormal); SetBendPlaneToCurrent(); } protected override void OnUpdate() { IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f); IKRotationWeight = Mathf.Clamp(IKRotationWeight, 0f, 1f); if (target != null) { IKPosition = target.position; IKRotation = target.rotation; } OnUpdateVirtual(); if (IKPositionWeight > 0) { // Reinitiating the bones when the hierarchy is not direct. This allows for skipping animated bones in the hierarchy. if (!directHierarchy) { bone1.Initiate(bone2.transform.position, bendNormal); bone2.Initiate(bone3.transform.position, bendNormal); } // Find out if bone lengths should be updated bone1.sqrMag = (bone2.transform.position - bone1.transform.position).sqrMagnitude; bone2.sqrMag = (bone3.transform.position - bone2.transform.position).sqrMagnitude; if (bendNormal == Vector3.zero && !Warning.logged) LogWarning("IKSolverTrigonometric Bend Normal is Vector3.zero."); weightIKPosition = Vector3.Lerp(bone3.transform.position, IKPosition, IKPositionWeight); // Interpolating bend normal Vector3 currentBendNormal = Vector3.Lerp(bone1.GetBendNormalFromCurrentRotation(), bendNormal, IKPositionWeight); // Calculating and interpolating bend direction Vector3 bendDirection = Vector3.Lerp(bone2.transform.position - bone1.transform.position, GetBendDirection(weightIKPosition, currentBendNormal), IKPositionWeight); if (bendDirection == Vector3.zero) bendDirection = bone2.transform.position - bone1.transform.position; // Rotating bone1 bone1.transform.rotation = bone1.GetRotation(bendDirection, currentBendNormal); // Rotating bone 2 bone2.transform.rotation = bone2.GetRotation(weightIKPosition - bone2.transform.position, bone2.GetBendNormalFromCurrentRotation()); } // Rotating bone3 if (IKRotationWeight > 0) { bone3.transform.rotation = Quaternion.Slerp(bone3.transform.rotation, IKRotation, IKRotationWeight); } OnPostSolveVirtual(); } protected Vector3 weightIKPosition; protected virtual void OnInitiateVirtual() {} protected virtual void OnUpdateVirtual() {} protected virtual void OnPostSolveVirtual() {} protected bool directHierarchy = true; /* * Calculates the bend direction based on the Law of Cosines. * */ protected Vector3 GetBendDirection(Vector3 IKPosition, Vector3 bendNormal) { Vector3 direction = IKPosition - bone1.transform.position; if (direction == Vector3.zero) return Vector3.zero; float directionSqrMag = direction.sqrMagnitude; float directionMagnitude = (float)Math.Sqrt(directionSqrMag); float x = (directionSqrMag + bone1.sqrMag - bone2.sqrMag) / 2f / directionMagnitude; float y = (float)Math.Sqrt(Mathf.Clamp(bone1.sqrMag - x * x, 0, Mathf.Infinity)); Vector3 yDirection = Vector3.Cross(direction, bendNormal); return Quaternion.LookRotation(direction, yDirection) * new Vector3(0f, y, x); } } }
// // CFStream.cs: // // Authors: // Martin Baulig <martin.baulig@gmail.com> // Rolf Bjarne Kvinge <rolf@xamarin.com> // // Copyright (C) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using MonoMac.CoreServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreFoundation { [Flags] public enum CFStreamEventType { None = 0, OpenCompleted = 1, HasBytesAvailable = 2, CanAcceptBytes = 4, ErrorOccurred = 8, EndEncountered = 16 } [StructLayout (LayoutKind.Sequential)] public struct CFStreamClientContext { public int Version; public IntPtr Info; IntPtr retain; IntPtr release; IntPtr copyDescription; public void Retain () { if (retain == IntPtr.Zero || Info == IntPtr.Zero) return; CFReadStreamRef_InvokeRetain (retain, Info); } public void Release () { if (release == IntPtr.Zero || Info == IntPtr.Zero) return; CFReadStreamRef_InvokeRelease (release, Info); } public override string ToString () { if (copyDescription == IntPtr.Zero) return base.ToString (); var ptr = CFReadStreamRef_InvokeCopyDescription (copyDescription, Info); return ptr == IntPtr.Zero ? base.ToString () : new NSString (ptr).ToString (); } internal void Invoke (IntPtr callback, IntPtr stream, CFStreamEventType eventType) { if (callback == IntPtr.Zero) return; CFReadStreamRef_InvokeCallback (callback, stream, eventType, Info); } [MonoNativeFunctionWrapper] delegate IntPtr RetainDelegate (IntPtr info); static IntPtr CFReadStreamRef_InvokeRetain (IntPtr retain, IntPtr info) { return ((RetainDelegate)Marshal.GetDelegateForFunctionPointer (retain, typeof (RetainDelegate))) (info); } [MonoNativeFunctionWrapper] delegate void ReleaseDelegate (IntPtr info); static void CFReadStreamRef_InvokeRelease (IntPtr release, IntPtr info) { ((ReleaseDelegate)Marshal.GetDelegateForFunctionPointer (release, typeof (ReleaseDelegate))) (info); } [MonoNativeFunctionWrapper] delegate IntPtr CopyDescriptionDelegate (IntPtr info); static IntPtr CFReadStreamRef_InvokeCopyDescription (IntPtr copyDescription, IntPtr info) { return ((CopyDescriptionDelegate)Marshal.GetDelegateForFunctionPointer (copyDescription, typeof (CopyDescriptionDelegate))) (info); } [MonoNativeFunctionWrapper] delegate void CallbackDelegate (IntPtr stream, CFStreamEventType eventType, IntPtr info); static void CFReadStreamRef_InvokeCallback (IntPtr callback, IntPtr stream, CFStreamEventType eventType, IntPtr info) { ((CallbackDelegate)Marshal.GetDelegateForFunctionPointer (callback, typeof (CallbackDelegate))) (stream, eventType, info); } } public enum CFStreamStatus { NotOpen = 0, Opening, Open, Reading, Writing, AtEnd, Closed, Error } public abstract class CFStream : CFType, INativeObject, IDisposable { IntPtr handle; GCHandle gch; CFRunLoop loop; NSString loopMode; bool open, closed; #region Stream Constructors [DllImport (Constants.CoreFoundationLibrary)] extern static void CFStreamCreatePairWithSocket (IntPtr allocator, CFSocketNativeHandle socket, out IntPtr read, out IntPtr write); public static void CreatePairWithSocket (CFSocket socket, out CFReadStream readStream, out CFWriteStream writeStream) { IntPtr read, write; CFStreamCreatePairWithSocket (IntPtr.Zero, socket.GetNative (), out read, out write); readStream = new CFReadStream (read); writeStream = new CFWriteStream (write); } [DllImport (Constants.CFNetworkLibrary)] extern static void CFStreamCreatePairWithPeerSocketSignature (IntPtr allocator, ref CFSocketSignature sig, out IntPtr read, out IntPtr write); public static void CreatePairWithPeerSocketSignature (AddressFamily family, SocketType type, ProtocolType proto, IPEndPoint endpoint, out CFReadStream readStream, out CFWriteStream writeStream) { using (var address = new CFSocketAddress (endpoint)) { var sig = new CFSocketSignature (family, type, proto, address); IntPtr read, write; CFStreamCreatePairWithPeerSocketSignature (IntPtr.Zero, ref sig, out read, out write); readStream = new CFReadStream (read); writeStream = new CFWriteStream (write); } } [DllImport (Constants.CFNetworkLibrary)] extern static void CFStreamCreatePairWithSocketToCFHost (IntPtr allocator, IntPtr host, int port, out IntPtr read, out IntPtr write); public static void CreatePairWithSocketToHost (IPEndPoint endpoint, out CFReadStream readStream, out CFWriteStream writeStream) { using (var host = CFHost.Create (endpoint)) { IntPtr read, write; CFStreamCreatePairWithSocketToCFHost ( IntPtr.Zero, host.Handle, endpoint.Port, out read, out write); readStream = new CFReadStream (read); writeStream = new CFWriteStream (write); } } [DllImport (Constants.CFNetworkLibrary)] extern static void CFStreamCreatePairWithSocketToHost (IntPtr allocator, IntPtr host, int port, out IntPtr read, out IntPtr write); public static void CreatePairWithSocketToHost (string host, int port, out CFReadStream readStream, out CFWriteStream writeStream) { using (var str = new CFString (host)) { IntPtr read, write; CFStreamCreatePairWithSocketToHost ( IntPtr.Zero, str.Handle, port, out read, out write); readStream = new CFReadStream (read); writeStream = new CFWriteStream (write); } } [DllImport (Constants.CFNetworkLibrary)] extern static IntPtr CFReadStreamCreateForHTTPRequest (IntPtr alloc, IntPtr request); public static CFHTTPStream CreateForHTTPRequest (CFHTTPMessage request) { var handle = CFReadStreamCreateForHTTPRequest (IntPtr.Zero, request.Handle); if (handle == IntPtr.Zero) return null; return new CFHTTPStream (handle); } [DllImport (Constants.CFNetworkLibrary)] extern static IntPtr CFReadStreamCreateForStreamedHTTPRequest (IntPtr alloc, IntPtr request, IntPtr body); public static CFHTTPStream CreateForStreamedHTTPRequest (CFHTTPMessage request, CFReadStream body) { var handle = CFReadStreamCreateForStreamedHTTPRequest (IntPtr.Zero, request.Handle, body.Handle); if (handle == IntPtr.Zero) return null; return new CFHTTPStream (handle); } [DllImport (Constants.CFNetworkLibrary)] extern static void CFStreamCreateBoundPair (IntPtr alloc, out IntPtr readStream, out IntPtr writeStream, CFIndex transferBufferSize); public static void CreateBoundPair (out CFReadStream readStream, out CFWriteStream writeStream, int bufferSize) { IntPtr read, write; CFStreamCreateBoundPair (IntPtr.Zero, out read, out write, bufferSize); readStream = new CFReadStream (read); writeStream = new CFWriteStream (write); } #endregion #region Stream API public abstract CFException GetError (); protected void CheckError () { var exc = GetError (); if (exc != null) throw exc; } public void Open () { if (open || closed) throw new InvalidOperationException (); CheckHandle (); if (!DoOpen ()) { CheckError (); throw new InvalidOperationException (); } open = true; } protected abstract bool DoOpen (); public void Close () { if (!open) return; CheckHandle (); if (loop != null) { DoSetClient (null, 0, IntPtr.Zero); UnscheduleFromRunLoop (loop, loopMode); loop = null; loopMode = null; } try { DoClose (); } finally { open = false; closed = true; } } protected abstract void DoClose (); public CFStreamStatus GetStatus () { CheckHandle (); return DoGetStatus (); } protected abstract CFStreamStatus DoGetStatus (); internal IntPtr GetProperty (NSString name) { CheckHandle (); return DoGetProperty (name); } protected abstract IntPtr DoGetProperty (NSString name); protected abstract bool DoSetProperty (NSString name, INativeObject value); internal void SetProperty (NSString name, INativeObject value) { CheckHandle (); if (DoSetProperty (name, value)) return; throw new InvalidOperationException (string.Format ( "Cannot set property '{0}' on {1}.", name, GetType ().Name) ); } #endregion #region Events public class StreamEventArgs : EventArgs { public CFStreamEventType EventType { get; private set; } public StreamEventArgs (CFStreamEventType type) { this.EventType = type; } public override string ToString () { return string.Format ("[StreamEventArgs: EventType={0}]", EventType); } } public event EventHandler<StreamEventArgs> OpenCompletedEvent; public event EventHandler<StreamEventArgs> HasBytesAvailableEvent; public event EventHandler<StreamEventArgs> CanAcceptBytesEvent; public event EventHandler<StreamEventArgs> ErrorEvent; public event EventHandler<StreamEventArgs> ClosedEvent; protected virtual void OnOpenCompleted (StreamEventArgs args) { if (OpenCompletedEvent != null) OpenCompletedEvent (this, args); } protected virtual void OnHasBytesAvailableEvent (StreamEventArgs args) { if (HasBytesAvailableEvent != null) HasBytesAvailableEvent (this, args); } protected virtual void OnCanAcceptBytesEvent (StreamEventArgs args) { if (CanAcceptBytesEvent != null) CanAcceptBytesEvent (this, args); } protected virtual void OnErrorEvent (StreamEventArgs args) { if (ErrorEvent != null) ErrorEvent (this, args); } protected virtual void OnClosedEvent (StreamEventArgs args) { if (ClosedEvent != null) ClosedEvent (this, args); } #endregion protected abstract void ScheduleWithRunLoop (CFRunLoop loop, NSString mode); protected abstract void UnscheduleFromRunLoop (CFRunLoop loop, NSString mode); protected delegate void CFStreamCallback (IntPtr s, CFStreamEventType type, IntPtr info); [MonoPInvokeCallback (typeof(CFStreamCallback))] static void OnCallback (IntPtr s, CFStreamEventType type, IntPtr info) { var stream = GCHandle.FromIntPtr (info).Target as CFStream; stream.OnCallback (type); } protected virtual void OnCallback (CFStreamEventType type) { var args = new StreamEventArgs (type); switch (type) { case CFStreamEventType.OpenCompleted: OnOpenCompleted (args); break; case CFStreamEventType.CanAcceptBytes: OnCanAcceptBytesEvent (args); break; case CFStreamEventType.HasBytesAvailable: OnHasBytesAvailableEvent (args); break; case CFStreamEventType.ErrorOccurred: OnErrorEvent (args); break; case CFStreamEventType.EndEncountered: OnClosedEvent (args); break; } } public void EnableEvents (CFRunLoop runLoop, NSString runLoopMode) { if (open || closed || (loop != null)) throw new InvalidOperationException (); CheckHandle (); loop = runLoop; loopMode = runLoopMode; var ctx = new CFStreamClientContext (); ctx.Info = GCHandle.ToIntPtr (gch); var args = CFStreamEventType.OpenCompleted | CFStreamEventType.CanAcceptBytes | CFStreamEventType.HasBytesAvailable | CFStreamEventType.CanAcceptBytes | CFStreamEventType.ErrorOccurred | CFStreamEventType.EndEncountered; var ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (CFStreamClientContext))); try { Marshal.StructureToPtr (ctx, ptr, false); if (!DoSetClient (OnCallback, (int)args, ptr)) throw new InvalidOperationException ("Stream does not support async events."); } finally { Marshal.FreeHGlobal (ptr); } ScheduleWithRunLoop (runLoop, runLoopMode); } protected abstract bool DoSetClient (CFStreamCallback callback, CFIndex eventTypes, IntPtr context); protected CFStream (IntPtr handle) { this.handle = handle; gch = GCHandle.Alloc (this); } protected void CheckHandle () { if (handle == IntPtr.Zero) throw new ObjectDisposedException (GetType ().Name); } ~CFStream () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } protected virtual void Dispose (bool disposing) { if (disposing) { Close (); if (gch.IsAllocated) gch.Free (); } if (handle != IntPtr.Zero) { CFObject.CFRelease (handle); handle = IntPtr.Zero; } } } }
using GuruComponents.CodeEditor.Library.Drawing.GDI; using GuruComponents.CodeEditor.CodeEditor.TextDraw; namespace GuruComponents.CodeEditor.CodeEditor { /// <summary> /// Represents which split view is currently active in the syntaxbox. /// </summary> public enum ActiveView { TopLeft, TopRight, BottomLeft, BottomRight, } /// <summary> /// Indent styles used by the control /// </summary> public enum IndentStyle { /// <summary> /// Caret is always confined to the first column when a new line is inserted. /// </summary> None = 0, /// <summary> /// New lines inherit the same indention as the previous row. /// </summary> LastRow = 1, /// <summary> /// New lines get their indention from the scoping level. /// <seealso cref="GuruComponents.CodeEditor.CodeEditor.Syntax.Scope.CauseIndent">CauseIndent</seealso> /// </summary> Scope = 2, /// <summary> /// New lines get thir indention from the scoping level or from the previous row /// depending on which is most indented. /// <seealso cref="GuruComponents.CodeEditor.CodeEditor.Syntax.Scope.CauseIndent">CauseIndent</seealso> /// </summary> Smart = 3, } } namespace GuruComponents.CodeEditor.CodeEditor.TextDraw { /// <summary> /// To be implemented /// </summary> public enum TextDrawType { /// <summary> /// For public use only /// </summary> StarBorder = 0, /// <summary> /// For public use only /// </summary> MinusBorder = 1, /// <summary> /// For public use only /// </summary> DoubleBorder = 2, /// <summary> /// For public use only /// </summary> SingleBorder = 3 } /// <summary> /// For public use only /// </summary> public enum TextDrawDirectionType { /// <summary> /// For public use only /// </summary> Right = 1, /// <summary> /// For public use only /// </summary> Left = 2, /// <summary> /// For public use only /// </summary> Up = 4, /// <summary> /// For public use only /// </summary> Down = 8 } /// <summary> /// For public use only /// </summary> public enum TextBorderChars { /// <summary> /// For public use only /// </summary> DownRight = 0, /// <summary> /// For public use only /// </summary> RightLeft = 1, /// <summary> /// For public use only /// </summary> DownRightLeft = 2, /// <summary> /// For public use only /// </summary> DownLeft = 4, /// <summary> /// For public use only /// </summary> DownUp = 5, /// <summary> /// For public use only /// </summary> DownUpRight = 10, /// <summary> /// For public use only /// </summary> DownUpRightLeft = 11, /// <summary> /// For public use only /// </summary> DownUpLeft = 12, /// <summary> /// For public use only /// </summary> UpRight = 20, /// <summary> /// For public use only /// </summary> UpRightLeft = 21, /// <summary> /// For public use only /// </summary> UpLeft = 22, /// <summary> /// For public use only /// </summary> Blank = 6 } /// <summary> /// Text actions that can be performed by the SyntaxBoxControl /// </summary> public enum XTextAction { /// <summary> /// The control is not performing any action /// </summary> xtNone = 0, /// <summary> /// The control is in Drag Drop mode /// </summary> xtDragText = 1, /// <summary> /// The control is selecting text /// </summary> xtSelect = 2 } } namespace GuruComponents.CodeEditor.CodeEditor.Painter { /// <summary> /// View point struct used by the SyntaxBoxControl. /// The struct contains information about various rendering parameters that the IPainter needs. /// </summary> public class ViewPoint { /// <summary> /// Used for offsetting the screen in y axis. /// </summary> public int YOffset; /// <summary> /// Height of a row in pixels /// </summary> public int RowHeight; /// <summary> /// Width of a char (space) in pixels /// </summary> public int CharWidth; /// <summary> /// Index of the first visible row /// </summary> public int FirstVisibleRow; /// <summary> /// Number of rows that can be displayed in the current view /// </summary> public int VisibleRowCount; /// <summary> /// Index of the first visible column /// </summary> public int FirstVisibleColumn; /// <summary> /// Width of the client area in pixels /// </summary> public int ClientAreaWidth; /// <summary> /// Height of the client area in pixels /// </summary> public int ClientAreaStart; /// <summary> /// The action that the SyntaxBoxControl is currently performing /// </summary> public XTextAction Action; /// <summary> /// Width of the gutter margin in pixels /// </summary> public int GutterMarginWidth; /// <summary> /// Width of the Linenumber margin in pixels /// </summary> public int LineNumberMarginWidth; /// <summary> /// /// </summary> public int TotalMarginWidth; /// <summary> /// Width of the text margin (sum of gutter + linenumber + folding margins) /// </summary> public int TextMargin; //document items } /// <summary> /// Struct used by the Painter_GDI class. /// </summary> public class RenderItems { /// <summary> /// For public use only /// </summary> public GDISurface BackBuffer; //backbuffer surface /// <summary> /// For public use only /// </summary> public GDISurface SelectionBuffer; //backbuffer surface /// <summary> /// For public use only /// </summary> public GDISurface StringBuffer; //backbuffer surface /// <summary> /// For public use only /// </summary> public GDIFont FontNormal; //Font , no decoration /// <summary> /// For public use only /// </summary> public GDIFont FontBold; //Font , bold /// <summary> /// For public use only /// </summary> public GDIFont FontItalic; //Font , italic /// <summary> /// For public use only /// </summary> public GDIFont FontBoldItalic; //Font , bold & italic /// <summary> /// For public use only /// </summary> public GDIFont FontUnderline; //Font , no decoration /// <summary> /// For public use only /// </summary> public GDIFont FontBoldUnderline; //Font , bold /// <summary> /// For public use only /// </summary> public GDIFont FontItalicUnderline; //Font , italic /// <summary> /// For public use only /// </summary> public GDIFont FontBoldItalicUnderline; //Font , bold & italic /// <summary> /// For public use only /// </summary> public GDIBrush GutterMarginBrush; //Gutter margin brush /// <summary> /// For public use only /// </summary> public GDIBrush GutterMarginBorderBrush; //Gutter margin brush /// <summary> /// For public use only /// </summary> public GDIBrush LineNumberMarginBrush; //linenumber margin brush /// <summary> /// For public use only /// </summary> public GDIBrush LineNumberMarginBorderBrush; //linenumber margin brush /// <summary> /// For public use only /// </summary> public GDIBrush BackgroundBrush; //background brush /// <summary> /// For public use only /// </summary> public GDIBrush HighLightLineBrush; //background brush /// <summary> /// For public use only /// </summary> public GDIBrush OutlineBrush; //background brush } }
//Things to exec exec("./Item_Skates.cs"); exec("./Item_HockeyStick.cs"); exec("./Item_Puck.cs"); exec("./Item_GoalieStick.cs"); exec("./Item_GoalieSkates.cs"); exec("./Item_Helmet.cs"); //Global vars $Check::Amount = 5; //Support functions function makePositive(%num) { if(%num < 0) { return %num * -1; } else { return %num; } } function vectorMultiply(%vector1, %vector2) { %component1 = getWord(%vector1, 0); %component2 = getWord(%vector1, 1); %component3 = getWord(%vector1, 2); %component4 = getWord(%vector2, 0); %component5 = getWord(%vector2, 1); %component6 = getWord(%vector2, 2); %fcomponent1 = %component1 * %component4; %fcomponent2 = %component2 * %component5; %fcomponent3 = %component3 * %component6; %fvec = %fcomponent1 SPC %fcomponent2 SPC %fcomponent3; return %fvec; } function VectorExtend(%vec, %x) { return VectorAdd(%vec, VectorScale(VectorNormalize(%vec), %x)); } //actual code function servercmdclearpucks(%client) { } package IceHockey { function Armor::onTrigger(%data,%obj,%slot,%val) { Parent::onTrigger(%data,%obj,%slot,%val); //echo("onTrigger invoked"); if(%obj.getDatablock() == PlayerIceHockeyArmor.getID() || %obj.getDatablock() == PlayerGoalieArmor.getID()) { //echo("yes he has a hockey player"); if(%slot == 2) { //echo("stopping him"); if(($Sim::Time - %obj.lastbrake) > 1) { serverPlay3D(Shave_Ice,%obj.gettransform()); %obj.setVelocity("0 0 0"); %obj.lastbrake = $Sim::Time; } } } %image = %obj.getMountedImage(0); //Echo(%image); if(%slot == 4) { //HOCKEY PASS if(isObject(%image) && %image.HockeyStickWPuck) { %obj.hasPuck = false; %obj.hasSportBall = false; //echo("no puck :("); serverPlay3D(SlapShot,%obj.getPosition()); %obj.unmountimage( 0 ); %obj.mountimage(HockeyStickImage, 0); %aim = %obj.getMuzzleVector(0); %aim = getWord(%aim, 0) SPC getWord(%aim, 1) SPC "0"; %posScale = vectorAdd(vectorScale(%aim,0.1 * vectorLen(%obj.getVelocity())),vectorScale(%aim,5)); %position = vectorAdd(%posScale,%obj.getPosition()); %velocity = vectorScale(%aim,40); //%velocity = vectorAdd(%velScale,vectorLen(%obj.getVelocity())); %p = new item() { dataBlock = PuckPickupItem; lifetime = 40000; position = %position; sourceObject = %obj; sourceSlot = 0; client = %obj.client; }; %p.setVelocity(%velocity); %p.schedulePop(); %obj.playThread(3, shiftRight); } if(isObject(%image) && %image.HockeyStick) { if(%val) %obj.playThread(3,shiftRight); } //GOALIE PASS if(isObject(%image) && %image.GoalieStickWPuck) { %obj.hasPuck = false; %obj.hasSportBall = false; //echo("no puck :("); serverPlay3D(SlapShot,%obj.getPosition()); %obj.unmountimage( 0 ); %obj.mountimage(GoalieStickImage, 0); %aim = %obj.getMuzzleVector(0); %aim = getWord(%aim, 0) SPC getWord(%aim, 1) SPC "0"; %posScale = vectorAdd(vectorScale(%aim,0.1 * vectorLen(%obj.getVelocity())),vectorScale(%aim,5)); %position = vectorAdd(%posScale,%obj.getPosition()); %velocity = vectorScale(%aim,37); //%velocity = vectorAdd(%velScale,vectorLen(%obj.getVelocity())); %p = new item() { dataBlock = PuckPickupItem; lifetime = 40000; position = %position; sourceObject = %obj; sourceSlot = 0; client = %obj.client; }; %p.setVelocity(%velocity); %obj.playThread(3, shiftRight); } if(isObject(%image) && %image.GoalieStick) { if(%val) %obj.playThread(3,shiftRight); } } } function player::skateLoop(%this) { if(%this.getDatablock() == PlayerIceHockeyArmor.getID() || %this.getDatablock() == PlayerGoalieArmor.getID()) { //echo("skateLOOP WOOOOO!@#@#$@#4"); %pos = getWords(%this.getPosition(), 0, 1); if(%this.s_lastpos $= getWords(%this.getPosition(), 0, 1)) { //echo("same position"); //do nothing! } else if(!%this.isMounted()) { //echo("diff position"); if(makePositive(getWord(%this.getVelocity(),0)) < 3 && makePositive(getWord(%this.getVelocity(),1)) < 3) { %this.playSkateStep(1); } else { %this.playSkateStep(2); } %this.s_lastpos = getWords(%this.getPosition(), 0, 1); } //echo("@#@#$@#%@#$@#$NUMBER 2"); %this.schedule(300, skateloop); } } function player::addItem( %this, %tool ) { if(!isObject(%tool)) { return; } %tool = %tool.getID(); %slots = %this.getDataBlock().maxTools; for(%i = 0; %i < %slots ; %i++) { if(!isObject(%this.tool[%i])) { %this.tool[%i] = %tool; if(isObject(%cl = %this.client)) { messageClient(%cl, 'MsgItemPickup', '', %i, %tool); } break; } } } function Armor::onCollision(%this, %obj, %col, %thing, %other) { //echo("collided"); if(%col.hasskates) { echo("pushing..."); %vel = vectorAdd(%col.getVelocity(),vectorScale(%player.getVelocity,6)); echo(%vel); %col.setVelocity(%vel); } parent::OnCollision(%this, %obj, %col, %thing, %other); } function player::playSkateStep(%this,%type) { %random = getRandom(1, 2); if(%type == 1) { %sound = "skate_quiet" @ (%random); } else { %sound = "skate_loud" @ (%random); } serverplay3d(%sound,%this.getHackPosition() SPC "0 0 1 0"); } }; activatePackage(IceHockey);
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class CampaignTimeZone : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<string>( name: "TimeZoneId", table: "Campaign", nullable: false, defaultValue: "Central Standard Time"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "TimeZoneId", table: "Campaign"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
using Mono.Cecil; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Signum.TSGenerator; public class PreloadingAssemblyResolver : DefaultAssemblyResolver { public AssemblyDefinition SignumUtilities { get; private set; } public AssemblyDefinition SignumEntities { get; private set; } Dictionary<string, string> assemblyLocations; public PreloadingAssemblyResolver(string[] references) { this.assemblyLocations = references.ToDictionary(a => Path.GetFileNameWithoutExtension(a)); foreach (var dll in references.Where(r => r.Contains("Signum"))) { var assembly = ModuleDefinition.ReadModule(dll, new ReaderParameters { AssemblyResolver = this }).Assembly; if (assembly.Name.Name == "Signum.Entities") SignumEntities = assembly; if (assembly.Name.Name == "Signum.Utilities") SignumUtilities = assembly; RegisterAssembly(assembly); } } public override AssemblyDefinition Resolve(AssemblyNameReference name) { var assembly = ModuleDefinition.ReadModule(this.assemblyLocations[name.Name], new ReaderParameters { AssemblyResolver = this }).Assembly; this.RegisterAssembly(assembly); return assembly; } } static class EntityDeclarationGenerator { internal class TypeCache { public TypeDefinition ModifiableEntity; public TypeDefinition InTypeScriptAttribute; public TypeDefinition ImportInTypeScriptAttribute; public TypeDefinition IEntity; public TypeCache(AssemblyDefinition signumEntities) { ModifiableEntity = signumEntities.MainModule.GetType("Signum.Entities", "ModifiableEntity"); InTypeScriptAttribute = signumEntities.MainModule.GetType("Signum.Entities", "InTypeScriptAttribute"); ImportInTypeScriptAttribute = signumEntities.MainModule.GetType("Signum.Entities", "ImportInTypeScriptAttribute"); IEntity = signumEntities.MainModule.GetType("Signum.Entities", "IEntity"); } } static TypeCache Cache; static ConcurrentDictionary<TypeReference, bool> IEntityCache = new ConcurrentDictionary<TypeReference, bool>(); internal static string Process(AssemblyOptions options, string templateFileName, string currentNamespace) { StringBuilder sb = new StringBuilder(); var entities = options.Resolver.SignumEntities; Cache = new TypeCache(entities); var namespacesReferences = new Dictionary<string, Dictionary<string, NamespaceTSReference>>(); namespacesReferences.GetNamespaceReference(options, Cache.ModifiableEntity); var exportedTypes = options.ModuleDefinition.Types.Where(a => a.Namespace == currentNamespace).ToList(); if (exportedTypes.Count == 0) throw new InvalidOperationException($"Assembly '{options.CurrentAssembly}' has not types in namespace '{currentNamespace}'"); var imported = options.ModuleDefinition.Assembly.CustomAttributes.Where(at => at.AttributeType.FullName == Cache.ImportInTypeScriptAttribute.FullName) .Where(at => (string)at.ConstructorArguments[1].Value == currentNamespace) .Select(at => ((TypeReference)at.ConstructorArguments[0].Value).Resolve()) .ToList(); var importedMessage = imported.Where(a => a.Name.EndsWith("Message")).ToList(); var importedEnums = imported.Except(importedMessage).ToList(); var entityResults = (from type in exportedTypes where !type.IsValueType && (type.InTypeScript() ?? IsModifiableEntity(type)) select new { ns = type.Namespace, type, text = EntityInTypeScript(type, options, namespacesReferences), }).ToList(); var interfacesResults = (from type in exportedTypes where type.IsInterface && (type.InTypeScript() ?? type.AnyInterfaces(IEntityCache, i => i.FullName == Cache.IEntity.FullName)) select new { ns = type.Namespace, type, text = EntityInTypeScript(type, options, namespacesReferences), }).ToList(); var usedEnums = (from type in entityResults.Select(a => a.type) from p in GetAllProperties(type) let pt = (p.PropertyType.ElementType() ?? p.PropertyType).UnNullify() let def = pt.Resolve() where def != null && def.IsEnum select def).Distinct().ToList(); var symbolResults = (from type in exportedTypes where !type.IsValueType && type.IsStaticClass() && type.ContainsAttribute("AutoInitAttribute") && (type.InTypeScript() ?? true) select new { ns = type.Namespace, type, text = SymbolInTypeScript(type, options, namespacesReferences), }).ToList(); var enumResult = (from type in exportedTypes where type.IsEnum && (type.InTypeScript() ?? usedEnums.Contains(type)) select new { ns = type.Namespace, type, text = EnumInTypeScript(type, options), }).ToList(); var externalEnums = (from type in usedEnums.Where(options.IsExternal).Concat(importedEnums) select new { ns = currentNamespace + ".External", type, text = EnumInTypeScript(type, options), }).ToList(); var externalMessages = (from type in importedMessage select new { ns = currentNamespace + ".External", type, text = MessageInTypeScript(type, options), }).ToList(); var messageResults = (from type in exportedTypes where type.IsEnum && type.Name.EndsWith("Message") select new { ns = type.Namespace, type, text = MessageInTypeScript(type, options), }).ToList(); var queryResult = (from type in exportedTypes where type.IsEnum && type.Name.EndsWith("Query") select new { ns = type.Namespace, type, text = QueryInTypeScript(type, options), }).ToList(); var namespaces = entityResults .Concat(interfacesResults) .Concat(enumResult) .Concat(messageResults) .Concat(queryResult) .Concat(symbolResults) .Concat(externalEnums) .Concat(externalMessages) .GroupBy(a => a.ns) .OrderBy(a => a.Key); foreach (var ns in namespaces) { var key = RemoveNamespace(ns.Key.ToString(), currentNamespace); if (key.Length == 0) { foreach (var item in ns.OrderBy(a => a.type.Name)) { sb.AppendLine(item.text); } } else { sb.AppendLine("export namespace " + key + " {"); sb.AppendLine(); foreach (var item in ns.OrderBy(a => a.type.Name)) { foreach (var line in item.text.Split(new[] { "\r\n" }, StringSplitOptions.None)) sb.AppendLine(" " + line); } sb.AppendLine("}"); sb.AppendLine(); } } var code = sb.ToString(); return WriteFillFile(options, code, templateFileName, namespacesReferences); } private static string WriteFillFile(AssemblyOptions options, string code, string templateFileName, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences) { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"//////////////////////////////////"); sb.AppendLine(@"//Auto-generated. Do NOT modify!//"); sb.AppendLine(@"//////////////////////////////////"); sb.AppendLine(); var path = namespacesReferences.GetOrThrow("Signum.Entities").GetOrThrow("Signum.Entities").Path.Replace("Signum.Entities.ts", "Reflection.ts"); sb.AppendLine($"import {{ MessageKey, QueryKey, Type, EnumType, registerSymbol }} from '{RelativePath(path, templateFileName)}'"); foreach (var a in namespacesReferences.Values) { foreach (var ns in a.Values) { sb.AppendLine($"import * as {ns.VariableName} from '{RelativePath(ns.Path, templateFileName)}'"); } } sb.AppendLine(); sb.AppendLine(File.ReadAllText(templateFileName)); sb.AppendLine(code); return sb.ToString(); } private static string RelativePath(string path, string fileName) { Uri pathUri = new Uri(path.RemoveSuffix(".ts"), UriKind.Absolute); Uri fileNameUri = new Uri(fileName, UriKind.Absolute); string relPath = fileNameUri.MakeRelativeUri(pathUri).ToString(); var result = relPath.Replace(@"\", "/"); if (!result.StartsWith("..")) return "./" + result; return result; } private static string EnumInTypeScript(TypeDefinition type, AssemblyOptions options) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"export const {type.Name} = new EnumType<{type.Name}>(\"{type.Name}\");"); sb.AppendLine($"export type {type.Name} ="); var fields = type.Fields.OrderBy(a => a.Constant as IComparable).Where(a => a.IsPublic && a.IsStatic).ToList(); for (int i = 0; i < fields.Count; i++) { sb.Append($" \"{fields[i].Name}\""); if (i < fields.Count - 1) sb.AppendLine(" |"); else sb.AppendLine(";"); } return sb.ToString(); } private static string MessageInTypeScript(TypeDefinition type, AssemblyOptions options) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"export module {type.Name} {{"); var fields = type.Fields.OrderBy(a => a.MetadataToken.RID).Where(a => a.IsPublic && a.IsStatic).ToList(); foreach (var field in fields) { string context = $"By type {type.Name} and field {field.Name}"; sb.AppendLine($" export const {field.Name} = new MessageKey(\"{type.Name}\", \"{field.Name}\");"); } sb.AppendLine(@"}"); return sb.ToString(); } private static string QueryInTypeScript(TypeDefinition type, AssemblyOptions options) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"export module {type.Name} {{"); var fields = type.Fields.OrderBy(a => a.MetadataToken.RID).Where(a => a.IsPublic && a.IsStatic).ToList(); foreach (var field in fields) { string context = $"By type {type.Name} and field {field.Name}"; sb.AppendLine($" export const {field.Name} = new QueryKey(\"{type.Name}\", \"{field.Name}\");"); } sb.AppendLine(@"}"); return sb.ToString(); } static ConcurrentDictionary<TypeReference, bool> IOperationSymbolCache = new ConcurrentDictionary<TypeReference, bool>(); private static string SymbolInTypeScript(TypeDefinition type, AssemblyOptions options, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"export module {type.Name} {{"); var fields = type.Fields.OrderBy(a => a.MetadataToken.RID).Where(a => a.IsPublic && a.IsStatic).ToList(); foreach (var field in fields) { string context = $"By type {type.Name} and field {field.Name}"; var propertyType = TypeScriptName(field.FieldType, type, options, namespacesReferences, context); var fieldTypeDef = field.FieldType.Resolve(); var cleanType = fieldTypeDef.IsInterface && fieldTypeDef.AnyInterfaces(IOperationSymbolCache, i => i.Name == "IOperationSymbolContainer") ? "Operation" : CleanTypeName(fieldTypeDef); sb.AppendLine($" export const {field.Name} : {propertyType} = registerSymbol(\"{cleanType}\", \"{type.Name}.{field.Name}\");"); } sb.AppendLine(@"}"); return sb.ToString(); } private static string EntityInTypeScript(TypeDefinition type, AssemblyOptions options, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences) { StringBuilder sb = new StringBuilder(); if (!type.IsAbstract) sb.AppendLine($"export const {type.Name} = new Type<{type.Name}>(\"{CleanTypeName(type)}\");"); List<string> baseTypes = new List<string>(); if (type.BaseType != null) baseTypes.Add(TypeScriptName(type.BaseType, type, options, namespacesReferences, $"By type {type.Name}")); var baseInterfaces = Parents(type.BaseType?.Resolve()).SelectMany(t => t.Resolve()?.Interfaces.Select(a => a.InterfaceType) ?? Enumerable.Empty<TypeReference>()).Select(a => a.FullName).ToHashSet(); var interfaces = type.Interfaces.Select(i => i.InterfaceType).Where(it => !baseInterfaces.Contains(it.FullName)) .Where(it => it.FullName == Cache.IEntity.FullName || it.Resolve()?.Interfaces.Any(it2 => it2.InterfaceType.FullName == Cache.IEntity.FullName) == true); foreach (var i in interfaces) baseTypes.Add(TypeScriptName(i, type, options, namespacesReferences, $"By type {type.Name}")); sb.AppendLine($"export interface {TypeScriptName(type, type, options, namespacesReferences, "declaring " + type.Name)} extends {string.Join(", ", baseTypes.Distinct())} {{"); if (!type.IsAbstract && Parents(type.BaseType?.Resolve()).All(a => a.IsAbstract)) sb.AppendLine($" Type: \"{CleanTypeName(type)}\";"); var properties = GetProperties(type); var defaultNullableCustomAttribute = type.NullableContextAttribute(); foreach (var prop in properties) { string context = $"By type {type.Name} and property {prop.Name}"; var propertyType = TypeScriptNameInternal(prop.PropertyType, type, options, namespacesReferences, context) + (prop.GetTypescriptNull(defaultNullableCustomAttribute) ? " | null" : ""); var undefined = prop.GetTypescriptUndefined() ? "?" : ""; sb.AppendLine($" {FirstLower(prop.Name)}{undefined}: {propertyType};"); } sb.AppendLine(@"}"); return sb.ToString(); } static CustomAttribute NullableContextAttribute(this TypeDefinition type) { return type.CustomAttributes.SingleOrDefault(a => a.AttributeType.Name == "NullableContextAttribute") ?? type.DeclaringType?.NullableContextAttribute(); } static ConcurrentDictionary<TypeReference, bool> IsModifiableDictionary = new ConcurrentDictionary<TypeReference, bool>(); static bool IsModifiableEntity(TypeDefinition t) { if (t.IsValueType || t.IsInterface) return false; if (!InheritsFromModEntity(t)) return false; return true; bool InheritsFromModEntity(TypeReference tr) { return IsModifiableDictionary.GetOrAdd(tr, tr => { if (tr.FullName == Cache.ModifiableEntity.FullName) return true; var td = tr.Resolve(); if (td.BaseType == null || td.BaseType.FullName == "System.Object") return false; return InheritsFromModEntity(td.BaseType); }); } } private static IEnumerable<TypeDefinition> Parents(TypeDefinition type) { while (type != null && type.FullName != Cache.ModifiableEntity.FullName) { yield return type; type = type.BaseType?.Resolve(); } } static string CleanTypeName(TypeDefinition t) { if (!t.AnyInterfaces(IEntityCache, tr => tr.FullName == Cache.IEntity.FullName)) return t.Name; if (t.Name.EndsWith("Entity")) return t.Name.RemoveSuffix("Entity"); if (t.Name.EndsWith("Model")) return t.Name.RemoveSuffix("Model"); if (t.Name.EndsWith("Symbol")) return t.Name.RemoveSuffix("Symbol"); return t.Name; } static string RemoveSuffix(this string text, string postfix) { if (text.EndsWith(postfix) && text != postfix) return text.Substring(0, text.Length - postfix.Length); return text; } private static IEnumerable<PropertyDefinition> GetAllProperties(TypeDefinition type) { return GetProperties(type).Concat(type.BaseType == null ? Enumerable.Empty<PropertyDefinition>() : GetAllProperties(type.BaseType.Resolve())); } private static IEnumerable<PropertyDefinition> GetProperties(TypeDefinition type) { return type.Properties.Where(p => p.HasThis && p.GetMethod.IsPublic) .Where(p => p.InTypeScript() ?? !(p.ContainsAttribute("HiddenPropertyAttribute") || p.ContainsAttribute("ExpressionFieldAttribute") || p.ContainsAttribute("AutoExpressionFieldAttribute"))); } public static bool ContainsAttribute(this IMemberDefinition p, string attributeName) { return p.CustomAttributes.Any(a => a.AttributeType.Name == attributeName); } public static CustomAttribute GetAttributeInherit(this TypeDefinition type, string attributeName) { if (type == null) return null; var att = type.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == attributeName); if (att != null) return att; return GetAttributeInherit(type.BaseType?.Resolve(), attributeName); } public static bool? InTypeScript(this MemberReference mr) { var attr = mr.Resolve().CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == Cache.InTypeScriptAttribute.FullName); if (attr == null) return null; return (bool?)attr.ConstructorArguments.FirstOrDefault().Value; } public static bool GetTypescriptUndefined(this PropertyDefinition p) { var ainTSAttr = p.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == Cache.InTypeScriptAttribute.FullName); var b = (bool?)ainTSAttr?.Properties.SingleOrDefault(a => a.Name == "Undefined").Argument.Value; if (b != null) return b.Value; return GetTypescriptUndefined(p.DeclaringType) ?? false; } private static bool? GetTypescriptUndefined(TypeDefinition declaringType) { var inTSAttr = GetAttributeInherit(declaringType, Cache.InTypeScriptAttribute.FullName); return (bool?)inTSAttr?.Properties.SingleOrDefault(a => a.Name == "Undefined").Argument.Value; } public static bool GetTypescriptNull(this PropertyDefinition p, CustomAttribute defaultCustomAttribute) { var inTSAttr = p.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == Cache.InTypeScriptAttribute.FullName); var b = (bool?)inTSAttr?.Properties.SingleOrDefault(a => a.Name == "Null").Argument.Value; if (b != null) return b.Value; if (p.PropertyType.IsValueType) return p.PropertyType.IsNullable(); else { var nullableAttr = p.CustomAttributes.SingleOrDefault(a => a.AttributeType.Name == "NullableAttribute"); if (nullableAttr == null) nullableAttr = defaultCustomAttribute; if (nullableAttr == null) return false; var arg = nullableAttr.ConstructorArguments[0].Value; if (arg is byte val) return val == 2; if (arg is CustomAttributeArgument[] args) return ((byte)args[0].Value) == 2; throw new InvalidOperationException("Unexpected value of type " + arg.GetType() + " in NullableAttribute constructor"); } } private static string FirstLower(string name) { return char.ToLowerInvariant(name[0]) + name.Substring(1); } public static bool IsNullable(this TypeReference type) { return type is GenericInstanceType gtype && gtype.ElementType.Name == "Nullable`1"; } public static TypeReference UnNullify(this TypeReference type) { return type is GenericInstanceType gtype && gtype.ElementType.Name == "Nullable`1" ? gtype.GenericArguments.Single() : type; } static ConcurrentDictionary<TypeReference, bool> IEnumerableCache = new ConcurrentDictionary<TypeReference, bool>(); public static TypeReference ElementType(this TypeReference type) { if (!(type is GenericInstanceType gen)) return null; if (type.FullName == typeof(string).FullName || type.FullName == typeof(byte[]).FullName) return null; var def = type.Resolve(); if (def == null) return null; if (!gen.AnyInterfaces(IEnumerableCache, tr => tr is GenericInstanceType git && git.ElementType.Name == "IEnumerable`1")) return null; return gen.GenericArguments.Single(); } static string TypeScriptName(TypeReference type, TypeDefinition current, AssemblyOptions options, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences, string errorContext) { var ut = type.UnNullify(); if (ut != type) return TypeScriptNameInternal(ut, current, options, namespacesReferences, errorContext) + " | null"; return TypeScriptNameInternal(type, current, options, namespacesReferences, errorContext); } private static string TypeScriptNameInternal(TypeReference type, TypeDefinition current, AssemblyOptions options, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences, string errorContext) { type = type.UnNullify(); if (type.FullName == typeof(Boolean).FullName) return "boolean"; if (type.FullName == typeof(Char).FullName) return "string"; if (type.FullName == typeof(SByte).FullName || type.FullName == typeof(Byte).FullName || type.FullName == typeof(Int16).FullName || type.FullName == typeof(UInt16).FullName || type.FullName == typeof(Int32).FullName || type.FullName == typeof(UInt32).FullName || type.FullName == typeof(Int64).FullName || type.FullName == typeof(UInt64).FullName || type.FullName == typeof(Decimal).FullName || type.FullName == typeof(Single).FullName || type.FullName == typeof(Double).FullName) return "number"; if (type.FullName == typeof(String).FullName) return "string"; if (type.FullName == typeof(DateTime).FullName || type.FullName == typeof(DateOnly).FullName || type.FullName == typeof(DateTimeOffset).FullName || type.FullName == typeof(TimeSpan).FullName || type.FullName == typeof(TimeOnly).FullName || type.FullName == typeof(Guid).FullName) return "string /*" + type.Name + "*/"; if (type.FullName == typeof(Byte[]).FullName) return "string /*Byte[]*/"; if (type.IsGenericParameter) return type.Name; if (type is GenericInstanceType git) return RelativeName(type.Resolve(), current, options, namespacesReferences, errorContext) + "<" + string.Join(", ", git.GenericArguments.Select(a => TypeScriptName(a, current, options, namespacesReferences, errorContext)).ToList()) + ">"; else if (type.HasGenericParameters) return RelativeName(type.Resolve(), current, options, namespacesReferences, errorContext) + "<" + string.Join(", ", type.GenericParameters.Select(gp => gp.Name)) + ">"; else if (type is ArrayType at) return TypeScriptName(at.ElementType, current, options, namespacesReferences, errorContext) + "[]"; else return RelativeName(type.Resolve(), current, options, namespacesReferences, errorContext); } private static string RelativeName(TypeDefinition type, TypeDefinition current, AssemblyOptions options, Dictionary<string, Dictionary<string, NamespaceTSReference>> namespacesReferences, string errorContext) { if (type.IsGenericParameter) return type.Name; if (type.DeclaringType != null) return RelativeName(type.DeclaringType, current, options, namespacesReferences, errorContext) + "_" + BaseTypeScriptName(type); if (type.Module.Assembly.Equals(current.Module.Assembly) && type.Namespace == current.Namespace) { string relativeNamespace = RelativeNamespace(type, current); return CombineNamespace(relativeNamespace, BaseTypeScriptName(type)); } else if (type.IsEnum && options.IsExternal(type)) { return "External." + BaseTypeScriptName(type); } else { var nsReference = GetNamespaceReference(namespacesReferences, options, type); if (nsReference == null) { if (type.Interfaces.Any(i => i.InterfaceType.FullName == typeof(IEnumerable).FullName)) return "Array"; throw new InvalidOperationException($"{errorContext}: Type {type.ToString()} is declared in the assembly '{type.Module.Assembly.Name}', but no React directory for it is found."); } return CombineNamespace(nsReference.VariableName, BaseTypeScriptName(type)); } } public static bool AnyInterfaces(this TypeReference type, ConcurrentDictionary<TypeReference, bool> cache, Func<TypeReference, bool> func) { return cache.GetOrAdd(type, type => { var td = type.Resolve(); foreach (var item in td.Interfaces) { if (func(item.InterfaceType)) return true; } if (td.BaseType == null) return false; return td.BaseType.AnyInterfaces(cache, func); }); } public static NamespaceTSReference GetNamespaceReference(this Dictionary<string, Dictionary<string, NamespaceTSReference>> references, AssemblyOptions options, TypeDefinition type) { AssemblyReference assemblyReference; options.AssemblyReferences.TryGetValue(type.Module.Assembly.Name.Name, out assemblyReference); if (assemblyReference == null) return null; return references.GetOrCreate(type.Module.Assembly.Name.Name, () => new Dictionary<string, NamespaceTSReference>()) .GetOrCreate(type.Namespace, () => new NamespaceTSReference { Namespace = type.Namespace, Path = FindDeclarationsFile(assemblyReference, type.Namespace, type), VariableName = GetVariableName(references, type.Namespace.Split('.')) }); } static T GetOrCreate<K, T>(this Dictionary<K, T> dictionary, K key, Func<T> create) { if (dictionary.TryGetValue(key, out var result)) return result; return dictionary[key] = create(); } private static string GetVariableName(Dictionary<string, Dictionary<string, NamespaceTSReference>> namespaceReferences, string[] nameParts) { var list = namespaceReferences.Values.SelectMany(a => a.Values.Select(ns => ns.VariableName)); for (int i = 1; ; i++) { foreach (var item in nameParts.Reverse()) { var candidate = item + (i == 1 ? "" : i.ToString()); if (!list.Contains(candidate)) return candidate; } } } private static string FindDeclarationsFile(AssemblyReference assemblyReference, string @namespace, TypeDefinition typeForError) { var fileTS = @namespace + ".ts"; var result = assemblyReference.AllTypescriptFiles.Where(a => Path.GetFileName(a) == fileTS).ToList(); if (result.Count == 1) return result.Single(); if (result.Count > 1) throw new InvalidOperationException($"importing '{typeForError}' required but multiple '{fileTS}' were found inside '{assemblyReference.ReactDirectory}':\r\n{string.Join("\r\n", result.Select(a => " " + a).ToArray())}"); var fileT4S = @namespace + ".t4s"; result = assemblyReference.AllTypescriptFiles.Where(a => Path.GetFileName(a) == fileT4S).ToList(); if (result.Count == 1) return result.Single().RemoveSuffix(".t4s") + ".ts"; if (result.Count > 1) throw new InvalidOperationException($"importing '{typeForError}' required but multiple '{fileT4S}' were found inside '{assemblyReference.ReactDirectory}':\r\n{string.Join("\r\n", result.Select(a => " " + a).ToArray())}"); throw new InvalidOperationException($"importing '{typeForError}' required but no '{fileTS}' or '{fileT4S}' found inside '{assemblyReference.ReactDirectory}'"); } private static string BaseTypeScriptName(TypeDefinition type) { if (type.FullName == Cache.IEntity.FullName) return "Entity"; var name = type.Name; int pos = name.IndexOf('`'); if (pos == -1) return name; return name.Substring(0, pos); } private static string RelativeNamespace(TypeDefinition referedType, TypeDefinition current) { var referedNS = referedType.Namespace.Split('.').ToList(); var currentNS = current.Namespace.Split('.').ToList(); var equal = referedNS.Zip(currentNS, (a, b) => new { a, b }).Where(p => p.a == p.b).Count(); referedNS.RemoveRange(0, equal); return string.Join(".", referedNS); } private static string CombineNamespace(params string[] parts) { StringBuilder sb = new StringBuilder(); foreach (var p in parts) { if (!string.IsNullOrEmpty(p)) { if (sb.Length > 0) sb.Append("."); sb.Append(p); } } return sb.ToString(); } private static string RemoveNamespace(string v, string baseNamespace) { if (v == baseNamespace) return ""; if (v.StartsWith(baseNamespace + ".")) return v.Substring((baseNamespace + ".").Length); return v; } public static bool IsStaticClass(this TypeDefinition type) { return type.IsAbstract && type.IsSealed; } } [Serializable] public class AssemblyOptions { public string CurrentAssembly; public Dictionary<string, AssemblyReference> AssemblyReferences; public Dictionary<string, string> AllReferences { get; internal set; } public PreloadingAssemblyResolver Resolver { get; internal set; } public ModuleDefinition ModuleDefinition { get; internal set; } public bool IsExternal(TypeDefinition type) { return type.Module.Assembly.Name.Name != CurrentAssembly && !AssemblyReferences.ContainsKey(type.Module.Assembly.Name.Name); } //public Assembly Default_Resolving(AssemblyLoadContext arg1, AssemblyName arg2) //{ // Console.WriteLine(arg2.Name); // if (AllReferences.TryGetValue(arg2.Name, out string path)) // return arg1.LoadFromAssemblyPath(path); // return null; //} } [Serializable] public class AssemblyReference { public string ReactDirectory; public string AssemblyFullPath; public string AssemblyName; public List<string> AllTypescriptFiles; } public class NamespaceTSReference { public string Namespace; public string Path; public string VariableName; } public static class DictionaryExtensions { public static V GetOrThrow<K, V>(this Dictionary<K, V> dictionary, K key) { V result; if (!dictionary.TryGetValue(key, out result)) throw new KeyNotFoundException($"Key '{key}' not found"); return result; } }
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; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPromotion { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPromotion() : base() { FormClosed += frmPromotion_FormClosed; KeyPress += frmPromotion_KeyPress; Resize += frmPromotion_Resize; Load += frmPromotion_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public DateTimePicker _DTFields_3; public DateTimePicker _DTFields_2; public System.Windows.Forms.CheckBox _chkFields_2; private System.Windows.Forms.Button withEventsField_cmdDelete; public System.Windows.Forms.Button cmdDelete { get { return withEventsField_cmdDelete; } set { if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click -= cmdDelete_Click; } withEventsField_cmdDelete = value; if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click += cmdDelete_Click; } } } private System.Windows.Forms.Button withEventsField_cmdAdd; public System.Windows.Forms.Button cmdAdd { get { return withEventsField_cmdAdd; } set { if (withEventsField_cmdAdd != null) { withEventsField_cmdAdd.Click -= cmdAdd_Click; } withEventsField_cmdAdd = value; if (withEventsField_cmdAdd != null) { withEventsField_cmdAdd.Click += cmdAdd_Click; } } } private System.Windows.Forms.ListView withEventsField_lvPromotion; public System.Windows.Forms.ListView lvPromotion { get { return withEventsField_lvPromotion; } set { if (withEventsField_lvPromotion != null) { withEventsField_lvPromotion.DoubleClick -= lvPromotion_DoubleClick; withEventsField_lvPromotion.KeyPress -= lvPromotion_KeyPress; } withEventsField_lvPromotion = value; if (withEventsField_lvPromotion != null) { withEventsField_lvPromotion.DoubleClick += lvPromotion_DoubleClick; withEventsField_lvPromotion.KeyPress += lvPromotion_KeyPress; } } } public System.Windows.Forms.CheckBox _chkFields_1; public System.Windows.Forms.CheckBox _chkFields_0; public DateTimePicker _DTFields_0; private System.Windows.Forms.TextBox withEventsField__txtFields_0; public System.Windows.Forms.TextBox _txtFields_0 { get { return withEventsField__txtFields_0; } set { if (withEventsField__txtFields_0 != null) { withEventsField__txtFields_0.Enter -= txtFields_Enter; } withEventsField__txtFields_0 = value; if (withEventsField__txtFields_0 != null) { withEventsField__txtFields_0.Enter += txtFields_Enter; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } public System.Windows.Forms.Panel picButtons; public DateTimePicker _DTFields_1; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label _lblLabels_1; public System.Windows.Forms.Label _lblLabels_0; public System.Windows.Forms.Label _lblLabels_38; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; //Public WithEvents DTFields As DateTimePicker //Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPromotion)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._DTFields_3 = new System.Windows.Forms.DateTimePicker(); this._DTFields_2 = new System.Windows.Forms.DateTimePicker(); this._chkFields_2 = new System.Windows.Forms.CheckBox(); this.cmdDelete = new System.Windows.Forms.Button(); this.cmdAdd = new System.Windows.Forms.Button(); this.lvPromotion = new System.Windows.Forms.ListView(); this._chkFields_1 = new System.Windows.Forms.CheckBox(); this._chkFields_0 = new System.Windows.Forms.CheckBox(); this._DTFields_0 = new System.Windows.Forms.DateTimePicker(); this._txtFields_0 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this._DTFields_1 = new System.Windows.Forms.DateTimePicker(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this._lblLabels_1 = new System.Windows.Forms.Label(); this._lblLabels_0 = new System.Windows.Forms.Label(); this._lblLabels_38 = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._lbl_5 = new System.Windows.Forms.Label(); //Me.DTFields = New AxDTPickerArray(components) //Me.chkFields = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this._DTFields_3).BeginInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_2).BeginInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_0).BeginInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_1).BeginInit(); //CType(Me.DTFields, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.chkFields, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Edit Promotion Details"; this.ClientSize = new System.Drawing.Size(455, 460); this.Location = new System.Drawing.Point(73, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPromotion"; //_DTFields_3.OcxState = CType(resources.GetObject("_DTFields_3.OcxState"), System.Windows.Forms.AxHost.State) this._DTFields_3.Size = new System.Drawing.Size(130, 21); this._DTFields_3.Location = new System.Drawing.Point(291, 112); this._DTFields_3.TabIndex = 20; this._DTFields_3.Name = "_DTFields_3"; //_DTFields_2.OcxState = CType(resources.GetObject("_DTFields_2.OcxState"), System.Windows.Forms.AxHost.State) this._DTFields_2.Size = new System.Drawing.Size(130, 21); this._DTFields_2.Location = new System.Drawing.Point(104, 112); this._DTFields_2.TabIndex = 19; this._DTFields_2.Name = "_DTFields_2"; this._chkFields_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkFields_2.Text = "Only for Specific Time"; this._chkFields_2.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_2.Size = new System.Drawing.Size(151, 17); this._chkFields_2.Location = new System.Drawing.Point(270, 152); this._chkFields_2.TabIndex = 16; this._chkFields_2.CausesValidation = true; this._chkFields_2.Enabled = true; this._chkFields_2.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_2.Appearance = System.Windows.Forms.Appearance.Normal; this._chkFields_2.TabStop = true; this._chkFields_2.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkFields_2.Visible = true; this._chkFields_2.Name = "_chkFields_2"; this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdDelete.Text = "&Delete"; this.cmdDelete.Size = new System.Drawing.Size(94, 25); this.cmdDelete.Location = new System.Drawing.Point(352, 176); this.cmdDelete.TabIndex = 14; this.cmdDelete.TabStop = false; this.cmdDelete.BackColor = System.Drawing.SystemColors.Control; this.cmdDelete.CausesValidation = true; this.cmdDelete.Enabled = true; this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDelete.Name = "cmdDelete"; this.cmdAdd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdAdd.Text = "&Add"; this.cmdAdd.Size = new System.Drawing.Size(94, 25); this.cmdAdd.Location = new System.Drawing.Point(2, 176); this.cmdAdd.TabIndex = 13; this.cmdAdd.TabStop = false; this.cmdAdd.BackColor = System.Drawing.SystemColors.Control; this.cmdAdd.CausesValidation = true; this.cmdAdd.Enabled = true; this.cmdAdd.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdAdd.Cursor = System.Windows.Forms.Cursors.Default; this.cmdAdd.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdAdd.Name = "cmdAdd"; this.lvPromotion.Size = new System.Drawing.Size(445, 250); this.lvPromotion.Location = new System.Drawing.Point(2, 206); this.lvPromotion.TabIndex = 11; this.lvPromotion.View = System.Windows.Forms.View.Details; this.lvPromotion.LabelWrap = true; this.lvPromotion.HideSelection = false; this.lvPromotion.FullRowSelect = true; this.lvPromotion.GridLines = true; this.lvPromotion.ForeColor = System.Drawing.SystemColors.WindowText; this.lvPromotion.BackColor = System.Drawing.SystemColors.Window; this.lvPromotion.LabelEdit = true; this.lvPromotion.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lvPromotion.Name = "lvPromotion"; this._chkFields_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkFields_1.Text = "Disabled:"; this._chkFields_1.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_1.Size = new System.Drawing.Size(64, 13); this._chkFields_1.Location = new System.Drawing.Point(54, 138); this._chkFields_1.TabIndex = 7; this._chkFields_1.CausesValidation = true; this._chkFields_1.Enabled = true; this._chkFields_1.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_1.Appearance = System.Windows.Forms.Appearance.Normal; this._chkFields_1.TabStop = true; this._chkFields_1.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkFields_1.Visible = true; this._chkFields_1.Name = "_chkFields_1"; this._chkFields_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_0.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkFields_0.Text = "Apply Only to POS Channel"; this._chkFields_0.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_0.Size = new System.Drawing.Size(151, 13); this._chkFields_0.Location = new System.Drawing.Point(270, 138); this._chkFields_0.TabIndex = 8; this._chkFields_0.CausesValidation = true; this._chkFields_0.Enabled = true; this._chkFields_0.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_0.Appearance = System.Windows.Forms.Appearance.Normal; this._chkFields_0.TabStop = true; this._chkFields_0.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkFields_0.Visible = true; this._chkFields_0.Name = "_chkFields_0"; //_DTFields_0.OcxState = CType(resources.GetObject("_DTFields_0.OcxState"), System.Windows.Forms.AxHost.State) this._DTFields_0.Size = new System.Drawing.Size(130, 22); this._DTFields_0.Location = new System.Drawing.Point(105, 87); this._DTFields_0.TabIndex = 4; this._DTFields_0.Name = "_DTFields_0"; this._txtFields_0.AutoSize = false; this._txtFields_0.Size = new System.Drawing.Size(315, 19); this._txtFields_0.Location = new System.Drawing.Point(105, 66); this._txtFields_0.TabIndex = 2; this._txtFields_0.AcceptsReturn = true; this._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_0.BackColor = System.Drawing.SystemColors.Window; this._txtFields_0.CausesValidation = true; this._txtFields_0.Enabled = true; this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_0.HideSelection = true; this._txtFields_0.ReadOnly = false; this._txtFields_0.MaxLength = 0; this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_0.Multiline = false; this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_0.TabStop = true; this._txtFields_0.Visible = true; this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_0.Name = "_txtFields_0"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(455, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 10; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrint.Text = "&Print"; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.Location = new System.Drawing.Point(192, 3); this.cmdPrint.TabIndex = 15; this.cmdPrint.TabStop = false; this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.CausesValidation = true; this.cmdPrint.Enabled = true; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Name = "cmdPrint"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(369, 3); this.cmdClose.TabIndex = 12; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.TabIndex = 9; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; //_DTFields_1.OcxState = CType(resources.GetObject("_DTFields_1.OcxState"), System.Windows.Forms.AxHost.State) this._DTFields_1.Size = new System.Drawing.Size(130, 22); this._DTFields_1.Location = new System.Drawing.Point(291, 87); this._DTFields_1.TabIndex = 6; this._DTFields_1.Name = "_DTFields_1"; this.Label2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.Label2.Text = "To Time:"; this.Label2.Size = new System.Drawing.Size(51, 15); this.Label2.Location = new System.Drawing.Point(238, 116); this.Label2.TabIndex = 18; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.Enabled = true; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.Label1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.Label1.Text = "From Time:"; this.Label1.Size = new System.Drawing.Size(57, 17); this.Label1.Location = new System.Drawing.Point(48, 116); this.Label1.TabIndex = 17; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_1.Text = "End Date:"; this._lblLabels_1.Size = new System.Drawing.Size(48, 13); this._lblLabels_1.Location = new System.Drawing.Point(240, 90); this._lblLabels_1.TabIndex = 5; this._lblLabels_1.BackColor = System.Drawing.Color.Transparent; this._lblLabels_1.Enabled = true; this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_1.UseMnemonic = true; this._lblLabels_1.Visible = true; this._lblLabels_1.AutoSize = true; this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_1.Name = "_lblLabels_1"; this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_0.Text = "Start Date:"; this._lblLabels_0.Size = new System.Drawing.Size(51, 13); this._lblLabels_0.Location = new System.Drawing.Point(52, 90); this._lblLabels_0.TabIndex = 3; this._lblLabels_0.BackColor = System.Drawing.Color.Transparent; this._lblLabels_0.Enabled = true; this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_0.UseMnemonic = true; this._lblLabels_0.Visible = true; this._lblLabels_0.AutoSize = true; this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_0.Name = "_lblLabels_0"; this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_38.Text = "Promotion Name:"; this._lblLabels_38.Size = new System.Drawing.Size(81, 13); this._lblLabels_38.Location = new System.Drawing.Point(19, 69); this._lblLabels_38.TabIndex = 1; this._lblLabels_38.BackColor = System.Drawing.Color.Transparent; this._lblLabels_38.Enabled = true; this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_38.UseMnemonic = true; this._lblLabels_38.Visible = true; this._lblLabels_38.AutoSize = true; this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_38.Name = "_lblLabels_38"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(415, 112); this._Shape1_2.Location = new System.Drawing.Point(15, 60); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Text = "&1. General"; this._lbl_5.Size = new System.Drawing.Size(60, 13); this._lbl_5.Location = new System.Drawing.Point(15, 45); this._lbl_5.TabIndex = 0; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = true; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this.Controls.Add(_DTFields_3); this.Controls.Add(_DTFields_2); this.Controls.Add(_chkFields_2); this.Controls.Add(cmdDelete); this.Controls.Add(cmdAdd); this.Controls.Add(lvPromotion); this.Controls.Add(_chkFields_1); this.Controls.Add(_chkFields_0); this.Controls.Add(_DTFields_0); this.Controls.Add(_txtFields_0); this.Controls.Add(picButtons); this.Controls.Add(_DTFields_1); this.Controls.Add(Label2); this.Controls.Add(Label1); this.Controls.Add(_lblLabels_1); this.Controls.Add(_lblLabels_0); this.Controls.Add(_lblLabels_38); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.Controls.Add(_lbl_5); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdPrint); this.picButtons.Controls.Add(cmdClose); this.picButtons.Controls.Add(cmdCancel); //Me.DTFields.SetIndex(_DTFields_3, CType(3, Short)) //Me.DTFields.SetIndex(_DTFields_2, CType(2, Short)) //Me.DTFields.SetIndex(_DTFields_0, CType(0, Short)) //Me.DTFields.SetIndex(_DTFields_1, CType(1, Short)) //Me.chkFields.SetIndex(_chkFields_2, CType(2, Short)) //Me.chkFields.SetIndex(_chkFields_1, CType(1, Short)) //Me.chkFields.SetIndex(_chkFields_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) //Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short)) //Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short)) //Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short)) //Me.txtFields.SetIndex(_txtFields_0, CType(0, Short)) this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.chkFields, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.DTFields, System.ComponentModel.ISupportInitialize).EndInit() ((System.ComponentModel.ISupportInitialize)this._DTFields_1).EndInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_0).EndInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_2).EndInit(); ((System.ComponentModel.ISupportInitialize)this._DTFields_3).EndInit(); this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Redis { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// PatchSchedulesOperations operations. /// </summary> internal partial class PatchSchedulesOperations : IServiceOperations<RedisManagementClient>, IPatchSchedulesOperations { /// <summary> /// Initializes a new instance of the PatchSchedulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PatchSchedulesOperations(RedisManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RedisManagementClient /// </summary> public RedisManagementClient Client { get; private set; } /// <summary> /// Create or replace the patching schedule for redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters to set patch schedules for redis cache. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RedisPatchSchedulesResponse>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, RedisPatchSchedulesRequest parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("name", name); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RedisPatchSchedulesResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<RedisPatchSchedulesResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the patching schedule for redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); 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 patching schedule for redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RedisPatchSchedulesResponse>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.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("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/Redis/{name}/patchSchedules/default").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RedisPatchSchedulesResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<RedisPatchSchedulesResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright(c) DEVSENSE s.r.o. // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using NameTuple = System.Tuple<Devsense.PHP.Syntax.VariableNameRef, Devsense.PHP.Syntax.Ast.Expression>; namespace Devsense.PHP.Syntax.Ast { #region ActualParam /// <summary> /// Represents a single argument passed to <see cref="FunctionCall"/>. /// </summary> public struct ActualParam : ITreeNode { [Flags] public enum Flags : byte { Default = 0, IsByRef = 1, IsUnpack = 2, /// <summary> /// Flag annotating the "..." special argument making making the containing call converted to a closure. /// Introduced in PHP 8.1: https://wiki.php.net/rfc/first_class_callable_syntax /// </summary> IsCallableConvert = 4, } /// <summary> /// Either <see cref="Expression"/> or <see cref="Tuple{VariableNameRef, Expression}"/>. /// </summary> object _obj; /// <summary> /// Argument expression. /// </summary> public Expression Expression { get { if (_obj is Expression expr) return expr; if (_obj is NameTuple t) return t.Item2; Debug.Assert(_obj == null); return null; } } /// <summary> /// Named argument, if specified. /// </summary> public VariableNameRef? Name { get { if (_obj is NameTuple t) return t.Item1; return null; } } /// <summary> /// Flags describing use of the parameter. /// </summary> readonly Flags _flags; /// <summary> /// The parameter span. /// </summary> public Text.Span Span { get { if (_spanStart >= 0) { if (Expression != null && Expression.Span.IsValid) { return Text.Span.FromBounds(_spanStart, Expression.Span.End); } if (IsCallableConvert) { return new Text.Span(_spanStart, 3); // "..." } } return Text.Span.Invalid; } } readonly int _spanStart; /// <summary> /// Gets value indicating the parameter is not empty (<see cref="Expression"/> is not a <c>null</c> reference). /// </summary> public bool Exists => Expression != null; /// <summary> /// Gets value indicating whether the parameter is prefixed by <c>&amp;</c> character. /// </summary> public bool Ampersand => (_flags & Flags.IsByRef) != 0; /// <summary> /// Gets value indicating whether the parameter is passed with <c>...</c> prefix and so it has to be unpacked before passing to the function call. /// </summary> public bool IsUnpack => (_flags & Flags.IsUnpack) != 0; /// <summary> /// Flag annotating the "..." special argument making making the containing call converted to a closure. /// </summary> public bool IsCallableConvert => (_flags & Flags.IsCallableConvert) != 0; /// <summary> /// Gets value indicating it's a named argument. /// </summary> public bool IsNamedArgument => Name.HasValue; public ActualParam(Text.Span p, Expression param) : this(p, param, Flags.Default, default) { } public ActualParam(Text.Span p, Expression param, Flags flags, VariableNameRef? nameOpt = default) { _flags = flags; _spanStart = p.Start; _obj = nameOpt.HasValue ? (object)new NameTuple(nameOpt.Value, param) : param; } /// <summary> /// Call the right Visit* method on the given Visitor object. /// </summary> /// <param name="visitor">Visitor to be called.</param> public void VisitMe(TreeVisitor visitor) { visitor.VisitActualParam(this); } } #endregion #region NamedActualParam [Obsolete("This is not used and will be removed.")] public sealed class NamedActualParam : LangElement { public Expression/*!*/ Expression { get { return expression; } } internal Expression/*!*/ expression; public VariableName Name { get { return name; } } private VariableName name; public NamedActualParam(Text.Span span, string name, Expression/*!*/ expression) : base(span) { this.name = new VariableName(name); this.expression = expression; } /// <summary> /// Call the right Visit* method on the given Visitor object. /// </summary> /// <param name="visitor">Visitor to be called.</param> public override void VisitMe(TreeVisitor visitor) { throw new NotSupportedException(); //visitor.VisitNamedActualParam(this); } } #endregion #region CallSignature public struct CallSignature { public static CallSignature Empty => new CallSignature(ArrayUtils.Empty<ActualParam>(), Text.Span.Invalid); /// <summary> /// Creates a special signature that is treated like a conversion of the containing call to a Closure. /// Introduced in PHP 8.1: https://wiki.php.net/rfc/first_class_callable_syntax /// </summary> /// <param name="span">Span of the ellipsis '...'.</param> /// <returns>Single item list with parameter denoting it's a callable convert signature.</returns> public static List<ActualParam> CreateCallableConvert(Text.Span span) => new List<ActualParam>() { new ActualParam(span, null, ActualParam.Flags.IsCallableConvert) }; /// <summary> /// Gets value indicating the object is treated like a conversion of the containing call to a Closure. /// Introduced in PHP 8.1: https://wiki.php.net/rfc/first_class_callable_syntax /// </summary> public bool IsCallableConvert => Parameters != null && Parameters.Length == 1 && Parameters[0].IsCallableConvert; /// <summary> /// Gets value indicating the signature is empty. /// </summary> public bool IsEmpty => Parameters == null || Parameters.Length == 0; /// <summary> /// List of actual parameters (<see cref="ActualParam"/> nodes). /// </summary> public ActualParam[]/*!*/ Parameters { get; } /// <summary> /// Signature position including the parentheses. /// </summary> public Text.Span Span { get; set; } ///// <summary> ///// List of generic parameters. ///// </summary> //public TypeRef[]/*!*/ GenericParams //{ // get // { // return this.GetProperty<TypeRef[]>() ?? EmptyArray<TypeRef>.Instance; // } // set // { // if (value != null && value.Length != 0) // { // this.SetProperty<TypeRef[]>(value); // } // else // { // this.Properties.RemoveProperty<TypeRef[]>(); // } // } //} /// <summary> /// Initialize new instance of <see cref="CallSignature"/>. /// </summary> /// <param name="parameters">List of parameters.</param> /// <param name="span">Signature position.</param> public CallSignature(IList<ActualParam> parameters, Text.Span span) { this.Parameters = (parameters ?? throw new ArgumentNullException(nameof(parameters))).AsArray(); //this.GenericParams = (genericParams != null && genericParams.Count != 0) ? genericParams.AsArray() : null; this.Span = span; } } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Linq; using System.Runtime.CompilerServices; namespace System.Data.Linq { using System.Data.Linq.Mapping; using System.Data.Linq.Provider; internal class CommonDataServices : IDataServices { DataContext context; MetaModel metaModel; IdentityManager identifier; ChangeTracker tracker; ChangeDirector director; bool hasCachedObjects; Dictionary<MetaDataMember, IDeferredSourceFactory> factoryMap; internal CommonDataServices(DataContext context, MetaModel model) { this.context = context; this.metaModel = model; bool asReadOnly = !context.ObjectTrackingEnabled; this.identifier = IdentityManager.CreateIdentityManager(asReadOnly); this.tracker = ChangeTracker.CreateChangeTracker(this, asReadOnly); this.director = ChangeDirector.CreateChangeDirector(context); this.factoryMap = new Dictionary<MetaDataMember, IDeferredSourceFactory>(); } public DataContext Context { get { return this.context; } } public MetaModel Model { get { return this.metaModel; } } internal void SetModel(MetaModel model) { this.metaModel = model; } internal IdentityManager IdentityManager { get { return this.identifier; } } internal ChangeTracker ChangeTracker { get { return this.tracker; } } internal ChangeDirector ChangeDirector { get { return this.director; } } internal IEnumerable<RelatedItem> GetParents(MetaType type, object item) { return this.GetRelations(type, item, true); } internal IEnumerable<RelatedItem> GetChildren(MetaType type, object item) { return this.GetRelations(type, item, false); } private IEnumerable<RelatedItem> GetRelations(MetaType type, object item, bool isForeignKey) { foreach (MetaDataMember mm in type.PersistentDataMembers) { if (mm.IsAssociation) { MetaType otherType = mm.Association.OtherType; if (mm.Association.IsForeignKey == isForeignKey) { object value = null; if (mm.IsDeferred) { value = mm.DeferredValueAccessor.GetBoxedValue(item); } else { value = mm.StorageAccessor.GetBoxedValue(item); } if (value != null) { if (mm.Association.IsMany) { IEnumerable list = (IEnumerable)value; foreach (object otherItem in list) { yield return new RelatedItem(otherType.GetInheritanceType(otherItem.GetType()), otherItem); } } else { yield return new RelatedItem(otherType.GetInheritanceType(value.GetType()), value); } } } } } } internal void ResetServices() { hasCachedObjects = false; bool asReadOnly = !context.ObjectTrackingEnabled; this.identifier = IdentityManager.CreateIdentityManager(asReadOnly); this.tracker = ChangeTracker.CreateChangeTracker(this, asReadOnly); this.factoryMap = new Dictionary<MetaDataMember, IDeferredSourceFactory>(); } internal static object[] GetKeyValues(MetaType type, object instance) { List<object> keyValues = new List<object>(); foreach (MetaDataMember mm in type.IdentityMembers) { keyValues.Add(mm.MemberAccessor.GetBoxedValue(instance)); } return keyValues.ToArray(); } internal static object[] GetForeignKeyValues(MetaAssociation association, object instance) { List<object> keyValues = new List<object>(); foreach(MetaDataMember mm in association.ThisKey) { keyValues.Add(mm.MemberAccessor.GetBoxedValue(instance)); } return keyValues.ToArray(); } internal object GetCachedObject(MetaType type, object[] keyValues) { if( type == null ) { throw Error.ArgumentNull("type"); } if (!type.IsEntity) { return null; } return this.identifier.Find(type, keyValues); } internal object GetCachedObjectLike(MetaType type, object instance) { if( type == null ) { throw Error.ArgumentNull("type"); } if (!type.IsEntity) { return null; } return this.identifier.FindLike(type, instance); } public bool IsCachedObject(MetaType type, object instance) { if( type == null ) { throw Error.ArgumentNull("type"); } if (!type.IsEntity) { return false; } return this.identifier.FindLike(type, instance) == instance; } public object InsertLookupCachedObject(MetaType type, object instance) { if( type == null ) { throw Error.ArgumentNull("type"); } hasCachedObjects = true; // flag that we have cached objects if (!type.IsEntity) { return instance; } return this.identifier.InsertLookup(type, instance); } public bool RemoveCachedObjectLike(MetaType type, object instance) { if (type == null) { throw Error.ArgumentNull("type"); } if (!type.IsEntity) { return false; } return this.identifier.RemoveLike(type, instance); } public void OnEntityMaterialized(MetaType type, object instance) { if (type == null) { throw Error.ArgumentNull("type"); } this.tracker.FastTrack(instance); if (type.HasAnyLoadMethod) { SendOnLoaded(type, instance); } } private static void SendOnLoaded(MetaType type, object item) { if (type != null) { SendOnLoaded(type.InheritanceBase, item); if (type.OnLoadedMethod != null) { try { type.OnLoadedMethod.Invoke(item, new object[] { }); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } } } } /// <summary> /// Returns a query for the entity indicated by the specified key. /// </summary> internal Expression GetObjectQuery(MetaType type, object[] keyValues) { if (type == null) { throw Error.ArgumentNull("type"); } if (keyValues == null) { throw Error.ArgumentNull("keyValues"); } return this.GetObjectQuery(type, BuildKeyExpressions(keyValues, type.IdentityMembers)); } internal Expression GetObjectQuery(MetaType type, Expression[] keyValues) { ITable table = this.context.GetTable(type.InheritanceRoot.Type); ParameterExpression serverItem = Expression.Parameter(table.ElementType, "p"); // create a where expression including all the identity members Expression whereExpression = null; for (int i = 0, n = type.IdentityMembers.Count; i < n; i++) { MetaDataMember metaMember = type.IdentityMembers[i]; Expression memberExpression = (metaMember.Member is FieldInfo) ? Expression.Field(serverItem, (FieldInfo)metaMember.Member) : Expression.Property(serverItem, (PropertyInfo)metaMember.Member); Expression memberEqualityExpression = Expression.Equal(memberExpression, keyValues[i]); whereExpression = (whereExpression != null) ? Expression.And(whereExpression, memberEqualityExpression) : memberEqualityExpression; } return Expression.Call(typeof(Queryable), "Where", new Type[] { table.ElementType }, table.Expression, Expression.Lambda(whereExpression, serverItem)); } internal Expression GetDataMemberQuery(MetaDataMember member, Expression[] keyValues) { if (member == null) throw Error.ArgumentNull("member"); if (keyValues == null) throw Error.ArgumentNull("keyValues"); if (member.IsAssociation) { MetaAssociation association = member.Association; Type rootType = association.ThisMember.DeclaringType.InheritanceRoot.Type; Expression thisSource = Expression.Constant(context.GetTable(rootType)); if (rootType != association.ThisMember.DeclaringType.Type) { thisSource = Expression.Call(typeof(Enumerable), "Cast", new Type[] { association.ThisMember.DeclaringType.Type }, thisSource); } Expression thisInstance = Expression.Call(typeof(Enumerable), "FirstOrDefault", new Type[] { association.ThisMember.DeclaringType.Type }, System.Data.Linq.SqlClient.Translator.WhereClauseFromSourceAndKeys(thisSource, association.ThisKey.ToArray(), keyValues) ); Expression otherSource = Expression.Constant(context.GetTable(association.OtherType.InheritanceRoot.Type)); if (association.OtherType.Type!=association.OtherType.InheritanceRoot.Type) { otherSource = Expression.Call(typeof(Enumerable), "Cast", new Type[] { association.OtherType.Type }, otherSource); } Expression expr = System.Data.Linq.SqlClient.Translator.TranslateAssociation( this.context, association, otherSource, keyValues, thisInstance ); return expr; } else { Expression query = this.GetObjectQuery(member.DeclaringType, keyValues); Type elementType = System.Data.Linq.SqlClient.TypeSystem.GetElementType(query.Type); ParameterExpression p = Expression.Parameter(elementType, "p"); Expression e = p; if (elementType != member.DeclaringType.Type) e = Expression.Convert(e, member.DeclaringType.Type); Expression mem = (member.Member is PropertyInfo) ? Expression.Property(e, (PropertyInfo)member.Member) : Expression.Field(e, (FieldInfo)member.Member); LambdaExpression selector = Expression.Lambda(mem, p); return Expression.Call(typeof(Queryable), "Select", new Type[] { elementType, selector.Body.Type }, query, selector); } } private static Expression[] BuildKeyExpressions(object[] keyValues, ReadOnlyCollection<MetaDataMember> keyMembers) { Expression[] keyValueExpressions = new Expression[keyValues.Length]; for (int i = 0, n = keyMembers.Count; i < n; i++) { MetaDataMember metaMember = keyMembers[i]; Expression keyValueExpression = Expression.Constant(keyValues[i], metaMember.Type); keyValueExpressions[i] = keyValueExpression; } return keyValueExpressions; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public IDeferredSourceFactory GetDeferredSourceFactory(MetaDataMember member) { if (member == null) { throw Error.ArgumentNull("member"); } IDeferredSourceFactory factory; if (this.factoryMap.TryGetValue(member, out factory)) { return factory; } Type elemType = member.IsAssociation && member.Association.IsMany ? System.Data.Linq.SqlClient.TypeSystem.GetElementType(member.Type) : member.Type; factory = (IDeferredSourceFactory) Activator.CreateInstance( typeof(DeferredSourceFactory<>).MakeGenericType(elemType), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { member, this }, null ); this.factoryMap.Add(member, factory); return factory; } class DeferredSourceFactory<T> : IDeferredSourceFactory { MetaDataMember member; CommonDataServices services; ICompiledQuery query; bool refersToPrimaryKey; T[] empty; internal DeferredSourceFactory(MetaDataMember member, CommonDataServices services) { this.member = member; this.services = services; this.refersToPrimaryKey = this.member.IsAssociation && this.member.Association.OtherKeyIsPrimaryKey; this.empty = new T[] { }; } public IEnumerable CreateDeferredSource(object instance) { if (instance == null) throw Error.ArgumentNull("instance"); return new DeferredSource(this, instance); } public IEnumerable CreateDeferredSource(object[] keyValues) { if (keyValues == null) throw Error.ArgumentNull("keyValues"); return new DeferredSource(this, keyValues); } private IEnumerator<T> Execute(object instance) { ReadOnlyCollection<MetaDataMember> keys = null; if (this.member.IsAssociation) { keys = this.member.Association.ThisKey; } else { keys = this.member.DeclaringType.IdentityMembers; } object[] keyValues = new object[keys.Count]; for (int i = 0, n = keys.Count; i < n; i++) { object value = keys[i].StorageAccessor.GetBoxedValue(instance); keyValues[i] = value; } if (this.HasNullForeignKey(keyValues)) { return ((IEnumerable<T>)this.empty).GetEnumerator(); } T cached; if (this.TryGetCachedObject(keyValues, out cached)) { return ((IEnumerable<T>)(new T[] { cached })).GetEnumerator(); } if (this.member.LoadMethod != null) { try { object result = this.member.LoadMethod.Invoke(this.services.Context, new object[] { instance }); if (typeof(T).IsAssignableFrom(this.member.LoadMethod.ReturnType)) { return ((IEnumerable<T>)new T[] { (T)result }).GetEnumerator(); } else { return ((IEnumerable<T>)result).GetEnumerator(); } } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } throw; } } else { return this.ExecuteKeyQuery(keyValues); } } private IEnumerator<T> ExecuteKeys(object[] keyValues) { if (this.HasNullForeignKey(keyValues)) { return ((IEnumerable<T>)this.empty).GetEnumerator(); } T cached; if (this.TryGetCachedObject(keyValues, out cached)) { return ((IEnumerable<T>)(new T[] { cached })).GetEnumerator(); } return this.ExecuteKeyQuery(keyValues); } private bool HasNullForeignKey(object[] keyValues) { if (this.refersToPrimaryKey) { bool keyHasNull = false; for (int i = 0, n = keyValues.Length; i < n; i++) { keyHasNull |= keyValues[i] == null; } if (keyHasNull) { return true; } } return false; } private bool TryGetCachedObject(object[] keyValues, out T cached) { cached = default(T); if (this.refersToPrimaryKey) { // look to see if we already have this object in the identity cache MetaType mt = this.member.IsAssociation ? this.member.Association.OtherType : this.member.DeclaringType; object obj = this.services.GetCachedObject(mt, keyValues); if (obj != null) { cached = (T)obj; return true; } } return false; } private IEnumerator<T> ExecuteKeyQuery(object[] keyValues) { if (this.query == null) { ParameterExpression p = Expression.Parameter(typeof(object[]), "keys"); Expression[] keyExprs = new Expression[keyValues.Length]; ReadOnlyCollection<MetaDataMember> members = this.member.IsAssociation ? this.member.Association.OtherKey : this.member.DeclaringType.IdentityMembers; for (int i = 0, n = keyValues.Length; i < n; i++) { MetaDataMember mm = members[i]; keyExprs[i] = Expression.Convert( #pragma warning disable 618 // Disable the 'obsolete' warning Expression.ArrayIndex(p, Expression.Constant(i)), #pragma warning restore 618 mm.Type ); } Expression q = this.services.GetDataMemberQuery(this.member, keyExprs); LambdaExpression lambda = Expression.Lambda(q, p); this.query = this.services.Context.Provider.Compile(lambda); } return ((IEnumerable<T>)this.query.Execute(this.services.Context.Provider, new object[] { keyValues }).ReturnValue).GetEnumerator(); } class DeferredSource : IEnumerable<T>, IEnumerable { DeferredSourceFactory<T> factory; object instance; internal DeferredSource(DeferredSourceFactory<T> factory, object instance) { this.factory = factory; this.instance = instance; } public IEnumerator<T> GetEnumerator() { object[] keyValues = this.instance as object[]; if (keyValues != null) { return this.factory.ExecuteKeys(keyValues); } return this.factory.Execute(this.instance); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } /// <summary> /// Returns true if any objects have been added to the identity cache. If /// object tracking is disabled, this still returns true if any attempts /// where made to cache an object. Thus regardless of object tracking mode, /// this can be used as an indicator as to whether any result returning queries /// have been executed. /// </summary> internal bool HasCachedObjects { get { return this.hasCachedObjects; } } public object GetCachedObject(Expression query) { if (query == null) return null; MethodCallExpression mc = query as MethodCallExpression; if (mc == null || mc.Arguments.Count < 1 || mc.Arguments.Count > 2) return null; if (mc.Method.DeclaringType != typeof(Queryable)) { return null; } switch (mc.Method.Name) { case "Where": case "First": case "FirstOrDefault": case "Single": case "SingleOrDefault": break; default: return null; } if (mc.Arguments.Count == 1) { // If it is something like // context.Customers.Where(c => c.ID = 123).First() // then it is equivalent of // context.Customers.First(c => c.ID = 123) // hence reduce to context.Customers.Where(c => c.ID = 123) and process the remaining query return GetCachedObject(mc.Arguments[0]); } UnaryExpression quote = mc.Arguments[1] as UnaryExpression; if (quote == null || quote.NodeType != ExpressionType.Quote) return null; LambdaExpression pred = quote.Operand as LambdaExpression; if (pred == null) return null; ConstantExpression cex = mc.Arguments[0] as ConstantExpression; if (cex == null) return null; ITable t = cex.Value as ITable; if (t == null) return null; Type elementType = System.Data.Linq.SqlClient.TypeSystem.GetElementType(query.Type); if (elementType != t.ElementType) return null; MetaTable metaTable = this.metaModel.GetTable(t.ElementType); object[] keyValues = this.GetKeyValues(metaTable.RowType, pred); if (keyValues != null) { return this.GetCachedObject(metaTable.RowType, keyValues); } return null; } internal object[] GetKeyValues(MetaType type, LambdaExpression predicate) { if (predicate == null) throw Error.ArgumentNull("predicate"); if (predicate.Parameters.Count != 1) return null; Dictionary<MetaDataMember, object> keys = new Dictionary<MetaDataMember, object>(); if (this.GetKeysFromPredicate(type, keys, predicate.Body) && keys.Count == type.IdentityMembers.Count) { object[] values = keys.OrderBy(kv => kv.Key.Ordinal).Select(kv => kv.Value).ToArray(); return values; } return null; } private bool GetKeysFromPredicate(MetaType type, Dictionary<MetaDataMember, object> keys, Expression expr) { BinaryExpression bex = expr as BinaryExpression; if (bex == null) { MethodCallExpression mex = expr as MethodCallExpression; if (mex != null && mex.Method.Name == "op_Equality" && mex.Arguments.Count == 2) { bex = Expression.Equal(mex.Arguments[0], mex.Arguments[1]); } else { return false; } } switch (bex.NodeType) { case ExpressionType.And: return this.GetKeysFromPredicate(type, keys, bex.Left) && this.GetKeysFromPredicate(type, keys, bex.Right); case ExpressionType.Equal: return GetKeyFromPredicate(type, keys, bex.Left, bex.Right) || GetKeyFromPredicate(type, keys, bex.Right, bex.Left); default: return false; } } private static bool GetKeyFromPredicate(MetaType type, Dictionary<MetaDataMember, object> keys, Expression mex, Expression vex) { MemberExpression memex = mex as MemberExpression; if (memex == null || memex.Expression == null || memex.Expression.NodeType != ExpressionType.Parameter || memex.Expression.Type != type.Type) { return false; } if (!type.Type.IsAssignableFrom(memex.Member.ReflectedType) && !memex.Member.ReflectedType.IsAssignableFrom(type.Type)) { return false; } MetaDataMember mm = type.GetDataMember(memex.Member); if (!mm.IsPrimaryKey) { return false; } if (keys.ContainsKey(mm)) { return false; } ConstantExpression cex = vex as ConstantExpression; if (cex != null) { keys.Add(mm, cex.Value); return true; } InvocationExpression ie = vex as InvocationExpression; if (ie != null && ie.Arguments != null && ie.Arguments.Count == 0) { ConstantExpression ce = ie.Expression as ConstantExpression; if (ce != null) { keys.Add(mm, ((Delegate)ce.Value).DynamicInvoke(new object[] {})); return true; } } return false; } /// <summary> /// Either returns the object from cache if it is in cache, or /// queries for it. /// </summary> internal object GetObjectByKey(MetaType type, object[] keyValues) { // first check the cache object target = GetCachedObject(type, keyValues); if (target == null) { // no cached value, so query for it target = ((IEnumerable)this.context.Provider.Execute(this.GetObjectQuery(type, keyValues)).ReturnValue).OfType<object>().SingleOrDefault(); } return target; } } internal struct RelatedItem { internal MetaType Type; internal object Item; internal RelatedItem(MetaType type, object item) { this.Type = type; this.Item = item; } } }
/* * 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.Collections.Generic; using System.Text; namespace OpenSim.Region.UserStatistics { public static class HTMLUtil { public static void TR_O(ref StringBuilder o, string pclass) { o.Append("<tr"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(">\n\t"); } public static void TR_C(ref StringBuilder o) { o.Append("</tr>\n"); } public static void TD_O(ref StringBuilder o, string pclass) { TD_O(ref o, pclass, 0, 0); } public static void TD_O(ref StringBuilder o, string pclass, int rowspan, int colspan) { o.Append("<td"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } if (rowspan > 1) { o.Append(" rowspan=\""); o.Append(rowspan); o.Append("\""); } if (colspan > 1) { o.Append(" colspan=\""); o.Append(colspan); o.Append("\""); } o.Append(">"); } public static void TD_C(ref StringBuilder o) { o.Append("</td>"); } public static void TABLE_O(ref StringBuilder o, string pclass) { o.Append("<table"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(">\n\t"); } public static void TABLE_C(ref StringBuilder o) { o.Append("</table>\n"); } public static void BLOCKQUOTE_O(ref StringBuilder o, string pclass) { o.Append("<blockquote"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void BLOCKQUOTE_C(ref StringBuilder o) { o.Append("</blockquote>\n"); } public static void BR(ref StringBuilder o) { o.Append("<br />\n"); } public static void HR(ref StringBuilder o, string pclass) { o.Append("<hr"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void UL_O(ref StringBuilder o, string pclass) { o.Append("<ul"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void UL_C(ref StringBuilder o) { o.Append("</ul>\n"); } public static void OL_O(ref StringBuilder o, string pclass) { o.Append("<ol"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void OL_C(ref StringBuilder o) { o.Append("</ol>\n"); } public static void LI_O(ref StringBuilder o, string pclass) { o.Append("<li"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void LI_C(ref StringBuilder o) { o.Append("</li>\n"); } public static void GenericClass(ref StringBuilder o, string pclass) { o.Append(" class=\""); o.Append(pclass); o.Append("\""); } public static void InsertProtoTypeAJAX(ref StringBuilder o) { o.Append("<script type=\"text/javascript\" src=\"prototype.js\"></script>\n"); o.Append("<script type=\"text/javascript\" src=\"updater.js\"></script>\n"); } public static void InsertPeriodicUpdaters(ref StringBuilder o, string[] divID, int[] seconds, string[] reportfrag) { o.Append("<script type=\"text/javascript\">\n"); o.Append( @" // <![CDATA[ document.observe('dom:loaded', function() { /* first arg : div to update second arg : interval to poll in seconds third arg : file to get data */ "); for (int i = 0; i < divID.Length; i++) { o.Append("new updater('"); o.Append(divID[i]); o.Append("', "); o.Append(seconds[i]); o.Append(", '"); o.Append(reportfrag[i]); o.Append("');\n"); } o.Append(@" }); // ]]> </script>"); } public static void HtmlHeaders_O(ref StringBuilder o) { o.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); o.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"nl\">"); o.Append("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />"); } public static void HtmlHeaders_C(ref StringBuilder o) { o.Append("</HEAD>"); o.Append("<BODY>"); } public static void AddReportLinks(ref StringBuilder o, Dictionary<string, IStatsController> reports, string pClass) { int repcount = 0; foreach (string str in reports.Keys) { if (reports[str].ReportName.Length > 0) { if (repcount > 0) { o.Append("|&nbsp;&nbsp;"); } A(ref o, reports[str].ReportName, str, pClass); o.Append("&nbsp;&nbsp;"); repcount++; } } } public static void A(ref StringBuilder o, string linktext, string linkhref, string pClass) { o.Append("<A"); if (pClass.Length > 0) { GenericClass(ref o, pClass); } o.Append(" href=\""); o.Append(linkhref); o.Append("\">"); o.Append(linktext); o.Append("</A>"); } } }
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System; using System.Collections.Generic; using Gremlin.Net.Process.Remote; using Gremlin.Net.Process.Traversal.Strategy.Decoration; using Gremlin.Net.Structure; // THIS IS A GENERATED FILE - DO NOT MODIFY THIS FILE DIRECTLY - see pom.xml namespace Gremlin.Net.Process.Traversal { #pragma warning disable 1591 /// <summary> /// A <see cref="GraphTraversalSource" /> is the primary DSL of the Gremlin traversal machine. /// It provides access to all the configurations and steps for Turing complete graph computing. /// </summary> public class GraphTraversalSource { /// <summary> /// Gets or sets the traversal strategies associated with this graph traversal source. /// </summary> public ICollection<ITraversalStrategy> TraversalStrategies { get; set; } /// <summary> /// Gets or sets the <see cref="Traversal.Bytecode" /> associated with the current state of this graph traversal /// source. /// </summary> public Bytecode Bytecode { get; set; } /// <summary> /// Initializes a new instance of the <see cref="GraphTraversalSource" /> class. /// </summary> public GraphTraversalSource() : this(new List<ITraversalStrategy>(), new Bytecode()) { } /// <summary> /// Initializes a new instance of the <see cref="GraphTraversalSource" /> class. /// </summary> /// <param name="traversalStrategies">The traversal strategies associated with this graph traversal source.</param> /// <param name="bytecode"> /// The <see cref="Traversal.Bytecode" /> associated with the current state of this graph traversal /// source. /// </param> public GraphTraversalSource(ICollection<ITraversalStrategy> traversalStrategies, Bytecode bytecode) { TraversalStrategies = traversalStrategies; Bytecode = bytecode; } public GraphTraversalSource WithBulk(bool useBulk) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withBulk", useBulk); return source; } public GraphTraversalSource WithPath() { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withPath"); return source; } public GraphTraversalSource WithSack(object initialValue) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue); return source; } public GraphTraversalSource WithSack(object initialValue, IBinaryOperator mergeOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, mergeOperator); return source; } public GraphTraversalSource WithSack(object initialValue, IUnaryOperator splitOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, splitOperator); return source; } public GraphTraversalSource WithSack(object initialValue, IUnaryOperator splitOperator, IBinaryOperator mergeOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, splitOperator, mergeOperator); return source; } public GraphTraversalSource WithSack(ISupplier initialValue) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue); return source; } public GraphTraversalSource WithSack(ISupplier initialValue, IBinaryOperator mergeOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, mergeOperator); return source; } public GraphTraversalSource WithSack(ISupplier initialValue, IUnaryOperator splitOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, splitOperator); return source; } public GraphTraversalSource WithSack(ISupplier initialValue, IUnaryOperator splitOperator, IBinaryOperator mergeOperator) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSack", initialValue, splitOperator, mergeOperator); return source; } public GraphTraversalSource WithSideEffect(string key, object initialValue) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSideEffect", key, initialValue); return source; } public GraphTraversalSource WithSideEffect(string key, object initialValue, IBinaryOperator reducer) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSideEffect", key, initialValue, reducer); return source; } public GraphTraversalSource WithSideEffect(string key, ISupplier initialValue) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSideEffect", key, initialValue); return source; } public GraphTraversalSource WithSideEffect(string key, ISupplier initialValue, IBinaryOperator reducer) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.Bytecode.AddSource("withSideEffect", key, initialValue, reducer); return source; } public GraphTraversalSource WithStrategies(params ITraversalStrategy[] traversalStrategies) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); var args = new List<object>(0 + traversalStrategies.Length) {}; args.AddRange(traversalStrategies); source.Bytecode.AddSource("withStrategies", args.ToArray()); return source; } public GraphTraversalSource WithoutStrategies(params Type[] traversalStrategyClasses) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); var args = new List<object>(0 + traversalStrategyClasses.Length) {}; args.AddRange(traversalStrategyClasses); source.Bytecode.AddSource("withoutStrategies", args.ToArray()); return source; } [Obsolete("Use the Bindings class instead.", false)] public GraphTraversalSource WithBindings(object bindings) { return this; } /// <summary> /// Configures the <see cref="GraphTraversalSource" /> as a "remote" to issue the /// <see cref="GraphTraversal{SType, EType}" /> for execution elsewhere. /// </summary> /// <param name="remoteConnection"> /// The <see cref="IRemoteConnection" /> instance to use to submit the /// <see cref="GraphTraversal{SType, EType}" />. /// </param> /// <returns>A <see cref="GraphTraversalSource" /> configured to use the provided <see cref="IRemoteConnection" />.</returns> public GraphTraversalSource WithRemote(IRemoteConnection remoteConnection) { var source = new GraphTraversalSource(new List<ITraversalStrategy>(TraversalStrategies), new Bytecode(Bytecode)); source.TraversalStrategies.Add(new RemoteStrategy(remoteConnection)); return source; } /// <summary> /// Add a GraphComputer class used to execute the traversal. /// This adds a <see cref="VertexProgramStrategy" /> to the strategies. /// </summary> public GraphTraversalSource WithComputer(string graphComputer = null, int? workers = null, string persist = null, string result = null, ITraversal vertices = null, ITraversal edges = null, Dictionary<string, dynamic> configuration = null) { return WithStrategies(new VertexProgramStrategy(graphComputer, workers, persist, result, vertices, edges, configuration)); } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the E step to that /// traversal. /// </summary> public GraphTraversal<Edge, Edge> E(params object[] edgesIds) { var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode)); var args = new List<object>(0 + edgesIds.Length) {}; args.AddRange(edgesIds); traversal.Bytecode.AddStep("E", args.ToArray()); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the V step to that /// traversal. /// </summary> public GraphTraversal<Vertex, Vertex> V(params object[] vertexIds) { var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode)); var args = new List<object>(0 + vertexIds.Length) {}; args.AddRange(vertexIds); traversal.Bytecode.AddStep("V", args.ToArray()); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addE step to that /// traversal. /// </summary> public GraphTraversal<Edge, Edge> AddE(string label) { var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode)); traversal.Bytecode.AddStep("addE", label); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addE step to that /// traversal. /// </summary> public GraphTraversal<Edge, Edge> AddE(ITraversal edgeLabelTraversal) { var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, new Bytecode(Bytecode)); traversal.Bytecode.AddStep("addE", edgeLabelTraversal); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that /// traversal. /// </summary> public GraphTraversal<Vertex, Vertex> AddV() { var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode)); traversal.Bytecode.AddStep("addV"); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that /// traversal. /// </summary> public GraphTraversal<Vertex, Vertex> AddV(string label) { var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode)); traversal.Bytecode.AddStep("addV", label); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step to that /// traversal. /// </summary> public GraphTraversal<Vertex, Vertex> AddV(ITraversal vertexLabelTraversal) { var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, new Bytecode(Bytecode)); traversal.Bytecode.AddStep("addV", vertexLabelTraversal); return traversal; } /// <summary> /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the inject step to that /// traversal. /// </summary> public GraphTraversal<S, S> Inject<S>(params S[] starts) { var traversal = new GraphTraversal<S, S>(TraversalStrategies, new Bytecode(Bytecode)); var args = new List<S>(0 + starts.Length) {}; args.AddRange(starts); traversal.Bytecode.AddStep("inject", args.ToArray()); return traversal; } } #pragma warning restore 1591 }
// 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.AcceptanceTestsBodyDateTimeRfc1123 { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for Datetimerfc1123. /// </summary> public static partial class Datetimerfc1123Extensions { /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetNull(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetNullAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetNullAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetInvalid(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetInvalidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetInvalidAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetOverflow(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetOverflowAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetOverflowAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUnderflow(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUnderflowAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetUnderflowAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMaxDateTime(this IDatetimerfc1123 operations, System.DateTime datetimeBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutUtcMaxDateTimeAsync(this IDatetimerfc1123 operations, System.DateTime datetimeBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max datetime value fri, 31 dec 9999 23:59:59 gmt /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcLowercaseMaxDateTime(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcLowercaseMaxDateTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value fri, 31 dec 9999 23:59:59 gmt /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetUtcLowercaseMaxDateTimeAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcUppercaseMaxDateTime(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcUppercaseMaxDateTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetUtcUppercaseMaxDateTimeAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMinDateTime(this IDatetimerfc1123 operations, System.DateTime datetimeBody) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMinDateTimeAsync(datetimeBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutUtcMinDateTimeAsync(this IDatetimerfc1123 operations, System.DateTime datetimeBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcMinDateTime(this IDatetimerfc1123 operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcMinDateTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.DateTime?> GetUtcMinDateTimeAsync(this IDatetimerfc1123 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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.ComponentModel; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace System.Runtime.Serialization { internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type s_typeOfException; internal static Type TypeOfException { get { if (s_typeOfException == null) s_typeOfException = typeof(Exception); return s_typeOfException; } } private static Type s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get { if (s_typeOfXmlSchemaType == null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } return s_typeOfXmlSchemaType; } } private static Type s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); private static Type s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); private static Type s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); #if uapaot private static Type s_typeOfSafeSerializationManager; private static bool s_typeOfSafeSerializationManagerSet; internal static Type TypeOfSafeSerializationManager { get { if (!s_typeOfSafeSerializationManagerSet) { s_typeOfSafeSerializationManager = TypeOfInt.Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager"); s_typeOfSafeSerializationManagerSet = true; } return s_typeOfSafeSerializationManager; } } #endif private static Type s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type s_typeOfHashtable; internal static Type TypeOfHashtable { get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type s_typeOfListGeneric; internal static Type TypeOfListGeneric { get { if (s_typeOfListGeneric == null) s_typeOfListGeneric = typeof(List<>); return s_typeOfListGeneric; } } private static Type s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static Type s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } } private static Uri s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } #region Contract compliance for System.Type private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) { if (seq1 == null || seq2 == null || seq1.Length != seq2.Length) return false; for (int i = 0; i < seq1.Length; i++) { if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i])) return false; } return true; } private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName)); matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes)); return matchedMethods.FirstOrDefault(); } internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { var constructorInfos = type.GetConstructors(bindingFlags); var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion private static Type s_typeOfScriptObject; private static Func<object, string> s_serializeFunc; private static Func<string, object> s_deserializeFunc; internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc) { Globals.s_typeOfScriptObject = typeOfScriptObject; Globals.s_serializeFunc = serializeFunc; Globals.s_deserializeFunc = deserializeFunc; } internal static string ScriptObjectJsonSerialize(object obj) { Debug.Assert(s_serializeFunc != null); return Globals.s_serializeFunc(obj); } internal static object ScriptObjectJsonDeserialize(string json) { Debug.Assert(s_deserializeFunc != null); return Globals.s_deserializeFunc(json); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$"; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?> <xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='anyType' nillable='true' type='xs:anyType' /> <xs:element name='anyURI' nillable='true' type='xs:anyURI' /> <xs:element name='base64Binary' nillable='true' type='xs:base64Binary' /> <xs:element name='boolean' nillable='true' type='xs:boolean' /> <xs:element name='byte' nillable='true' type='xs:byte' /> <xs:element name='dateTime' nillable='true' type='xs:dateTime' /> <xs:element name='decimal' nillable='true' type='xs:decimal' /> <xs:element name='double' nillable='true' type='xs:double' /> <xs:element name='float' nillable='true' type='xs:float' /> <xs:element name='int' nillable='true' type='xs:int' /> <xs:element name='long' nillable='true' type='xs:long' /> <xs:element name='QName' nillable='true' type='xs:QName' /> <xs:element name='short' nillable='true' type='xs:short' /> <xs:element name='string' nillable='true' type='xs:string' /> <xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' /> <xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' /> <xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' /> <xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' /> <xs:element name='char' nillable='true' type='tns:char' /> <xs:simpleType name='char'> <xs:restriction base='xs:int'/> </xs:simpleType> <xs:element name='duration' nillable='true' type='tns:duration' /> <xs:simpleType name='duration'> <xs:restriction base='xs:duration'> <xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' /> <xs:minInclusive value='-P10675199DT2H48M5.4775808S' /> <xs:maxInclusive value='P10675199DT2H48M5.4775807S' /> </xs:restriction> </xs:simpleType> <xs:element name='guid' nillable='true' type='tns:guid' /> <xs:simpleType name='guid'> <xs:restriction base='xs:string'> <xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' /> </xs:restriction> </xs:simpleType> <xs:attribute name='FactoryType' type='xs:QName' /> <xs:attribute name='Id' type='xs:ID' /> <xs:attribute name='Ref' type='xs:IDREF' /> </xs:schema> "; } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Observable.cs" company="sgmunn"> // (c) sgmunn 2012 // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace MonoKit.Reactive.Linq { using System; using System.Threading.Tasks; using MonoKit.Reactive; using MonoKit.Reactive.Concurrency; using MonoKit.Reactive.Subjects; using MonoKit.Reactive.Disposables; public static class Observable { public static IObservable<T> Empty<T>() { return new AnonymousObservable<T>( (observer) => { observer.OnCompleted(); return Disposable.Empty; }); } public static IObservable<T>Create<T>(Func<IObserver<T>, Action> onSubscribe) { return Create<T>(observer => Disposable.Create(onSubscribe(observer))); } public static IObservable<T>Create<T>(Func<IObserver<T>, IDisposable> onSubscribe) { return new AnonymousObservable<T>(onSubscribe); } public static IObservable<T> ObserveOn<T>(this IObservable<T> source, IScheduler scheduler) { return new AnonymousObservable<T> (observer => { var x = new ScheduledObserver<T>(scheduler, observer); return source.Subscribe(x); }); } public static IObservable<T> Return<T>(T value) { return new AnonymousObservable<T>( (observer) => { observer.OnNext(value); observer.OnCompleted(); return Disposable.Empty; }); } public static IObservable<T> Throw<T>(Exception ex) { return new AnonymousObservable<T>( (observer) => { observer.OnError(ex); return Disposable.Empty; }); } public static IObservable<T> Start<T>(Func<T> function) { var task = new Task<T>(function); return task.AsObservable(); } public static IObservable<Unit> Start(Action action) { var task = new Task<Unit> (() => { action(); return Unit.Default; }); return task.AsObservable(); } public static IObservable<T> AsObservable<T>(this Task<T> task) { var subject = new Subject<T>(); task.ContinueWith (t => { subject.OnError(t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith (t => { subject.OnNext(t.Result); subject.OnCompleted(); }, TaskContinuationOptions.OnlyOnRanToCompletion); return new AnonymousObservable<T> (o => { // subscribe the observer to our subject first, var subscription = subject.Subscribe(o); // start the task task.Start(); // return the subscription token return subscription; }); } public static IObservable<T> Do<T>(this IObservable<T> source, Action<T> onNextAction) { Func<IObserver<T>, IDisposable> subscribeFunction = observer => source.Subscribe( (x => { try { onNextAction(x); } catch (Exception ex) { observer.OnError(ex); return; } observer.OnNext(x); }), observer.OnError, observer.OnCompleted); return new AnonymousObservable<T>(subscribeFunction); } public static IObservable<T> Where<T>(this IObservable<T> source, Func<T, bool> whereClause) { return new AnonymousObservable<T>( observer => source.Subscribe( new AnonymousObserver<T>( x => { bool result; try { result = whereClause(x); } catch (Exception exception) { observer.OnError(exception); return; } if (result) { observer.OnNext(x); } }, observer.OnError, observer.OnCompleted)) ); } public static IObservable<T> OfType<T>(this IObservable<object> source) { return source.Where (x => x != null && typeof(T).IsAssignableFrom(x.GetType())).Select(x => (T)x); } public static IObservable<TResult> Select<T, TResult>(this IObservable<T> source, Func<T, TResult> selector) { return new AnonymousObservable<TResult>( observer => source.Subscribe( new AnonymousObserver<T>( x => { TResult result; try { result = selector(x); } catch (Exception exception) { observer.OnError(exception); return; } observer.OnNext(result); }, observer.OnError, observer.OnCompleted))); } public static IObservable<T> Cast<T>(this IObservable<object> source) { return new AnonymousObservable<T>( observer => source.Subscribe( new AnonymousObserver<object>( x => { T result; try { result = (T)x; } catch (Exception exception) { observer.OnError(exception); return; } observer.OnNext(result); }, observer.OnError, observer.OnCompleted))); } public static IObservable<T> Take<T>(this IObservable<T> source, int count) { return new AnonymousObservable<T>( observer => source.Subscribe( new AnonymousObserver<T>( x => { if (count > 0) { count--; observer.OnNext(x); if (count < 1) { observer.OnCompleted(); } } }, observer.OnError, observer.OnCompleted))); } public static IObservable<T> Skip<T>(this IObservable<T> source, int count) { return new AnonymousObservable<T>( observer => source.Subscribe( new AnonymousObserver<T>( x => { if (count <= 0) { observer.OnNext(x); } else { count--; } }, observer.OnError, observer.OnCompleted))); } } }
using System; using System.Reflection; using System.Runtime.InteropServices; namespace Python.Runtime { /// <summary> /// Base class for Python types that reflect managed exceptions based on /// System.Exception /// </summary> /// <remarks> /// The Python wrapper for managed exceptions LIES about its inheritance /// tree. Although the real System.Exception is a subclass of /// System.Object the Python type for System.Exception does NOT claim that /// it subclasses System.Object. Instead TypeManager.CreateType() uses /// Python's exception.Exception class as base class for System.Exception. /// </remarks> internal class ExceptionClassObject : ClassObject { internal ExceptionClassObject(Type tp) : base(tp) { } internal static Exception ToException(IntPtr ob) { var co = GetManagedObject(ob) as CLRObject; if (co == null) { return null; } var e = co.inst as Exception; if (e == null) { return null; } return e; } /// <summary> /// Exception __str__ implementation /// </summary> public new static IntPtr tp_str(IntPtr ob) { Exception e = ToException(ob); if (e == null) { return Exceptions.RaiseTypeError("invalid object"); } string message = string.Empty; if (e.Message != string.Empty) { message = e.Message; } if (!string.IsNullOrEmpty(e.StackTrace)) { message = message + "\n" + e.StackTrace; } return Runtime.PyUnicode_FromString(message); } } /// <summary> /// Encapsulates the Python exception APIs. /// </summary> /// <remarks> /// Readability of the Exceptions class improvements as we look toward version 2.7 ... /// </remarks> public class Exceptions { internal static IntPtr warnings_module; internal static IntPtr exceptions_module; private Exceptions() { } /// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); } /// <summary> /// Cleanup resources upon shutdown of the Python runtime. /// </summary> internal static void Shutdown() { if (Runtime.Py_IsInitialized() != 0) { Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { var op = (IntPtr)fi.GetValue(type); if (op != IntPtr.Zero) { Runtime.XDecref(op); } } Runtime.XDecref(exceptions_module); Runtime.PyObject_HasAttrString(warnings_module, "xx"); Runtime.XDecref(warnings_module); } } /// <summary> /// Set the 'args' slot on a python exception object that wraps /// a CLR exception. This is needed for pickling CLR exceptions as /// BaseException_reduce will only check the slots, bypassing the /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// </summary> /// <param name="ob">The python object wrapping </param> internal static void SetArgsAndCause(IntPtr ob) { // e: A CLR Exception Exception e = ExceptionClassObject.ToException(ob); if (e == null) { return; } IntPtr args; if (!string.IsNullOrEmpty(e.Message)) { args = Runtime.PyTuple_New(1); IntPtr msg = Runtime.PyUnicode_FromString(e.Message); Runtime.PyTuple_SetItem(args, 0, msg); } else { args = Runtime.PyTuple_New(0); } Marshal.WriteIntPtr(ob, ExceptionOffset.args, args); #if PYTHON3 if (e.InnerException != null) { IntPtr cause = CLRObject.GetInstHandle(e.InnerException); Marshal.WriteIntPtr(ob, ExceptionOffset.cause, cause); } #endif } /// <summary> /// Shortcut for (pointer == NULL) -&gt; throw PythonException /// </summary> /// <param name="pointer">Pointer to a Python object</param> internal static unsafe void ErrorCheck(IntPtr pointer) { if (pointer == IntPtr.Zero) { throw new PythonException(); } } /// <summary> /// Shortcut for (pointer == NULL or ErrorOccurred()) -&gt; throw PythonException /// </summary> internal static unsafe void ErrorOccurredCheck(IntPtr pointer) { if (pointer == IntPtr.Zero || ErrorOccurred()) { throw new PythonException(); } } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the current Python exception matches the given /// Python object. This is a wrapper for PyErr_ExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr ob) { return Runtime.PyErr_ExceptionMatches(ob) != 0; } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the given Python exception matches the given /// Python object. This is a wrapper for PyErr_GivenExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr exc, IntPtr ob) { int i = Runtime.PyErr_GivenExceptionMatches(exc, ob); return i != 0; } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a native string. /// This is a wrapper for the Python PyErr_SetString call. /// </remarks> public static void SetError(IntPtr ob, string value) { Runtime.PyErr_SetString(ob, value); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a Python object. /// This is a wrapper for the Python PyErr_SetObject call. /// </remarks> public static void SetError(IntPtr ob, IntPtr value) { Runtime.PyErr_SetObject(ob, value); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a CLR exception /// object. The CLR exception instance is wrapped as a Python /// object, allowing it to be handled naturally from Python. /// </remarks> public static void SetError(Exception e) { // Because delegates allow arbitrary nesting of Python calling // managed calling Python calling... etc. it is possible that we // might get a managed exception raised that is a wrapper for a // Python exception. In that case we'd rather have the real thing. var pe = e as PythonException; if (pe != null) { Runtime.PyErr_SetObject(pe.PyType, pe.PyValue); return; } IntPtr op = CLRObject.GetInstHandle(e); IntPtr etype = Runtime.PyObject_GetAttrString(op, "__class__"); Runtime.PyErr_SetObject(etype, op); Runtime.XDecref(etype); Runtime.XDecref(op); } /// <summary> /// ErrorOccurred Method /// </summary> /// <remarks> /// Returns true if an exception occurred in the Python runtime. /// This is a wrapper for the Python PyErr_Occurred call. /// </remarks> public static bool ErrorOccurred() { return Runtime.PyErr_Occurred() != 0; } /// <summary> /// Clear Method /// </summary> /// <remarks> /// Clear any exception that has been set in the Python runtime. /// </remarks> public static void Clear() { Runtime.PyErr_Clear(); } //==================================================================== // helper methods for raising warnings //==================================================================== /// <summary> /// Alias for Python's warnings.warn() function. /// </summary> public static void warn(string message, IntPtr exception, int stacklevel) { if (exception == IntPtr.Zero || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); } Runtime.XIncref(warnings_module); IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn"); Runtime.XDecref(warnings_module); Exceptions.ErrorCheck(warn); IntPtr args = Runtime.PyTuple_New(3); IntPtr msg = Runtime.PyString_FromString(message); Runtime.XIncref(exception); // PyTuple_SetItem steals a reference IntPtr level = Runtime.PyInt_FromInt32(stacklevel); Runtime.PyTuple_SetItem(args, 0, msg); Runtime.PyTuple_SetItem(args, 1, exception); Runtime.PyTuple_SetItem(args, 2, level); IntPtr result = Runtime.PyObject_CallObject(warn, args); Exceptions.ErrorCheck(result); Runtime.XDecref(warn); Runtime.XDecref(result); Runtime.XDecref(args); } public static void warn(string message, IntPtr exception) { warn(message, exception, 1); } public static void deprecation(string message, int stacklevel) { warn(message, Exceptions.DeprecationWarning, stacklevel); } public static void deprecation(string message) { deprecation(message, 1); } //==================================================================== // Internal helper methods for common error handling scenarios. //==================================================================== internal static IntPtr RaiseTypeError(string message) { Exceptions.SetError(Exceptions.TypeError, message); return IntPtr.Zero; } // 2010-11-16: Arranged in python (2.6 & 2.7) source header file order /* Predefined exceptions are puplic static variables on the Exceptions class filled in from the python class using reflection in Initialize() looked up by name, not posistion. */ public static IntPtr BaseException; public static IntPtr Exception; public static IntPtr StopIteration; public static IntPtr GeneratorExit; #if PYTHON2 public static IntPtr StandardError; #endif public static IntPtr ArithmeticError; public static IntPtr LookupError; public static IntPtr AssertionError; public static IntPtr AttributeError; public static IntPtr EOFError; public static IntPtr FloatingPointError; public static IntPtr EnvironmentError; public static IntPtr IOError; public static IntPtr OSError; public static IntPtr ImportError; public static IntPtr IndexError; public static IntPtr KeyError; public static IntPtr KeyboardInterrupt; public static IntPtr MemoryError; public static IntPtr NameError; public static IntPtr OverflowError; public static IntPtr RuntimeError; public static IntPtr NotImplementedError; public static IntPtr SyntaxError; public static IntPtr IndentationError; public static IntPtr TabError; public static IntPtr ReferenceError; public static IntPtr SystemError; public static IntPtr SystemExit; public static IntPtr TypeError; public static IntPtr UnboundLocalError; public static IntPtr UnicodeError; public static IntPtr UnicodeEncodeError; public static IntPtr UnicodeDecodeError; public static IntPtr UnicodeTranslateError; public static IntPtr ValueError; public static IntPtr ZeroDivisionError; //#ifdef MS_WINDOWS //public static IntPtr WindowsError; //#endif //#ifdef __VMS //public static IntPtr VMSError; //#endif //PyAPI_DATA(PyObject *) PyExc_BufferError; //PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; //PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; /* Predefined warning categories */ public static IntPtr Warning; public static IntPtr UserWarning; public static IntPtr DeprecationWarning; public static IntPtr PendingDeprecationWarning; public static IntPtr SyntaxWarning; public static IntPtr RuntimeWarning; public static IntPtr FutureWarning; public static IntPtr ImportWarning; public static IntPtr UnicodeWarning; //PyAPI_DATA(PyObject *) PyExc_BytesWarning; } }
using System; using System.Runtime.InteropServices; using SQLite.Net.Interop; namespace SQLite.Net.Platform.Win32 { public class SQLiteApiWin32 : ISQLiteApiExt { public SQLiteApiWin32(string nativeInteropSearchPath = null) { if (nativeInteropSearchPath != null) SQLiteApiWin32InternalConfiguration.NativeInteropSearchPath = nativeInteropSearchPath; } public Result Open(byte[] filename, out IDbHandle db, int flags, IntPtr zvfs) { IntPtr dbPtr; Result r = SQLiteApiWin32Internal.sqlite3_open_v2(filename, out dbPtr, flags, zvfs); db = new DbHandle(dbPtr); return r; } public ExtendedResult ExtendedErrCode(IDbHandle db) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_extended_errcode(internalDbHandle.DbPtr); } public int LibVersionNumber() { return SQLiteApiWin32Internal.sqlite3_libversion_number(); } public string SourceID() { return Marshal.PtrToStringAnsi(SQLiteApiWin32Internal.sqlite3_sourceid()); } public Result EnableLoadExtension(IDbHandle db, int onoff) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_enable_load_extension(internalDbHandle.DbPtr, onoff); } public Result Close(IDbHandle db) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_close(internalDbHandle.DbPtr); } public Result Initialize() { return SQLiteApiWin32Internal.sqlite3_initialize(); } public Result Shutdown() { return SQLiteApiWin32Internal.sqlite3_shutdown(); } public Result Config(ConfigOption option) { return SQLiteApiWin32Internal.sqlite3_config(option); } public Result BusyTimeout(IDbHandle db, int milliseconds) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_busy_timeout(internalDbHandle.DbPtr, milliseconds); } public int Changes(IDbHandle db) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_changes(internalDbHandle.DbPtr); } public IDbStatement Prepare2(IDbHandle db, string query) { var internalDbHandle = (DbHandle) db; IntPtr stmt; Result r = SQLiteApiWin32Internal.sqlite3_prepare_v2(internalDbHandle.DbPtr, query, query.Length, out stmt, IntPtr.Zero); if (r != Result.OK) { throw SQLiteException.New(r, Errmsg16(internalDbHandle)); } return new DbStatement(stmt); } public Result Step(IDbStatement stmt) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_step(internalStmt.StmtPtr); } public Result Reset(IDbStatement stmt) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_reset(internalStmt.StmtPtr); } public Result Finalize(IDbStatement stmt) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_finalize(internalStmt.StmtPtr); } public long LastInsertRowid(IDbHandle db) { var internalDbHandle = (DbHandle) db; return SQLiteApiWin32Internal.sqlite3_last_insert_rowid(internalDbHandle.DbPtr); } public string Errmsg16(IDbHandle db) { var internalDbHandle = (DbHandle) db; return Marshal.PtrToStringUni(SQLiteApiWin32Internal.sqlite3_errmsg16(internalDbHandle.DbPtr)); } public int BindParameterIndex(IDbStatement stmt, string name) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_parameter_index(internalStmt.StmtPtr, name); } public int BindNull(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_null(internalStmt.StmtPtr, index); } public int BindInt(IDbStatement stmt, int index, int val) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_int(internalStmt.StmtPtr, index, val); } public int BindInt64(IDbStatement stmt, int index, long val) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_int64(internalStmt.StmtPtr, index, val); } public int BindDouble(IDbStatement stmt, int index, double val) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_double(internalStmt.StmtPtr, index, val); } public int BindText16(IDbStatement stmt, int index, string val, int n, IntPtr free) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_text16(internalStmt.StmtPtr, index, val, n, free); } public int BindBlob(IDbStatement stmt, int index, byte[] val, int n, IntPtr free) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_bind_blob(internalStmt.StmtPtr, index, val, n, free); } public int ColumnCount(IDbStatement stmt) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_count(internalStmt.StmtPtr); } public string ColumnName16(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.ColumnName16(internalStmt.StmtPtr, index); } public ColType ColumnType(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_type(internalStmt.StmtPtr, index); } public int ColumnInt(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_int(internalStmt.StmtPtr, index); } public long ColumnInt64(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_int64(internalStmt.StmtPtr, index); } public double ColumnDouble(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_double(internalStmt.StmtPtr, index); } public string ColumnText16(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return Marshal.PtrToStringUni(SQLiteApiWin32Internal.sqlite3_column_text16(internalStmt.StmtPtr, index)); } public byte[] ColumnBlob(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.ColumnBlob(internalStmt.StmtPtr, index); } public int ColumnBytes(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.sqlite3_column_bytes(internalStmt.StmtPtr, index); } public byte[] ColumnByteArray(IDbStatement stmt, int index) { var internalStmt = (DbStatement) stmt; return SQLiteApiWin32Internal.ColumnByteArray(internalStmt.StmtPtr, index); } #region Backup public IDbBackupHandle BackupInit(IDbHandle destHandle, string destName, IDbHandle srcHandle, string srcName) { var internalDestDb = (DbHandle)destHandle; var internalSrcDb = (DbHandle)srcHandle; IntPtr p = SQLiteApiWin32Internal.sqlite3_backup_init(internalDestDb.DbPtr, destName, internalSrcDb.DbPtr, srcName); if(p == IntPtr.Zero) { return null; } else { return new DbBackupHandle(p); } } public Result BackupStep(IDbBackupHandle handle, int pageCount) { var internalBackup = (DbBackupHandle)handle; return SQLiteApiWin32Internal.sqlite3_backup_step(internalBackup.DbBackupPtr, pageCount); } public Result BackupFinish(IDbBackupHandle handle) { var internalBackup = (DbBackupHandle)handle; return SQLiteApiWin32Internal.sqlite3_backup_finish(internalBackup.DbBackupPtr); } public int BackupRemaining(IDbBackupHandle handle) { var internalBackup = (DbBackupHandle)handle; return SQLiteApiWin32Internal.sqlite3_backup_remaining(internalBackup.DbBackupPtr); } public int BackupPagecount(IDbBackupHandle handle) { var internalBackup = (DbBackupHandle)handle; return SQLiteApiWin32Internal.sqlite3_backup_pagecount(internalBackup.DbBackupPtr); } public int Sleep(int millis) { return SQLiteApiWin32Internal.sqlite3_sleep(millis); } private struct DbBackupHandle : IDbBackupHandle { public DbBackupHandle(IntPtr dbBackupPtr) : this() { DbBackupPtr = dbBackupPtr; } internal IntPtr DbBackupPtr { get; set; } public bool Equals(IDbBackupHandle other) { return other is DbBackupHandle && DbBackupPtr == ((DbBackupHandle)other).DbBackupPtr; } } #endregion private struct DbHandle : IDbHandle { public DbHandle(IntPtr dbPtr) : this() { DbPtr = dbPtr; } internal IntPtr DbPtr { get; set; } public bool Equals(IDbHandle other) { return other is DbHandle && DbPtr == ((DbHandle) other).DbPtr; } } private struct DbStatement : IDbStatement { public DbStatement(IntPtr stmtPtr) : this() { StmtPtr = stmtPtr; } internal IntPtr StmtPtr { get; set; } public bool Equals(IDbStatement other) { return other is DbStatement && StmtPtr == ((DbStatement) other).StmtPtr; } } } }
using System.Collections.Generic; using System.Globalization; using UnityEditor; using UnityEngine; namespace BitStrap { /// <summary> /// Bunch of EditorGUI[Layout] helper methods to ease your Unity custom editor development. /// </summary> public static class EditorHelper { private class ObjectNameComparer : IComparer<Object> { public readonly static ObjectNameComparer Instance = new ObjectNameComparer(); int IComparer<Object>.Compare( Object a, Object b ) { return System.String.Compare( a.name, b.name, System.StringComparison.OrdinalIgnoreCase ); } } /// <summary> /// Collection of some cool and useful GUI styles. /// </summary> public static class Styles { public static GUIStyle Header { get { return GUI.skin.GetStyle( "HeaderLabel" ); } } public static GUIStyle Selection { get { return GUI.skin.GetStyle( "MeTransitionSelectHead" ); } } public static GUIStyle PreDrop { get { return GUI.skin.GetStyle( "TL SelectionButton PreDropGlow" ); } } public static GUIStyle SearchTextField { get { return GUI.skin.GetStyle( "SearchTextField" ); } } public static GUIStyle SearchCancelButtonEmpty { get { return GUI.skin.GetStyle( "SearchCancelButtonEmpty" ); } } public static GUIStyle SearchCancelButton { get { return GUI.skin.GetStyle( "SearchCancelButton" ); } } public static GUIStyle Plus { get { return GUI.skin.GetStyle( "OL Plus" ); } } public static GUIStyle Minus { get { return GUI.skin.GetStyle( "OL Minus" ); } } public static GUIStyle Input { get { return GUI.skin.GetStyle( "flow shader in 0" ); } } public static GUIStyle Output { get { return GUI.skin.GetStyle( "flow shader out 0" ); } } public static GUIStyle Warning { get { return GUI.skin.GetStyle( "CN EntryWarn" ); } } } private static string searchField = ""; private static Vector2 scroll = Vector2.zero; private static Texture[] unityIcons = null; private static GUIStyle boxStyle = null; /// <summary> /// The drop down button stored Rect. For use with GenericMenu /// </summary> public static Rect DropDownRect { get; private set; } private static GUIStyle BoxStyle { get { if( boxStyle == null ) { boxStyle = EditorStyles.helpBox; boxStyle.padding.left = 1; boxStyle.padding.right = 1; boxStyle.padding.top = 4; boxStyle.padding.bottom = 8; boxStyle.margin.left = 16; boxStyle.margin.right = 16; } return boxStyle; } } /// <summary> /// Begins drawing a box. /// Draw its header here. /// </summary> public static void BeginBoxHeader() { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginVertical( BoxStyle ); EditorGUILayout.BeginHorizontal( EditorStyles.toolbar ); } /// <summary> /// Ends drawing the box header. /// Draw its contents here. /// </summary> public static void EndBoxHeaderBeginContent() { EndBoxHeaderBeginContent( Vector2.zero ); } /// <summary> /// Ends drawing the box header. /// Draw its contents here (scroll version). /// </summary> /// <param name="scroll"></param> /// <returns></returns> public static Vector2 EndBoxHeaderBeginContent( Vector2 scroll ) { EditorGUILayout.EndHorizontal(); GUILayout.Space( 1.0f ); return EditorGUILayout.BeginScrollView( scroll ); } /// <summary> /// Begins drawing a box with a label header. /// </summary> /// <param name="label"></param> public static void BeginBox( string label ) { BeginBoxHeader(); Rect rect = GUILayoutUtility.GetRect( GUIContent.none, GUI.skin.label ); rect.y -= 2.0f; rect.height += 2.0f; EditorGUI.LabelField( rect, Label( label ), Styles.Header ); EndBoxHeaderBeginContent(); } /// <summary> /// Begins drawing a box with a label header (scroll version). /// </summary> /// <param name="scroll"></param> /// <param name="label"></param> /// <returns></returns> public static Vector2 BeginBox( Vector2 scroll, string label ) { BeginBoxHeader(); EditorGUILayout.LabelField( Label( label ), Styles.Header ); return EndBoxHeaderBeginContent( scroll ); } /// <summary> /// Finishes drawing the box. /// </summary> /// <returns></returns> public static bool EndBox() { EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); return EditorGUI.EndChangeCheck(); } /// <summary> /// Reserves a Rect in a layout setup given a style. /// </summary> /// <param name="style"></param> /// <returns></returns> public static Rect Rect( GUIStyle style ) { return GUILayoutUtility.GetRect( GUIContent.none, style ); } /// <summary> /// Reserves a Rect with an explicit height in a layout. /// </summary> /// <param name="height"></param> /// <returns></returns> public static Rect Rect( float height ) { return GUILayoutUtility.GetRect( 0.0f, height, GUILayout.ExpandWidth( true ) ); } /// <summary> /// Returns a GUIContent containing a label and the tooltip defined in GUI.tooltip. /// </summary> /// <param name="label"></param> /// <returns></returns> public static GUIContent Label( string label ) { return new GUIContent( label, GUI.tooltip ); } /// <summary> /// Draws a drop down button and stores its Rect in DropDownRect variable. /// </summary> /// <param name="label"></param> /// <param name="style"></param> /// <returns></returns> public static bool DropDownButton( string label, GUIStyle style ) { var content = new GUIContent( label ); DropDownRect = GUILayoutUtility.GetRect( content, style ); return GUI.Button( DropDownRect, content, style ); } /// <summary> /// Draws a search field like those of Project window. /// </summary> /// <param name="search"></param> /// <returns></returns> public static string SearchField( string search ) { using( Horizontal.Do() ) { search = EditorGUILayout.TextField( search, Styles.SearchTextField ); var buttonStyle = string.IsNullOrEmpty( search ) ? EditorHelper.Styles.SearchCancelButtonEmpty : EditorHelper.Styles.SearchCancelButton; if( GUILayout.Button( GUIContent.none, buttonStyle ) ) search = ""; } return search; } /// <summary> /// Draws a delayed search field like those of Project window. /// </summary> /// <param name="search"></param> /// <returns></returns> public static string DelayedSearchField( string search ) { using( Horizontal.Do() ) { search = EditorGUILayout.DelayedTextField( search, Styles.SearchTextField ); var buttonStyle = string.IsNullOrEmpty( search ) ? EditorHelper.Styles.SearchCancelButtonEmpty : EditorHelper.Styles.SearchCancelButton; if( GUILayout.Button( GUIContent.none, buttonStyle ) ) search = ""; } return search; } /// <summary> /// This is a debug method that draws all Unity styles found in GUI.skin.customStyles /// together with its name, so you can later use some specific style. /// </summary> public static void DrawAllStyles() { searchField = SearchField( searchField ); string searchLower = searchField.ToLower( CultureInfo.InvariantCulture ); EditorGUILayout.Space(); using( ScrollView.Do( ref scroll ) ) { foreach( GUIStyle style in GUI.skin.customStyles ) { if( string.IsNullOrEmpty( searchField ) || style.name.ToLower( CultureInfo.InvariantCulture ).Contains( searchLower ) ) { using( Horizontal.Do() ) { EditorGUILayout.TextField( style.name, EditorStyles.label ); GUILayout.Label( style.name, style ); } } } } } /// <summary> /// This is a debug method that draws all Unity icons /// together with its name, so you can later use them. /// </summary> public static void DrawAllIcons() { if( unityIcons == null ) { unityIcons = Resources.FindObjectsOfTypeAll<Texture>(); System.Array.Sort( unityIcons, ObjectNameComparer.Instance ); } searchField = SearchField( searchField ); string searchLower = searchField.ToLower( CultureInfo.InvariantCulture ); EditorGUILayout.Space(); using( ScrollView.Do( ref scroll ) ) { foreach( Texture texture in unityIcons ) { if( texture == null || texture.name == "" ) continue; if( !AssetDatabase.GetAssetPath( texture ).StartsWith( "Library/" ) ) continue; if( string.IsNullOrEmpty( searchField ) || texture.name.ToLower( CultureInfo.InvariantCulture ).Contains( searchLower ) ) { using( Horizontal.Do() ) { EditorGUILayout.TextField( texture.name, EditorStyles.label ); GUILayout.Label( new GUIContent( texture ) ); } } } } } } }
/* * Unity VSCode Support * * Seamless support for Microsoft Visual Studio Code in Unity * * Version: * 2.7 * * Authors: * Matthew Davey <matthew.davey@dotbunny.com> */ namespace dotBunny.Unity { using System; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; [InitializeOnLoad] public static class VSCode { /// <summary> /// Current Version Number /// </summary> public const float Version = 2.7f; /// <summary> /// Current Version Code /// </summary> public const string VersionCode = "-RELEASE"; /// <summary> /// Download URL for Unity Debbuger /// </summary> public const string UnityDebuggerURL = "https://unity.gallery.vsassets.io/_apis/public/gallery/publisher/unity/extension/unity-debug/latest/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage"; #region Properties /// <summary> /// Path to VSCode executable public static string CodePath { get { string current = EditorPrefs.GetString("VSCode_CodePath", ""); if(current == "" || !VSCodeExists(current)) { //Value not set, set to "" or current path is invalid, try to autodetect it //If autodetect fails, a error will be printed and the default value set EditorPrefs.SetString("VSCode_CodePath", AutodetectCodePath()); //If its not installed or the install folder isn't a "normal" one, //AutodetectCodePath will print a error message to the Unity Console } return EditorPrefs.GetString("VSCode_CodePath", current); } set { EditorPrefs.SetString("VSCode_CodePath", value); } } /// <summary> /// Get Program Files Path /// </summary> /// <returns>The platforms "Program Files" path.</returns> static string ProgramFilesx86() { if( 8 == IntPtr.Size || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))) { return Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } return Environment.GetEnvironmentVariable("ProgramFiles"); } /// <summary> /// Should debug information be displayed in the Unity terminal? /// </summary> public static bool Debug { get { return EditorPrefs.GetBool("VSCode_Debug", false); } set { EditorPrefs.SetBool("VSCode_Debug", value); } } /// <summary> /// Is the Visual Studio Code Integration Enabled? /// </summary> /// <remarks> /// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode /// </remarks> public static bool Enabled { get { return EditorPrefs.GetBool("VSCode_Enabled", false); } set { // When turning the plugin on, we should remove all the previous project files if (!Enabled && value) { ClearProjectFiles(); } EditorPrefs.SetBool("VSCode_Enabled", value); } } public static bool UseUnityDebugger { get { return EditorPrefs.GetBool("VSCode_UseUnityDebugger", false); } set { if ( value != UseUnityDebugger ) { // Set value EditorPrefs.SetBool("VSCode_UseUnityDebugger", value); // Do not write the launch JSON file because the debugger uses its own if ( value ) { WriteLaunchFile = false; } // Update launch file UpdateLaunchFile(); } } } /// <summary> /// When opening a project in Unity, should it automatically open in VS Code. /// </summary> public static bool AutoOpenEnabled { get { return EditorPrefs.GetBool("VSCode_AutoOpenEnabled", false); } set { EditorPrefs.SetBool("VSCode_AutoOpenEnabled", value); } } /// <summary> /// Should the launch.json file be written? /// </summary> /// <remarks> /// Useful to disable if someone has their own custom one rigged up /// </remarks> public static bool WriteLaunchFile { get { return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true); } set { EditorPrefs.SetBool("VSCode_WriteLaunchFile", value); } } /// <summary> /// Should the plugin automatically update itself. /// </summary> static bool AutomaticUpdates { get { return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false); } set { EditorPrefs.SetBool("VSCode_AutomaticUpdates", value); } } static float GitHubVersion { get { return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version); } set { EditorPrefs.SetFloat("VSCode_GitHubVersion", value); } } /// <summary> /// When was the last time that the plugin was updated? /// </summary> static DateTime LastUpdate { get { // Feature creation date. DateTime lastTime = new DateTime(2015, 10, 8); if (EditorPrefs.HasKey("VSCode_LastUpdate")) { DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime); } return lastTime; } set { EditorPrefs.SetString("VSCode_LastUpdate", value.ToString()); } } /// <summary> /// Quick reference to the VSCode launch settings file /// </summary> static string LaunchPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json"; } } /// <summary> /// The full path to the project /// </summary> static string ProjectPath { get { return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath); } } /// <summary> /// Should the script editor be reverted when quiting Unity. /// </summary> /// <remarks> /// Useful for environments where you do not use VSCode for everything. /// </remarks> static bool RevertExternalScriptEditorOnExit { get { return EditorPrefs.GetBool("VSCode_RevertScriptEditorOnExit", true); } set { EditorPrefs.SetBool("VSCode_RevertScriptEditorOnExit", value); } } /// <summary> /// Quick reference to the VSCode settings folder /// </summary> static string SettingsFolder { get { return ProjectPath + System.IO.Path.DirectorySeparatorChar + ".vscode"; } } static string SettingsPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json"; } } static int UpdateTime { get { return EditorPrefs.GetInt("VSCode_UpdateTime", 7); } set { EditorPrefs.SetInt("VSCode_UpdateTime", value); } } #endregion /// <summary> /// Integration Constructor /// </summary> static VSCode() { if (Enabled) { UpdateUnityPreferences(true); UpdateLaunchFile(); // Add Update Check DateTime targetDate = LastUpdate.AddDays(UpdateTime); if (DateTime.Now >= targetDate && AutomaticUpdates) { CheckForUpdate(); } // Open VS Code automatically when project is loaded if (AutoOpenEnabled) { CheckForAutoOpen(); } } // Event for when script is reloaded System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload; } static void System_AppDomain_CurrentDomain_DomainUnload(object sender, System.EventArgs e) { if (Enabled && RevertExternalScriptEditorOnExit) { UpdateUnityPreferences(false); } } #region Public Members /// <summary> /// Force Unity To Write Project File /// </summary> /// <remarks> /// Reflection! /// </remarks> public static void SyncSolution() { System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor"); System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); SyncSolution.Invoke(null, null); } /// <summary> /// Update the solution files so that they work with VS Code /// </summary> public static void UpdateSolution() { // No need to process if we are not enabled if (!VSCode.Enabled) { return; } if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files"); } var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); foreach (var filePath in solutionFiles) { string content = File.ReadAllText(filePath); content = ScrubSolutionContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } foreach (var filePath in projectFiles) { string content = File.ReadAllText(filePath); content = ScrubProjectContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } } #endregion #region Private Members /// <summary> /// Try to find automatically the installation of VSCode /// </summary> static string AutodetectCodePath() { string[] possiblePaths = #if UNITY_EDITOR_OSX { "/Applications/Visual Studio Code.app", "/Applications/Visual Studio Code - Insiders.app" }; #elif UNITY_EDITOR_WIN { ProgramFilesx86() + Path.DirectorySeparatorChar + "Microsoft VS Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd", ProgramFilesx86() + Path.DirectorySeparatorChar + "Microsoft VS Code Insiders" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code-insiders.cmd" }; #else { "/usr/bin/code", "/bin/code", "/usr/local/bin/code" }; #endif for(int i = 0; i < possiblePaths.Length; i++) { if(VSCodeExists(possiblePaths[i])) { return possiblePaths[i]; } } PrintNotFound(possiblePaths[0]); return possiblePaths[0]; //returns the default one, printing a warning message 'executable not found' } /// <summary> /// Call VSCode with arguments /// </summary> static void CallVSCode(string args) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); if(!VSCodeExists(CodePath)) { PrintNotFound(CodePath); return; } #if UNITY_EDITOR_OSX proc.StartInfo.FileName = "open"; // Check the path to see if there is "Insiders" if (CodePath.Contains("Insiders")) { proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCodeInsiders\" --args " + args.Replace(@"\", @"\\"); } else { proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args.Replace(@"\", @"\\"); } proc.StartInfo.UseShellExecute = false; #elif UNITY_EDITOR_WIN proc.StartInfo.FileName = CodePath; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; #else proc.StartInfo.FileName = CodePath; proc.StartInfo.Arguments = args.Replace(@"\", @"\\"); proc.StartInfo.UseShellExecute = false; #endif proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); } /// <summary> /// Check for Updates with GitHub /// </summary> static void CheckForUpdate() { var fileContent = string.Empty; EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f); // Because were not a runtime framework, lets just use the simplest way of doing this try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs"); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Set the last update time LastUpdate = DateTime.Now; // Fix for oddity in downlo if (fileContent.Substring(0, 2) != "/*") { int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase); // Jump over junk characters fileContent = fileContent.Substring(startPosition); } string[] fileExploded = fileContent.Split('\n'); if (fileExploded.Length > 7) { float github = Version; if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github)) { GitHubVersion = github; } if (github > Version) { var GUIDs = AssetDatabase.FindAssets("t:Script VSCode"); var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar + AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar); if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No")) { // Always make sure the file is writable System.IO.FileInfo fileInfo = new System.IO.FileInfo(path); fileInfo.IsReadOnly = false; // Write update file File.WriteAllText(path, fileContent); // Force update on text file AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate); } } } } /// <summary> /// Checks whether it should auto-open VSCode /// </summary> /// <remarks> /// VSCode() gets called on Launch and Run, through IntializeOnLoad /// https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html /// To make sure it only opens VSCode when Unity (re)launches (i.e. opens a project), /// we compare the launch time, which we calculate using EditorApplication.timeSinceStartup. /// </remarks> static void CheckForAutoOpen() { double timeInSeconds = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; int unityLaunchTimeInSeconds = (int)(timeInSeconds - EditorApplication.timeSinceStartup); int prevUnityLaunchTime = EditorPrefs.GetInt("VSCode_UnityLaunchTime", 0); // If launch time has changed, then Unity was re-opened if (unityLaunchTimeInSeconds > prevUnityLaunchTime) { // Launch VSCode VSCode.MenuOpenProject(); // Save new launch time EditorPrefs.SetInt("VSCode_UnityLaunchTime", unityLaunchTimeInSeconds); } } /// <summary> /// Clear out any existing project files and lingering stuff that might cause problems /// </summary> static void ClearProjectFiles() { var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); var unityProjectFiles = Directory.GetFiles(currentDirectory, "*.unityproj"); foreach (string solutionFile in solutionFiles) { File.Delete(solutionFile); } foreach (string projectFile in projectFiles) { File.Delete(projectFile); } foreach (string unityProjectFile in unityProjectFiles) { File.Delete(unityProjectFile); } // Replace with our clean files (only in Unity 5) #if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7 SyncSolution(); #endif } /// <summary> /// Force Unity Preferences Window To Read From Settings /// </summary> static void FixUnityPreferences() { // I want that window, please and thank you System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor"); if (EditorWindow.focusedWindow == null) return; // Only run this when the editor window is visible (cause its what screwed us up) if (EditorWindow.focusedWindow.GetType() == T) { var window = EditorWindow.GetWindow(T, true, "Unity Preferences"); if (window == null) { if (Debug) { UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)"); } return; } var invokerType = window.GetType(); var invokerMethod = invokerType.GetMethod("ReadPreferences", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (invokerMethod != null) { invokerMethod.Invoke(window, null); } else if (Debug) { UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences"); } } } /// <summary> /// Determine what port Unity is listening for on Windows /// </summary> static int GetDebugPort() { #if UNITY_EDITOR_WIN System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "netstat"; process.StartInfo.Arguments = "-a -n -o -p TCP"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { string[] tokens = Regex.Split(line, "\\s+"); if (tokens.Length > 4) { int test = -1; int.TryParse(tokens[5], out test); if (test > 1023) { try { var p = System.Diagnostics.Process.GetProcessById(test); if (p.ProcessName == "Unity") { return test; } } catch { } } } } #else System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "lsof"; process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); // Not thread safe (yet!) string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { int port = -1; if (line.StartsWith("Unity")) { string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None); if (portions.Length >= 2) { Regex digitsOnly = new Regex(@"[^\d]"); string cleanPort = digitsOnly.Replace(portions[1], ""); if (int.TryParse(cleanPort, out port)) { if (port > -1) { return port; } } } } } #endif return -1; } /// <summary> /// Manually install the original Unity Debuger /// </summary> /// <remarks> /// This should auto update to the latest. /// </remarks> static void InstallUnityDebugger() { EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f); byte[] fileContent; try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadData(UnityDebuggerURL); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Do we have a file to install? if ( fileContent != null ) { string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix"; File.WriteAllBytes(fileName, fileContent); CallVSCode(fileName); } } // HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected. [MenuItem("Assets/Open C# Project In Code", false, 1000)] static void MenuOpenProject() { // Force the project files to be sync SyncSolution(); // Load Project CallVSCode("\"" + ProjectPath + "\""); } /// <summary> /// Print a error message to the Unity Console about not finding the code executable /// </summary> static void PrintNotFound(string path) { UnityEngine.Debug.LogError("[VSCode] Code executable in '" + path + "' not found. Check your" + "Visual Studio Code installation and insert the correct path in the Preferences menu."); } [MenuItem("Assets/Open C# Project In Code", true, 1000)] static bool ValidateMenuOpenProject() { return Enabled; } /// <summary> /// VS Code Integration Preferences Item /// </summary> /// <remarks> /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off /// </remarks> [PreferenceItem("VSCode")] static void VSCodePreferencesItem() { if (EditorApplication.isCompiling) { EditorGUILayout.HelpBox("Please wait for Unity to finish compiling. \nIf the window doesn't refresh, simply click on the window or move it around to cause a repaint to happen.", MessageType.Warning); return; } EditorGUILayout.BeginVertical(); var developmentInfo = "Support development of this plugin, follow @reapazor and @dotbunny on Twitter."; var versionInfo = string.Format("{0:0.00}", Version) + VersionCode + ", GitHub version @ " + string.Format("{0:0.00}", GitHubVersion); EditorGUILayout.HelpBox(developmentInfo + " --- [ " + versionInfo + " ]", MessageType.None); EditorGUI.BeginChangeCheck(); // Need the VS Code executable EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("VS Code Path", GUILayout.Width(75)); #if UNITY_5_3_OR_NEWER CodePath = EditorGUILayout.DelayedTextField(CodePath, GUILayout.ExpandWidth(true)); #else CodePath = EditorGUILayout.TextField(CodePath, GUILayout.ExpandWidth(true)); #endif GUI.SetNextControlName("PathSetButton"); if(GUILayout.Button("...", GUILayout.Height(14), GUILayout.Width(20))) { GUI.FocusControl("PathSetButton"); string path = EditorUtility.OpenFilePanel( "Visual Studio Code Executable", "", "" ); if( path.Length != 0 && File.Exists(path) || Directory.Exists(path)) { CodePath = path; } } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled); UseUnityDebugger = EditorGUILayout.Toggle(new GUIContent("Use Unity Debugger", "Should the integration integrate with Unity's VSCode Extension (must be installed)."), UseUnityDebugger); AutoOpenEnabled = EditorGUILayout.Toggle(new GUIContent("Enable Auto Open", "When opening a project in Unity, should it automatically open in VS Code?"), AutoOpenEnabled); EditorGUILayout.Space(); RevertExternalScriptEditorOnExit = EditorGUILayout.Toggle(new GUIContent("Revert Script Editor On Unload", "Should the external script editor setting be reverted to its previous setting on project unload? This is useful if you do not use Code with all your projects."),RevertExternalScriptEditorOnExit); Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug); WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile); EditorGUILayout.Space(); AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates); UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31); EditorGUILayout.Space(); EditorGUILayout.Space(); if (EditorGUI.EndChangeCheck()) { UpdateUnityPreferences(Enabled); // TODO: Force Unity To Reload Preferences // This seems to be a hick up / issue if (VSCode.Debug) { if (Enabled) { UnityEngine.Debug.Log("[VSCode] Integration Enabled"); } else { UnityEngine.Debug.Log("[VSCode] Integration Disabled"); } } } if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!"))) { CheckForUpdate(); EditorGUILayout.EndVertical(); return; } if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files."))) { WriteWorkspaceSettings(); EditorGUILayout.EndVertical(); return; } EditorGUILayout.Space(); if (UseUnityDebugger) { EditorGUILayout.HelpBox("In order for the \"Use Unity Debuggger\" option to function above, you need to have installed the Unity Debugger Extension for Visual Studio Code.", MessageType.Warning); if (GUILayout.Button(new GUIContent("Install Unity Debugger", "Install the Unity Debugger Extension into Code"))) { InstallUnityDebugger(); EditorGUILayout.EndVertical(); return; } } } /// <summary> /// Asset Open Callback (from Unity) /// </summary> /// <remarks> /// Called when Unity is about to open an asset. /// </remarks> [UnityEditor.Callbacks.OnOpenAssetAttribute()] static bool OnOpenedAsset(int instanceID, int line) { // bail out if we are not using VSCode if (!Enabled) { return false; } // current path without the asset folder string appPath = ProjectPath; // determine asset that has been double clicked in the project view UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID); if (selected.GetType().ToString() == "UnityEditor.MonoScript" || selected.GetType().ToString() == "UnityEngine.Shader") { string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected); string args = null; if (line == -1) { args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r"; } else { args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r"; } // call 'open' CallVSCode(args); return true; } // Didnt find a code file? let Unity figure it out return false; } /// <summary> /// Executed when the Editor's playmode changes allowing for capture of required data /// </summary> static void OnPlaymodeStateChanged() { if (UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode) { UpdateLaunchFile(); } } /// <summary> /// Detect when scripts are reloaded and relink playmode detection /// </summary> [UnityEditor.Callbacks.DidReloadScripts()] static void OnScriptReload() { EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged; } /// <summary> /// Remove extra/erroneous lines from a file. static void ScrubFile(string path) { string[] lines = File.ReadAllLines(path); System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>(); for (int i = 0; i < lines.Length; i++) { // Check Empty if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t") { } else { newLines.Add(lines[i]); } } File.WriteAllLines(path, newLines.ToArray()); } /// <summary> /// Remove extra/erroneous data from project file (content). /// </summary> static string ScrubProjectContent(string content) { if (content.Length == 0) return ""; #if !UNITY_EDITOR_WIN // Moved to 3.5, 2.0 is legacy. if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1) { content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>"); } #endif string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath string langVersion = "<LangVersion>default</LangVersion>"; bool found = true; int location = 0; string addedOptions = ""; int startLocation = -1; int endLocation = -1; int endLength = 0; while (found) { startLocation = -1; endLocation = -1; endLength = 0; addedOptions = ""; startLocation = content.IndexOf("<PropertyGroup", location); if (startLocation != -1) { endLocation = content.IndexOf("</PropertyGroup>", startLocation); endLength = (endLocation - startLocation); if (endLocation == -1) { found = false; continue; } else { found = true; location = endLocation; } if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1) { addedOptions += "\n\r\t" + targetPath + "\n\r"; } if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1) { addedOptions += "\n\r\t" + langVersion + "\n\r"; } if (!string.IsNullOrEmpty(addedOptions)) { content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation); } } else { found = false; } } return content; } /// <summary> /// Remove extra/erroneous data from solution file (content). /// </summary> static string ScrubSolutionContent(string content) { // Replace Solution Version content = content.Replace( "Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n", "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012"); // Remove Solution Properties (Unity Junk) int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution"); if (startIndex != -1) { int endIndex = content.IndexOf("EndGlobalSection", startIndex); content = content.Substring(0, startIndex) + content.Substring(endIndex + 16); } return content; } /// <summary> /// Update Visual Studio Code Launch file /// </summary> static void UpdateLaunchFile() { if (!VSCode.Enabled) { return; } else if (VSCode.UseUnityDebugger) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"name\": \"Unity Editor\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Windows Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"OSX Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Linux Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"iOS Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Android Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); } else if (VSCode.WriteLaunchFile) { int port = GetDebugPort(); if (port > -1) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\":\"0.2.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"request\":\"attach\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")"); } } else { if (VSCode.Debug) { UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port."); } } } } /// <summary> /// Update Unity Editor Preferences /// </summary> /// <param name="enabled">Should we turn on this party!</param> static void UpdateUnityPreferences(bool enabled) { if (enabled) { // App if (EditorPrefs.GetString("kScriptsDefaultApp") != CodePath) { EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp")); } EditorPrefs.SetString("kScriptsDefaultApp", CodePath); // Arguments if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g `$(File):$(Line)`") { EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs")); } EditorPrefs.SetString("kScriptEditorArgs", "-r -g `$(File):$(Line)`"); EditorPrefs.SetString("kScriptEditorArgs" + CodePath, "-r -g `$(File):$(Line)`"); // MonoDevelop Solution if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false)) { EditorPrefs.SetBool("VSCode_PreviousMD", true); } EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false); // Support Unity Proj (JS) if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false)) { EditorPrefs.SetBool("VSCode_PreviousUnityProj", true); } EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false); if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false)) { EditorPrefs.SetBool("VSCode_PreviousAttach", false); } EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true); } else { // Restore previous app if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp"))) { EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp")); } // Restore previous args if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs"))) { EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs")); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousMD", false)) { EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false)) { EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true); } // Always leave editor attaching on, I know, it solves the problem of needing to restart for this // to actually work EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true); } FixUnityPreferences(); } /// <summary> /// Determines if the current path to the code executable is valid or not (exists) /// </summary> static bool VSCodeExists(string curPath) { #if UNITY_EDITOR_OSX return System.IO.Directory.Exists(curPath); #else System.IO.FileInfo code = new System.IO.FileInfo(curPath); return code.Exists; #endif } /// <summary> /// Write Default Workspace Settings /// </summary> static void WriteWorkspaceSettings() { if (Debug) { UnityEngine.Debug.Log("[VSCode] Workspace Settings Written"); } if (!Directory.Exists(VSCode.SettingsFolder)) { System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); } string exclusions = "{\n" + "\t\"files.exclude\":\n" + "\t{\n" + // Hidden Files "\t\t\"**/.DS_Store\":true,\n" + "\t\t\"**/.git\":true,\n" + "\t\t\"**/.gitignore\":true,\n" + "\t\t\"**/.gitattributes\":true,\n" + "\t\t\"**/.gitmodules\":true,\n" + "\t\t\"**/.svn\":true,\n" + // Project Files "\t\t\"**/*.booproj\":true,\n" + "\t\t\"**/*.pidb\":true,\n" + "\t\t\"**/*.suo\":true,\n" + "\t\t\"**/*.user\":true,\n" + "\t\t\"**/*.userprefs\":true,\n" + "\t\t\"**/*.unityproj\":true,\n" + "\t\t\"**/*.dll\":true,\n" + "\t\t\"**/*.exe\":true,\n" + // Media Files "\t\t\"**/*.pdf\":true,\n" + // Audio "\t\t\"**/*.mid\":true,\n" + "\t\t\"**/*.midi\":true,\n" + "\t\t\"**/*.wav\":true,\n" + // Textures "\t\t\"**/*.gif\":true,\n" + "\t\t\"**/*.ico\":true,\n" + "\t\t\"**/*.jpg\":true,\n" + "\t\t\"**/*.jpeg\":true,\n" + "\t\t\"**/*.png\":true,\n" + "\t\t\"**/*.psd\":true,\n" + "\t\t\"**/*.tga\":true,\n" + "\t\t\"**/*.tif\":true,\n" + "\t\t\"**/*.tiff\":true,\n" + // Models "\t\t\"**/*.3ds\":true,\n" + "\t\t\"**/*.3DS\":true,\n" + "\t\t\"**/*.fbx\":true,\n" + "\t\t\"**/*.FBX\":true,\n" + "\t\t\"**/*.lxo\":true,\n" + "\t\t\"**/*.LXO\":true,\n" + "\t\t\"**/*.ma\":true,\n" + "\t\t\"**/*.MA\":true,\n" + "\t\t\"**/*.obj\":true,\n" + "\t\t\"**/*.OBJ\":true,\n" + // Unity File Types "\t\t\"**/*.asset\":true,\n" + "\t\t\"**/*.cubemap\":true,\n" + "\t\t\"**/*.flare\":true,\n" + "\t\t\"**/*.mat\":true,\n" + "\t\t\"**/*.meta\":true,\n" + "\t\t\"**/*.prefab\":true,\n" + "\t\t\"**/*.unity\":true,\n" + // Folders "\t\t\"build/\":true,\n" + "\t\t\"Build/\":true,\n" + "\t\t\"Library/\":true,\n" + "\t\t\"library/\":true,\n" + "\t\t\"obj/\":true,\n" + "\t\t\"Obj/\":true,\n" + "\t\t\"ProjectSettings/\":true,\r" + "\t\t\"temp/\":true,\n" + "\t\t\"Temp/\":true\n" + "\t}\n" + "}"; // Dont like the replace but it fixes the issue with the JSON File.WriteAllText(VSCode.SettingsPath, exclusions); } #endregion } /// <summary> /// VSCode Asset AssetPostprocessor /// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para> /// </summary> /// <remarks>Undocumented Event</remarks> public class VSCodeAssetPostprocessor : AssetPostprocessor { /// <summary> /// On documented, project generation event callback /// </summary> private static void OnGeneratedCSProjectFiles() { // Force execution of VSCode update VSCode.UpdateSolution(); } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. extern alias fs; // Temporary bridge until the Batch core NuGet without file staging is published namespace Batch.FileStaging.Tests.IntegrationTestUtilities { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Auth; using Microsoft.Azure.Batch.Common; using Microsoft.Azure.Batch.FileStaging; using StagingStorageAccount = fs::Microsoft.Azure.Batch.FileStaging.StagingStorageAccount; // Temporary bridge until the Batch core NuGet without file staging is published using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; using Constants = Microsoft.Azure.Batch.Constants; public static class TestUtilities { #region Credentials helpers public static BatchSharedKeyCredentials GetCredentialsFromEnvironment() { return new BatchSharedKeyCredentials( TestCommon.Configuration.BatchAccountUrl, TestCommon.Configuration.BatchAccountName, TestCommon.Configuration.BatchAccountKey); } public static async Task<BatchClient> OpenBatchClientAsync(BatchSharedKeyCredentials sharedKeyCredentials, bool addDefaultRetryPolicy = true) { BatchClient client = await BatchClient.OpenAsync(sharedKeyCredentials); //Force us to get exception if the server returns something we don't expect //TODO: To avoid including this test assembly via "InternalsVisibleTo" we resort to some reflection trickery... maybe this property //TODO: should just be public? //TODO: Disabled for now because the swagger spec does not accurately reflect all properties returned by the server //SetDeserializationSettings(client); //Set up some common stuff like a retry policy if (addDefaultRetryPolicy) { client.CustomBehaviors.Add(RetryPolicyProvider.LinearRetryProvider(TimeSpan.FromSeconds(3), 5)); } return client; } public static async Task<BatchClient> OpenBatchClientFromEnvironmentAsync() { BatchClient client = await OpenBatchClientAsync(GetCredentialsFromEnvironment()); return client; } public static StagingStorageAccount GetStorageCredentialsFromEnvironment() { string storageAccountKey = TestCommon.Configuration.StorageAccountKey; string storageAccountName = TestCommon.Configuration.StorageAccountName; string storageAccountBlobEndpoint = TestCommon.Configuration.StorageAccountBlobEndpoint; StagingStorageAccount storageStagingCredentials = new StagingStorageAccount(storageAccountName, storageAccountKey, storageAccountBlobEndpoint); return storageStagingCredentials; } #endregion #region Naming helpers public static string GetMyName() { string domainName = Environment.GetEnvironmentVariable("USERNAME"); return domainName; } #endregion #region Deletion helpers public static async Task DeleteJobIfExistsAsync(BatchClient client, string jobId) { try { await client.JobOperations.DeleteJobAsync(jobId).ConfigureAwait(false); } catch (BatchException e) { if (!IsExceptionNotFound(e) && !IsExceptionConflict(e)) { throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404 } } } public static async Task DeleteJobScheduleIfExistsAsync(BatchClient client, string jobScheduleId) { try { await client.JobScheduleOperations.DeleteJobScheduleAsync(jobScheduleId).ConfigureAwait(false); } catch (BatchException e) { if (!IsExceptionNotFound(e) && !IsExceptionConflict(e)) { throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404 } } } public static async Task DeletePoolIfExistsAsync(BatchClient client, string poolId) { try { await client.PoolOperations.DeletePoolAsync(poolId).ConfigureAwait(false); } catch (BatchException e) { if (!IsExceptionNotFound(e) && !IsExceptionConflict(e)) { throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404 } } } public static async Task DeleteCertificateIfExistsAsync(BatchClient client, string thumbprintAlgorithm, string thumbprint) { try { await client.CertificateOperations.DeleteCertificateAsync(thumbprintAlgorithm, thumbprint).ConfigureAwait(false); } catch (BatchException e) { if (!IsExceptionNotFound(e) && !IsExceptionConflict(e)) { throw; //re-throw in the case where we tried to delete the cert and got an exception with a status code which wasn't 409 or 404 } } } #endregion #region Wait helpers public static async Task WaitForPoolToReachStateAsync(BatchClient client, string poolId, AllocationState targetAllocationState, TimeSpan timeout) { CloudPool pool = await client.PoolOperations.GetPoolAsync(poolId); await RefreshBasedPollingWithTimeoutAsync( refreshing: pool, condition: () => Task.FromResult(pool.AllocationState == targetAllocationState), timeout: timeout).ConfigureAwait(false); } /// <summary> /// Will throw if timeout is exceeded. /// </summary> /// <param name="refreshing"></param> /// <param name="condition"></param> /// <param name="timeout"></param> /// <returns></returns> public static async Task RefreshBasedPollingWithTimeoutAsync(IRefreshable refreshing, Func<Task<bool>> condition, TimeSpan timeout) { DateTime allocationWaitStartTime = DateTime.UtcNow; DateTime timeoutAfterThisTimeUtc = allocationWaitStartTime.Add(timeout); while (!(await condition().ConfigureAwait(continueOnCapturedContext: false))) { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(continueOnCapturedContext: false); await refreshing.RefreshAsync().ConfigureAwait(continueOnCapturedContext: false); if (DateTime.UtcNow > timeoutAfterThisTimeUtc) { throw new Exception("RefreshBasedPollingWithTimeout: Timed out waiting for condition to be met."); } } } #endregion #region Private helpers private static bool IsExceptionNotFound(BatchException e) { return e.RequestInformation != null && e.RequestInformation.HttpStatusCode == HttpStatusCode.NotFound; } private static bool IsExceptionConflict(BatchException e) { return e.RequestInformation != null && e.RequestInformation.HttpStatusCode == HttpStatusCode.Conflict; } #endregion } }
using System; using System.Drawing; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml; using PdfSharp.Drawing; using Tharga.Reporter.Engine.Interface; namespace Tharga.Reporter.Engine.Entity.Element { public class Image : SinglePageAreaElement { private string _source; private ECacheMode? _cacheMode; public enum ECacheMode { Preferably, //Download file and store locally if possible. Read file from cache if possible. Always, //Always download files locally. Read file from cache if possible. Never //Never download files locally. Never read from cache. } public string Source { get { return _source ?? string.Empty; } set { _source = value; } } public ECacheMode CacheMode { get { return _cacheMode ?? ECacheMode.Preferably; } set { _cacheMode = value; } } internal override void Render(IRenderData renderData) { if (IsNotVisible(renderData)) return; var bounds = GetBounds(renderData.ParentBounds); System.Drawing.Image imageData = null; try { imageData = GetImage(renderData.DocumentData, bounds); renderData.ElementBounds = GetImageBounds(imageData, bounds); if (renderData.IncludeBackground || !IsBackground) { using (var image = XImage.FromGdiPlusImage(imageData)) { renderData.Graphics.DrawImage(image, renderData.ElementBounds); } } } catch (Exception e) { var f = new Font(); var font = new XFont(f.GetName(renderData.Section), f.GetSize(renderData.Section) / 1.5, f.GetStyle(renderData.Section)); var brush = new XSolidBrush(XColor.FromKnownColor(KnownColor.Transparent)); renderData.Graphics.DrawRectangle(new XPen(f.GetColor(renderData.Section)), brush, bounds); var textBrush = new XSolidBrush(XColor.FromArgb(f.GetColor(renderData.Section))); try { var nextTop = OutputText(renderData, e.Message, font, textBrush, new XPoint(bounds.Left, bounds.Top), bounds.Width); if (e.Data.Contains("source")) OutputText(renderData, e.Data["source"].ToString(), font, textBrush, new XPoint(bounds.Left, bounds.Top + nextTop), bounds.Width); } catch (Exception exception) { renderData.Graphics.DrawString(exception.Message, font, brush, new XPoint(bounds.Left, bounds.Top), XStringFormats.TopLeft); } } finally { imageData?.Dispose(); } } private static double OutputText(IRenderData renderData, string message, XFont font, XSolidBrush brush, XPoint point, double width) { var textSize = renderData.Graphics.MeasureString(message, font); var lineCount = 0; var offset = 0; var part = 0; var more = true; while (more) //offset + part < message.Length) { more = false; part = message.Length - offset; while (renderData.Graphics.MeasureString(message.Substring(offset, part), font).Width > width) { part--; more = true; } renderData.Graphics.DrawString(message.Substring(offset, part), font, brush, new XPoint(point.X,point.Y+ textSize.Height * lineCount), XStringFormats.TopLeft); offset = part; lineCount++; } return textSize.Height * lineCount; } private static XRect GetImageBounds(System.Drawing.Image imageData, XRect bounds) { var imageBounds = bounds; if (Math.Abs((imageBounds.Width / imageBounds.Height) - (imageData.Width / (double)imageData.Height)) > 0.01) { if (((imageBounds.Width / imageBounds.Height) - (imageData.Width / (double)imageData.Height)) > 0) imageBounds.Width = (imageBounds.Height * imageData.Width) / imageData.Height; else imageBounds.Height = (imageBounds.Width * imageData.Height) / imageData.Width; } return imageBounds; } public static string BytesToLongString(byte[] bytes) { var sb = new StringBuilder(); for (var i = 0; i < bytes.Length; i++) sb.AppendFormat("{0}/", bytes[i].ToString(CultureInfo.InvariantCulture)); var imgData = sb.ToString(); return imgData; } private static byte[] LongStringToBytes(string source) { var stringParts = source.Split('/'); var bytes = new byte[stringParts.Length - 1]; for (var i = 0; i < bytes.Length; i++) bytes[i] = (byte)int.Parse(stringParts[i]); return bytes; } private System.Drawing.Image GetImage(IDocumentData documentData, XRect bounds) { var source = Source.ParseValue(documentData, null, null, false); try { System.Drawing.Image imageData; if (File.Exists(source)) { imageData = System.Drawing.Image.FromFile(source); } else if (WebResourceExists(source, out imageData)) { } else if (!string.IsNullOrEmpty(source)) { using (var stream = new MemoryStream(LongStringToBytes(source))) { using (var image = System.Drawing.Image.FromStream(stream)) { imageData = new Bitmap(image.Width, image.Height); using (var gfx = Graphics.FromImage(imageData)) { gfx.DrawImage(image, 0, 0, image.Width, image.Height); } } } } if (imageData == null) { throw new InvalidOperationException($"Cannot generate image data for source '{source}'."); } //if (imageData == null) //{ // imageData = new Bitmap((int)bounds.Width, (int)bounds.Height); // using (var gfx = Graphics.FromImage(imageData)) // { // var pen = new Pen(Color.Red); // gfx.DrawLine(pen, 0, 0, imageData.Width, imageData.Height); // gfx.DrawLine(pen, imageData.Width, 0, 0, imageData.Height); // var font = new System.Drawing.Font("Verdana", 10); // var brush = new SolidBrush(Color.DarkRed); // gfx.DrawString(string.Format("Image '{0}' is missing.", source), font, brush, 0, 0); // } //} return imageData; } catch (Exception exception) { exception.AddData("source", source); throw; } } private bool WebResourceExists(string image, out System.Drawing.Image imageData) { try { imageData = null; if (string.IsNullOrEmpty(image)) return false; Uri path; if (Uri.TryCreate(image, UriKind.Absolute, out path)) { if (CacheMode != ECacheMode.Never) { if (WebResourceByCache(image, ref imageData)) { return true; } } if (WebResourceDirectly(image, ref imageData)) { return true; } return false; } else { var encoding = Encoding.GetEncoding(1252); var bytes = encoding.GetBytes(image); using (var ms = new MemoryStream(bytes)) { imageData = System.Drawing.Image.FromStream(ms); } return true; } } catch (Exception exception) { exception.AddData("image", image); throw; } } private static bool WebResourceDirectly(string image, ref System.Drawing.Image imageData) { using (var client = new WebClient()) { using (var stream = client.OpenRead(image)) { if (stream != null) { imageData = System.Drawing.Image.FromStream(stream); return true; } return false; } } } private bool WebResourceByCache(string image, ref System.Drawing.Image imageData) { var localName = image.Substring(image.IndexOf(":", StringComparison.Ordinal) + 3).Replace("/", "_").Replace("?", "_").Replace("=", "_").Replace("&", "_").Replace(":", "_"); var cacheFileName = string.Format("{0}{1}", Path.GetTempPath(), localName); if (!File.Exists(cacheFileName)) { try { using (var client = new WebClient()) { client.DownloadFile(image, cacheFileName); } } catch (WebException exception) { if (File.Exists(cacheFileName)) { File.Delete(cacheFileName); } if (CacheMode == ECacheMode.Always) { throw new InvalidOperationException("Unable to download image file to file.", exception).AddData("cacheFileName", cacheFileName); } return false; } } try { imageData = System.Drawing.Image.FromFile(cacheFileName); } catch (OutOfMemoryException exception) { exception.AddData("cacheFileName", cacheFileName); throw; } return true; } internal override XmlElement ToXme() { var xme = base.ToXme(); if (_source != null) xme.SetAttribute("Source", _source); if (_cacheMode != null) xme.SetAttribute("CacheMode", _cacheMode.ToString()); return xme; } internal static Image Load(XmlElement xme) { var image = new Image(); image.AppendData(xme); var xmlSource = xme.Attributes["Source"]; if (xmlSource != null) image.Source = xmlSource.Value; if (xme.Attributes["CacheMode"] != null) image.CacheMode = (ECacheMode)Enum.Parse(typeof(ECacheMode), xme.Attributes["CacheMode"].Value); return image; } } }
/* * Copyright 2013 Splunk, 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. */ namespace Splunk { using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// The <see cref="Event"/> class wraps an individual event or result that /// was returned by the <see cref="ResultsReader"/> class. /// An event maps each field name to an instance of /// <see cref="Event.FieldValue"/> class, which is a list of zero of more /// values. /// </summary> public class Event : Dictionary<string, Event.FieldValue> { /// <summary> /// Gets the XML markup for the <code>"_raw"</code> field value. This /// value is only used by the <see cref="ResultsReaderXml"/> class. /// <remarks> /// The return value is different than that of /// the <code>"_raw"</code> field value /// in that this segmented raw value is an XML fragment that includes all /// markup such as XML tags and escaped characters. /// For example, <code>anEvent["_raw"]</code> field value returns this: /// <code> /// <![CDATA[ /// "http://localhost:8000/en-US/app/search/flashtimeline?q=search%20search%20index%3D_internal%20%7C%20head%2010&earliest=rt-1h&latest=rt" /// ]]> /// </code> /// <code>anEvent.SegmentedRaw</code> returns this: /// <code> /// <v xml:space="preserve" trunc="0">"http://localhost:8000/en-US/app/<sg h="1">search</sg>/flashtimeline?q=<sg h="1">search</sg>%20<sg h="1">search</sg>%20index%3D_internal%20%7C%20head%2010&amp;earliest=rt-1h&amp;latest=rt"</v> /// </code> /// </remarks> /// </summary> public string SegmentedRaw { get; internal set; } /// <summary> /// A field can be accessed as either an <see cref="Array"/> /// or as a delimited string (using an implicit string converter or /// <see cref="GetArray()"/>). Splunk recommends accessing values as an /// array when possible. /// </summary> /// <remarks> /// <para> /// The delimiter for field values depends on the underlying /// result format. If the underlying format does not specify /// a delimiter, such as with the <see cref="ResultsReaderXml"/> class, /// the delimiter is <see cref="DefaultDelimiter"/>, /// which is a comma (,). /// </para> /// </remarks> // Note that the type conversion methods are not from IConvertible. // That is primarily because IConvertible methods require // IFormatProvider parameter which make it // not as easy to use. System.Convert methods do not require // IFormatProvider parameter. public class FieldValue { /// <summary> /// A single value or delimited set of values. /// Null if <see cref="arrayValues"/> is used. /// </summary> private string singleOrDelimited; /// <summary> /// An array of values. Null if <see cref="singleOrDelimited"/> /// is used. /// </summary> private string[] arrayValues; /// <summary> /// The default delimiter, which is a comma (,). /// </summary> public const string DefaultDelimiter = ","; /// <summary> /// Initializes a new instance of the <see cref="Event.FieldValue"/> /// class. /// </summary> /// <param name="singleOrDelimited"> /// The single value or delimited set of values. /// </param> public FieldValue(string singleOrDelimited) { this.singleOrDelimited = singleOrDelimited; } /// <summary> /// Initializes a new instance of the <see cref="Event.FieldValue"/> /// class. /// </summary> /// <param name="arrayValues">Array of values.</param> public FieldValue(string[] arrayValues) { this.arrayValues = arrayValues; } /// <summary> /// Gets the values for the field. /// </summary> /// <remarks> /// <b>Caution:</b> This variant of the <b>GetArray</b> method /// is unsafe for <see cref="ResultsReader"/> implementations that /// require a delimiter. Therefore, this method should only be /// used for results that are returned by /// <see cref="ResultsReaderXml"/>. For other readers, use the /// <see cref="GetArray(String)"/> method instead. /// If the underlying <see cref="ResultsReader"/> object has /// no delimiter, the original array of values is returned. /// If the object does have a delimiter, the single/delimited value /// is split based on the /// <see cref="DefaultDelimiter"/> and is returned as an array. /// </remarks> /// <returns> /// The original array of values if there is no delimiter, or the /// array of values split by the delimiter. /// </returns> public string[] GetArray() { return this.GetArray(DefaultDelimiter); } /// <summary> /// Gets the values for the field. /// </summary> /// <remarks> /// The delimiter must be determined empirically based on the search /// string and the data format of the index. The delimiter can /// differ between fields in the same <see cref="Event"/>. /// <para> /// If the underlying <see cref="ResultsReader"/> object has /// no delimiter, the original array of values is returned. /// If the object does have a delimiter, the single/delimited value /// is split based on the specified delimiter /// and is returned as an array. /// </para> /// </remarks> /// <param name="delimiter">The delimiter, which is be passed to /// <see cref="System.String.Split(string[], StringSplitOptions)"/> /// to perform the split.</param> /// <returns> /// The original array of values if there is no delimiter, /// or the array of values split by the delimiter. /// </returns> public string[] GetArray(string delimiter) { return this.arrayValues ?? this.singleOrDelimited.Split( new string[] { delimiter }, StringSplitOptions.None); } /// <summary> /// Returns the single value or delimited set of values for the /// field. /// </summary> /// <remarks> /// <para> /// When getting a multi-valued field, use the /// <see cref="GetArray()"/> methods instead. /// </para> /// </remarks> /// <returns>The single value or set of values delimited by /// <see cref="DefaultDelimiter"/>. /// </returns> public override string ToString() { return this.singleOrDelimited ?? string.Join( DefaultDelimiter, this.arrayValues); } /// <summary> /// Converts a <see cref="FieldValue"/> to a <c>string</c>. /// Same as <see cref="ToString"/> /// </summary> /// <remarks> /// <para> /// When getting a multi-valued field, use the /// <see cref="GetArray()"/> methods instead. /// </para> /// </remarks> /// <param name="value">Field value</param> /// <returns>The single value or set of values delimited by the /// <see cref="DefaultDelimiter"/>. /// </returns> public static implicit operator string(FieldValue value) { return value.ToString(); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>double</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator double(Event.FieldValue value) { return Convert.ToDouble(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>float</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator float(Event.FieldValue value) { return Convert.ToSingle(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>byte</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator byte(Event.FieldValue value) { return Convert.ToByte(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>ushort</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator ushort(Event.FieldValue value) { return Convert.ToUInt16(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>uint</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator uint(Event.FieldValue value) { return Convert.ToUInt32(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>ulong</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator ulong(Event.FieldValue value) { return Convert.ToUInt64(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>sbyte</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator sbyte(Event.FieldValue value) { return Convert.ToSByte(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>short</c>/. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator short(Event.FieldValue value) { return Convert.ToInt16(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>int</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator int(Event.FieldValue value) { return Convert.ToInt32(value.ToString()); } /// <summary> /// Converts an <see cref="Event.FieldValue"/> to a <c>ulong</c>. /// </summary> /// <param name="value">The field value.</param> /// <returns>The converted value.</returns> public static explicit operator long(Event.FieldValue value) { return Convert.ToInt64(value.ToString()); } /// <summary> /// Converts to a <c>byte</c>. /// </summary> /// <returns>The converted value.</returns> public byte ToByte() { return Convert.ToByte(this.ToString()); } /// <summary> /// Converts to a <c>ushort</c>. /// </summary> /// <returns>The converted value.</returns> public ushort ToUInt16() { return Convert.ToUInt16(this.ToString()); } /// <summary> /// Converts to a <c>uint</c>. /// </summary> /// <returns>The converted value.</returns> public uint ToUInt32() { return Convert.ToUInt32(this.ToString()); } /// <summary> /// Converts to a <c>ulong</c>. /// </summary> /// <returns>The converted value</returns> public ulong ToUInt64() { return Convert.ToUInt64(this.ToString()); } /// <summary> /// Converts to a <c>sbyte</c>. /// </summary> /// <returns>The converted value.</returns> public sbyte ToSByte() { return Convert.ToSByte(this.ToString()); } /// <summary> /// Converts to a <c>short</c>/. /// </summary> /// <returns>The converted value.</returns> public short ToInt16() { return Convert.ToInt16(this.ToString()); } /// <summary> /// Converts to a <c>int</c>. /// </summary> /// <returns>The converted value</returns> public int ToInt32() { return Convert.ToInt32(this.ToString()); } /// <summary> /// Converts to a <c>ulong</c>. /// </summary> /// <returns>The converted value.</returns> public long ToInt64() { return Convert.ToInt64(this.ToString()); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Web; using IList = System.Collections.IList; #endregion /// <summary> /// Represents an error log capable of storing and retrieving errors /// generated in an ASP.NET Web application. /// </summary> public abstract class ErrorLog { private string _appName; private bool _appNameInitialized; private static readonly object _contextKey = new object(); /// <summary> /// Logs an error in log for the application. /// </summary> public abstract string Log(Error error); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="Log"/>. /// </summary> public virtual IAsyncResult BeginLog(Error error, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new LogHandler(Log), error); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="Log"/>. /// </summary> public virtual string EndLog(IAsyncResult asyncResult) { return (string) EndSyncImpl(asyncResult); } private delegate string LogHandler(Error error); /// <summary> /// Retrieves a single application error from log given its /// identifier, or null if it does not exist. /// </summary> public abstract ErrorLogEntry GetError(string id); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="GetError"/>. /// </summary> public virtual IAsyncResult BeginGetError(string id, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new GetErrorHandler(GetError), id); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="GetError"/>. /// </summary> public virtual ErrorLogEntry EndGetError(IAsyncResult asyncResult) { return (ErrorLogEntry) EndSyncImpl(asyncResult); } private delegate ErrorLogEntry GetErrorHandler(string id); /// <summary> /// Retrieves a page of application errors from the log in /// descending order of logged time. /// </summary> public abstract int GetErrors(int pageIndex, int pageSize, IList errorEntryList); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="GetErrors"/>. /// </summary> public virtual IAsyncResult BeginGetErrors(int pageIndex, int pageSize, IList errorEntryList, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new GetErrorsHandler(GetErrors), pageIndex, pageSize, errorEntryList); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="GetErrors"/>. /// </summary> public virtual int EndGetErrors(IAsyncResult asyncResult) { return (int) EndSyncImpl(asyncResult); } private delegate int GetErrorsHandler(int pageIndex, int pageSize, IList errorEntryList); /// <summary> /// Get the name of this log. /// </summary> public virtual string Name { get { return this.GetType().Name; } } /// <summary> /// Gets the name of the application to which the log is scoped. /// </summary> public string ApplicationName { get { return Mask.NullString(_appName); } set { if (_appNameInitialized) throw new InvalidOperationException("The application name cannot be reset once initialized."); _appName = value; _appNameInitialized = Mask.NullString(value).Length > 0; } } /// <summary> /// Gets the default error log implementation specified in the /// configuration file, or the in-memory log implemention if /// none is configured. /// </summary> [ Obsolete("Use ErrorLog.GetDefault(context) instead.") ] public static ErrorLog Default { get { return GetDefault(HttpContext.Current); } } /// <summary> /// Gets the default error log implementation specified in the /// configuration file, or the in-memory log implemention if /// none is configured. /// </summary> public static ErrorLog GetDefault(HttpContext context) { return (ErrorLog) ServiceCenter.GetService(context, typeof(ErrorLog)); } internal static ErrorLog GetDefaultImpl(HttpContext context) { ErrorLog log; if (context != null) { log = (ErrorLog) context.Items[_contextKey]; if (log != null) return log; } // // Determine the default store type from the configuration and // create an instance of it. // log = (ErrorLog) SimpleServiceProviderFactory.CreateFromConfigSection(Configuration.GroupSlash + "errorLog"); // // If no object got created (probably because the right // configuration settings are missing) then default to // the in-memory log implementation. // if (log == null) log = new MemoryErrorLog(); if (context != null) { // // Infer the application name from the context if it has not // been initialized so far. // if (log.ApplicationName.Length == 0) log.ApplicationName = InferApplicationName(context); // // Save into the context if context is there so retrieval is // quick next time. // context.Items[_contextKey] = log; } return log; } private static string InferApplicationName(HttpContext context) { Debug.Assert(context != null); #if NET_1_1 || NET_1_0 return HttpRuntime.AppDomainAppId; #else // // Setup the application name (ASP.NET 2.0 or later). // string appName = null; if (context.Request != null) { // // ASP.NET 2.0 returns a different and more cryptic value // for HttpRuntime.AppDomainAppId comared to previous // versions. Also HttpRuntime.AppDomainAppId is not available // in partial trust environments. However, the APPL_MD_PATH // server variable yields the same value as // HttpRuntime.AppDomainAppId did previously so we try to // get to it over here for compatibility reasons (otherwise // folks upgrading to this version of ELMAH could find their // error log empty due to change in application name. // appName = context.Request.ServerVariables["APPL_MD_PATH"]; } if (string.IsNullOrEmpty(appName)) { // // Still no luck? Try HttpRuntime.AppDomainAppVirtualPath, // which is available even under partial trust. // appName = HttpRuntime.AppDomainAppVirtualPath; } return Mask.EmptyString(appName, "/"); #endif } // // The following two methods are helpers that provide boilerplate // implementations for implementing asnychronous BeginXXXX and // EndXXXX methods over a default synchronous implementation. // private static IAsyncResult BeginSyncImpl(AsyncCallback asyncCallback, object asyncState, Delegate syncImpl, params object[] args) { Debug.Assert(syncImpl != null); SynchronousAsyncResult asyncResult; string syncMethodName = syncImpl.Method.Name; try { asyncResult = SynchronousAsyncResult.OnSuccess(syncMethodName, asyncState, syncImpl.DynamicInvoke(args)); } catch (Exception e) { asyncResult = SynchronousAsyncResult.OnFailure(syncMethodName, asyncState, e); } if (asyncCallback != null) asyncCallback(asyncResult); return asyncResult; } private static object EndSyncImpl(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); SynchronousAsyncResult syncResult = asyncResult as SynchronousAsyncResult; if (syncResult == null) throw new ArgumentException("IAsyncResult object did not come from the corresponding async method on this type.", "asyncResult"); // // IMPORTANT! The End method on SynchronousAsyncResult will // throw an exception if that's what Log did when // BeginLog called it. The unforunate side effect of this is // the stack trace information for the exception is lost and // reset to this point. There seems to be a basic failure in the // framework to accommodate for this case more generally. One // could handle this through a custom exception that wraps the // original exception, but this assumes that an invocation will // only throw an exception of that custom type. // return syncResult.End(); } } }
// 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.Threading { using System; using System.Security; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using Microsoft.Win32.SafeHandles; public delegate void TimerCallback(Object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM, // to schedule all managed timers in the AppDomain. // // Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire. // There are roughly two types of timer: // // - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because // the whole point is that the timer only fires if something has gone wrong. // // - scheduled background tasks. These typically do fire, but they usually have quite long durations. // So the impact of spending a few extra cycles to fire these is negligible. // // Because of this, we want to choose a data structure with very fast insert and delete times, but we can live // with linear traversal times when firing timers. // // The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion // and removal, and O(N) traversal when finding expired timers. // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // internal class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. private static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { get { return s_queue; } } private TimerQueue() { // empty private constructor to ensure we remain a singleton. } #endregion #region interface to native per-AppDomain timer // // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. // private static int TickCount { get { #if !FEATURE_PAL if (Environment.IsWindows8OrAbove) { ulong time100ns; bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns); if (!result) throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()); // convert to 100ns to milliseconds, and truncate to 32 bits. return (int)(uint)(time100ns / 10000); } else #endif { return Environment.TickCount; } } } // // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded. // private class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(true) { } protected override bool ReleaseHandle() { return DeleteAppDomainTimer(handle); } } private AppDomainTimerSafeHandle m_appDomainTimer; private bool m_isAppDomainTimerScheduled; private int m_currentAppDomainTimerStartTicks; private uint m_currentAppDomainTimerDuration; private bool EnsureAppDomainTimerFiresBy(uint requestedDuration) { // // The VM's timer implementation does not work well for very long-duration timers. // See kb 950807. // So we'll limit our native timer duration to a "small" value. // This may cause us to attempt to fire timers early, but that's ok - // we'll just see that none of our timers has actually reached its due time, // and schedule the native timer again. // const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); if (m_isAppDomainTimerScheduled) { uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks); if (elapsed >= m_currentAppDomainTimerDuration) return true; //the timer's about to fire uint remainingDuration = m_currentAppDomainTimerDuration - elapsed; if (actualDuration >= remainingDuration) return true; //the timer will fire earlier than this request } // If Pause is underway then do not schedule the timers // A later update during resume will re-schedule if (m_pauseTicks != 0) { Debug.Assert(!m_isAppDomainTimerScheduled); Debug.Assert(m_appDomainTimer == null); return true; } if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { Debug.Assert(!m_isAppDomainTimerScheduled); m_appDomainTimer = CreateAppDomainTimer(actualDuration); if (!m_appDomainTimer.IsInvalid) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } else { if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration)) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } } // // The VM calls this when the native timer fires. // internal static void AppDomainTimerCallback() { Instance.FireNextTimers(); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool DeleteAppDomainTimer(IntPtr handle); #endregion #region Firing timers // // The list of timers // private TimerQueueTimer m_timers; private volatile int m_pauseTicks = 0; // Time when Pause was called // // Fire any timers that have expired, and update the native timer to schedule the rest of them. // private void FireNextTimers() { // // we fire the first timer on this thread; any other timers that might have fired are queued // to the ThreadPool. // TimerQueueTimer timerToFireOnThisThread = null; lock (this) { // prevent ThreadAbort while updating state try { } finally { // // since we got here, that means our previous timer has fired. // m_isAppDomainTimerScheduled = false; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; int nowTicks = TickCount; // // Sweep through all timers. The ones that have reached their due time // will fire. We will calculate the next native timer due time from the // other timers. // TimerQueueTimer timer = m_timers; while (timer != null) { Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) { // // Remember the next timer in case we delete this one // TimerQueueTimer nextTimer = timer.m_next; if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; uint elapsedForNextDueTime = elapsed - timer.m_dueTime; if (elapsedForNextDueTime < timer.m_period) { // Discount the extra amount of time that has elapsed since the previous firing time to // prevent timer ticks from drifting timer.m_dueTime = timer.m_period - elapsedForNextDueTime; } else { // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up // with the short period, have it fire 1 ms from now to avoid spinning without a delay. timer.m_dueTime = 1; } // // This is a repeating timer; schedule it to run again. // if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } } else { // // Not repeating; remove it from the queue // DeleteTimer(timer); } // // If this is the first timer, we'll fire it on this thread. Otherwise, queue it // to the ThreadPool. // if (timerToFireOnThisThread == null) timerToFireOnThisThread = timer; else QueueTimerCompletion(timer); timer = nextTimer; } else { // // This timer hasn't fired yet. Just update the next time the native timer fires. // uint remaining = timer.m_dueTime - elapsed; if (remaining < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = remaining; } timer = timer.m_next; } } if (haveTimerToSchedule) EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } // // Fire the user timer outside of the lock! // if (timerToFireOnThisThread != null) timerToFireOnThisThread.Fire(); } private static void QueueTimerCompletion(TimerQueueTimer timer) { WaitCallback callback = s_fireQueuedTimerCompletion; if (callback == null) s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion); // Can use "unsafe" variant because we take care of capturing and restoring // the ExecutionContext. ThreadPool.UnsafeQueueUserWorkItem(callback, timer); } private static WaitCallback s_fireQueuedTimerCompletion; private static void FireQueuedTimerCompletion(object state) { ((TimerQueueTimer)state).Fire(); } #endregion #region Queue implementation public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { if (timer.m_dueTime == Timeout.UnsignedInfinite) { // the timer is not in the list; add it (as the head of the list). timer.m_next = m_timers; timer.m_prev = null; if (timer.m_next != null) timer.m_next.m_prev = timer; m_timers = timer; } timer.m_dueTime = dueTime; timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period; timer.m_startTicks = TickCount; return EnsureAppDomainTimerFiresBy(dueTime); } public void DeleteTimer(TimerQueueTimer timer) { if (timer.m_dueTime != Timeout.UnsignedInfinite) { if (timer.m_next != null) timer.m_next.m_prev = timer.m_prev; if (timer.m_prev != null) timer.m_prev.m_next = timer.m_next; if (m_timers == timer) m_timers = timer.m_next; timer.m_dueTime = Timeout.UnsignedInfinite; timer.m_period = Timeout.UnsignedInfinite; timer.m_startTicks = 0; timer.m_prev = null; timer.m_next = null; } } #endregion } // // A timer in our TimerQueue. // internal sealed class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. // // The first four fields are maintained by TimerQueue itself. // internal TimerQueueTimer m_next; internal TimerQueueTimer m_prev; // // The time, according to TimerQueue.TickCount, when this timer's current interval started. // internal int m_startTicks; // // Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire. // internal uint m_dueTime; // // Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval. // internal uint m_period; // // Info about the user's callback // private readonly TimerCallback m_timerCallback; private readonly Object m_state; private readonly ExecutionContext m_executionContext; // // When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only // after all pending callbacks are complete. We set m_canceled to prevent any callbacks that // are already queued from running. We track the number of callbacks currently executing in // m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning // reaches zero. // private int m_callbacksRunning; private volatile bool m_canceled; private volatile WaitHandle m_notifyWhenNoCallbacksRunning; internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period) { m_timerCallback = timerCallback; m_state = state; m_dueTime = Timeout.UnsignedInfinite; m_period = Timeout.UnsignedInfinite; m_executionContext = ExecutionContext.Capture(); // // After the following statement, the timer may fire. No more manipulation of timer state outside of // the lock is permitted beyond this point! // if (dueTime != Timeout.UnsignedInfinite) Change(dueTime, period); } internal bool Change(uint dueTime, uint period) { bool success; lock (TimerQueue.Instance) { if (m_canceled) throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); // prevent ThreadAbort while updating state try { } finally { m_period = period; if (dueTime == Timeout.UnsignedInfinite) { TimerQueue.Instance.DeleteTimer(this); success = true; } else { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true); success = TimerQueue.Instance.UpdateTimer(this, dueTime, period); } } } return success; } public void Close() { lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (!m_canceled) { m_canceled = true; TimerQueue.Instance.DeleteTimer(this); } } } } public bool Close(WaitHandle toSignal) { bool success; bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (m_canceled) { success = false; } else { m_canceled = true; m_notifyWhenNoCallbacksRunning = toSignal; TimerQueue.Instance.DeleteTimer(this); if (m_callbacksRunning == 0) shouldSignal = true; success = true; } } } if (shouldSignal) SignalNoCallbacksRunning(); return success; } internal void Fire() { bool canceled = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { canceled = m_canceled; if (!canceled) m_callbacksRunning++; } } if (canceled) return; CallCallback(); bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { m_callbacksRunning--; if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null) shouldSignal = true; } } if (shouldSignal) SignalNoCallbacksRunning(); } internal void SignalNoCallbacksRunning() { Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); } internal void CallCallback() { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty); // call directly if EC flow is suppressed if (m_executionContext == null) { m_timerCallback(m_state); } else { ExecutionContext.Run(m_executionContext, s_callCallbackInContext, this); } } private static readonly ContextCallback s_callCallbackInContext = state => { TimerQueueTimer t = (TimerQueueTimer)state; t.m_timerCallback(t.m_state); }; } // // TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer // if the Timer is collected. // This is necessary because Timer itself cannot use its finalizer for this purpose. If it did, // then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize. // You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this // via first-class APIs), but Timer has never offered this, and adding it now would be a breaking // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // internal sealed class TimerHolder { internal TimerQueueTimer m_timer; public TimerHolder(TimerQueueTimer timer) { m_timer = timer; } ~TimerHolder() { // // If shutdown has started, another thread may be suspended while holding the timer lock. // So we can't safely close the timer. // // Similarly, we should not close the timer during AD-unload's live-object finalization phase. // A rude abort may have prevented us from releasing the lock. // // Note that in either case, the Timer still won't fire, because ThreadPool threads won't be // allowed to run in this AppDomain. // if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()) return; m_timer.Close(); } public void Close() { m_timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = m_timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } } public sealed class Timer : MarshalByRefObject, IDisposable { private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder m_timer; public Timer(TimerCallback callback, Object state, int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_TimeoutTooLarge); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge); TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm); } [CLSCompliant(false)] public Timer(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { TimerSetup(callback, state, dueTime, period); } public Timer(TimerCallback callback, Object state, long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } public Timer(TimerCallback callback) { int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period); } private void TimerSetup(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { if (callback == null) throw new ArgumentNullException(nameof(TimerCallback)); Contract.EndContractBlock(); m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period)); } public bool Change(int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(UInt32 dueTime, UInt32 period) { return m_timer.m_timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject == null) throw new ArgumentNullException(nameof(notifyObject)); Contract.EndContractBlock(); return m_timer.Close(notifyObject); } public void Dispose() { m_timer.Close(); } internal void KeepRootedWhileScheduled() { GC.SuppressFinalize(m_timer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Net; using System.Security.Principal; using System.DirectoryServices; namespace System.DirectoryServices.AccountManagement { internal partial class SAMStoreCtx : StoreCtx { private DirectoryEntry _ctxBase; private object _ctxBaseLock = new object(); // when mutating ctxBase private bool _ownCtxBase; // if true, we "own" ctxBase and must Dispose of it when we're done private bool _disposed = false; internal NetCred Credentials { get { return _credentials; } } private NetCred _credentials = null; internal AuthenticationTypes AuthTypes { get { return _authTypes; } } private AuthenticationTypes _authTypes; private ContextOptions _contextOptions; static SAMStoreCtx() { // // Load the *PropertyMappingTableByProperty and *PropertyMappingTableByWinNT tables // s_userPropertyMappingTableByProperty = new Hashtable(); s_userPropertyMappingTableByWinNT = new Hashtable(); s_groupPropertyMappingTableByProperty = new Hashtable(); s_groupPropertyMappingTableByWinNT = new Hashtable(); s_computerPropertyMappingTableByProperty = new Hashtable(); s_computerPropertyMappingTableByWinNT = new Hashtable(); s_validPropertyMap = new Dictionary<string, ObjectMask>(); s_maskMap = new Dictionary<Type, ObjectMask>(); s_maskMap.Add(typeof(UserPrincipal), ObjectMask.User); s_maskMap.Add(typeof(ComputerPrincipal), ObjectMask.Computer); s_maskMap.Add(typeof(GroupPrincipal), ObjectMask.Group); s_maskMap.Add(typeof(Principal), ObjectMask.Principal); for (int i = 0; i < s_propertyMappingTableRaw.GetLength(0); i++) { string propertyName = s_propertyMappingTableRaw[i, 0] as string; Type principalType = s_propertyMappingTableRaw[i, 1] as Type; string winNTAttribute = s_propertyMappingTableRaw[i, 2] as string; FromWinNTConverterDelegate fromWinNT = s_propertyMappingTableRaw[i, 3] as FromWinNTConverterDelegate; ToWinNTConverterDelegate toWinNT = s_propertyMappingTableRaw[i, 4] as ToWinNTConverterDelegate; Debug.Assert(propertyName != null); Debug.Assert((winNTAttribute != null && fromWinNT != null) || (fromWinNT == null)); Debug.Assert(principalType == typeof(Principal) || principalType.IsSubclassOf(typeof(Principal))); // Build the table entry. The same entry will be used in both tables. // Once constructed, the table entries are treated as read-only, so there's // no danger in sharing the entries between tables. PropertyMappingTableEntry propertyEntry = new PropertyMappingTableEntry(); propertyEntry.propertyName = propertyName; propertyEntry.suggestedWinNTPropertyName = winNTAttribute; propertyEntry.winNTToPapiConverter = fromWinNT; propertyEntry.papiToWinNTConverter = toWinNT; // Add it to the appropriate tables List<Hashtable> byPropertyTables = new List<Hashtable>(); List<Hashtable> byWinNTTables = new List<Hashtable>(); ObjectMask BitMask = 0; if (principalType == typeof(UserPrincipal)) { byPropertyTables.Add(s_userPropertyMappingTableByProperty); byWinNTTables.Add(s_userPropertyMappingTableByWinNT); BitMask = ObjectMask.User; } else if (principalType == typeof(ComputerPrincipal)) { byPropertyTables.Add(s_computerPropertyMappingTableByProperty); byWinNTTables.Add(s_computerPropertyMappingTableByWinNT); BitMask = ObjectMask.Computer; } else if (principalType == typeof(GroupPrincipal)) { byPropertyTables.Add(s_groupPropertyMappingTableByProperty); byWinNTTables.Add(s_groupPropertyMappingTableByWinNT); BitMask = ObjectMask.Group; } else { Debug.Assert(principalType == typeof(Principal)); byPropertyTables.Add(s_userPropertyMappingTableByProperty); byPropertyTables.Add(s_computerPropertyMappingTableByProperty); byPropertyTables.Add(s_groupPropertyMappingTableByProperty); byWinNTTables.Add(s_userPropertyMappingTableByWinNT); byWinNTTables.Add(s_computerPropertyMappingTableByWinNT); byWinNTTables.Add(s_groupPropertyMappingTableByWinNT); BitMask = ObjectMask.Principal; } if ((winNTAttribute == null) || (winNTAttribute == "*******")) { BitMask = ObjectMask.None; } ObjectMask currentMask; if (s_validPropertyMap.TryGetValue(propertyName, out currentMask)) { s_validPropertyMap[propertyName] = currentMask | BitMask; } else { s_validPropertyMap.Add(propertyName, BitMask); } // *PropertyMappingTableByProperty // If toWinNT is null, there's no PAPI->WinNT mapping for this property // (it's probably read-only, e.g., "LastLogon"). // if (toWinNT != null) // { foreach (Hashtable propertyMappingTableByProperty in byPropertyTables) { if (propertyMappingTableByProperty[propertyName] == null) propertyMappingTableByProperty[propertyName] = new ArrayList(); ((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry); } // } // *PropertyMappingTableByWinNT // If fromLdap is null, there's no direct WinNT->PAPI mapping for this property. // It's probably a property that requires custom handling, such as an IdentityClaim. if (fromWinNT != null) { string winNTAttributeLower = winNTAttribute.ToLower(CultureInfo.InvariantCulture); foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables) { if (propertyMappingTableByWinNT[winNTAttributeLower] == null) propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList(); ((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry); } } } } // Throws exception if ctxBase is not a computer object public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options) { Debug.Assert(ctxBase != null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path); Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer")); _ctxBase = ctxBase; _ownCtxBase = ownCtxBase; if (username != null && password != null) _credentials = new NetCred(username, password); _contextOptions = options; _authTypes = SDSUtils.MapOptionsToAuthTypes(options); } public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Dispose: disposing, ownCtxBase={0}", _ownCtxBase); if (_ownCtxBase) _ctxBase.Dispose(); _disposed = true; } } finally { base.Dispose(); } } // // StoreCtx information // // Retrieves the Path (ADsPath) of the object used as the base of the StoreCtx internal override string BasePath { get { Debug.Assert(_ctxBase != null); return _ctxBase.Path; } } // // CRUD // // Used to perform the specified operation on the Principal. They also make any needed security subsystem // calls to obtain digitial signatures. // // Insert() and Update() must check to make sure no properties not supported by this StoreCtx // have been set, prior to persisting the Principal. internal override void Insert(Principal p) { Debug.Assert(p.unpersisted == true); Debug.Assert(p.fakePrincipal == false); try { // Insert the principal into the store SDSUtils.InsertPrincipal( p, this, new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership), _credentials, _authTypes, false // handled in PushChangesToNative ); // Load in all the initial values from the store ((DirectoryEntry)p.UnderlyingObject).RefreshCache(); // Load in the StoreKey Debug.Assert(p.Key == null); // since it was previously unpersisted Debug.Assert(p.UnderlyingObject != null); // since we just persisted it Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; // We just created a principal, so it should have an objectSid Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1)); SAMStoreKey key = new SAMStoreKey( this.MachineFlatName, (byte[])de.Properties["objectSid"].Value ); p.Key = key; // Reset the change tracking p.ResetAllChangeStatus(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Insert: new SID is ", Utils.ByteArrayToString((byte[])de.Properties["objectSid"].Value)); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override void Update(Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Update"); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); Debug.Assert(p.UnderlyingObject != null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); try { // Commit the properties SDSUtils.ApplyChangesToDirectory( p, this, new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership), _credentials, _authTypes ); // Reset the change tracking p.ResetAllChangeStatus(); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override void Delete(Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Delete"); Debug.Assert(p.fakePrincipal == false); // Principal.Delete() shouldn't be calling us on an unpersisted Principal. Debug.Assert(p.unpersisted == false); Debug.Assert(p.UnderlyingObject != null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); try { SDSUtils.DeleteDirectoryEntry((DirectoryEntry)p.UnderlyingObject); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override bool AccessCheck(Principal p, PrincipalAccessMask targetPermission) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck " + targetPermission.ToString()); switch (targetPermission) { case PrincipalAccessMask.ChangePassword: PropertyValueCollection values = ((DirectoryEntry)p.GetUnderlyingObject()).Properties["UserFlags"]; if (values.Count != 0) { Debug.Assert(values.Count == 1); Debug.Assert(values[0] is int); return (SDSUtils.StatusFromAccountControl((int)values[0], PropertyNames.PwdInfoCannotChangePassword)); } Debug.Fail("SAMStoreCtx.AccessCheck: user entry has an empty UserFlags value"); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck Unable to read userAccountControl"); break; default: Debug.Fail("SAMStoreCtx.AccessCheck: Fell off end looking for " + targetPermission.ToString()); break; } return false; } internal override void Move(StoreCtx originalStore, Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Move"); } // // Special operations: the Principal classes delegate their implementation of many of the // special methods to their underlying StoreCtx // // methods for manipulating accounts /// <summary> /// This method sets the default user account control bits for the new principal /// being created in this account store. /// </summary> /// <param name="p"> Principal to set the user account control bits for </param> internal override void InitializeUserAccountControl(AuthenticablePrincipal p) { Debug.Assert(p != null); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == true); // should only ever be called for new principals // set the userAccountControl bits on the underlying directory entry DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); Type principalType = p.GetType(); if ((principalType == typeof(UserPrincipal)) || (principalType.IsSubclassOf(typeof(UserPrincipal)))) { de.Properties["userFlags"].Value = SDSUtils.SAM_DefaultUAC; } } internal override bool IsLockedOut(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); try { de.RefreshCache(); return (bool)de.InvokeGet("IsAccountLocked"); } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is System.Runtime.InteropServices.COMException) { throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); } throw; } } internal override void UnlockAccount(AuthenticablePrincipal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount"); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); // Computer accounts are never locked out, so nothing to do if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount: computer acct, skipping"); return; } DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); // After setting the property, we need to commit the change to the store. // We do it in a copy of de, so that we don't inadvertently commit any other // pending changes in de. DirectoryEntry copyOfDe = null; try { copyOfDe = SDSUtils.BuildDirectoryEntry(de.Path, _credentials, _authTypes); Debug.Assert(copyOfDe != null); copyOfDe.InvokeSet("IsAccountLocked", new object[] { false }); copyOfDe.CommitChanges(); } catch (System.Runtime.InteropServices.COMException e) { // ADSI threw an exception trying to write the change GlobalDebug.WriteLineIf(GlobalDebug.Error, "SAMStoreCtx", "UnlockAccount: caught COMException, message={0}", e.Message); throw ExceptionHelper.GetExceptionFromCOMException(e); } finally { if (copyOfDe != null) copyOfDe.Dispose(); } } // methods for manipulating passwords internal override void SetPassword(AuthenticablePrincipal p, string newPassword) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); // ********** In SAM, computer accounts don't have a set password method if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "SetPassword: computer acct, can't reset"); throw new InvalidOperationException(StringResources.SAMStoreCtxNoComputerPasswordSet); } Debug.Assert(p != null); Debug.Assert(newPassword != null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); SDSUtils.SetPassword(de, newPassword); } internal override void ChangePassword(AuthenticablePrincipal p, string oldPassword, string newPassword) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); // ********** In SAM, computer accounts don't have a change password method if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ChangePassword: computer acct, can't change"); throw new InvalidOperationException(StringResources.SAMStoreCtxNoComputerPasswordSet); } Debug.Assert(p != null); Debug.Assert(newPassword != null); // but it could be an empty string Debug.Assert(oldPassword != null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); SDSUtils.ChangePassword(de, oldPassword, newPassword); } internal override void ExpirePassword(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); // ********** In SAM, computer accounts don't have a password-expired property if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ExpirePassword: computer acct, can't expire"); throw new InvalidOperationException(StringResources.SAMStoreCtxNoComputerPasswordExpire); } WriteAttribute(p, "PasswordExpired", 1); } internal override void UnexpirePassword(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); // ********** In SAM, computer accounts don't have a password-expired property if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UnexpirePassword: computer acct, can't unexpire"); throw new InvalidOperationException(StringResources.SAMStoreCtxNoComputerPasswordExpire); } WriteAttribute(p, "PasswordExpired", 0); } private void WriteAttribute(AuthenticablePrincipal p, string attribute, int value) { Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); Debug.Assert(p != null); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; SDSUtils.WriteAttribute(de.Path, attribute, value, _credentials, _authTypes); } // // the various FindBy* methods // internal override ResultSet FindByLockoutTime( DateTime dt, MatchType matchType, Type principalType) { throw new NotSupportedException(StringResources.StoreNotSupportMethod); } internal override ResultSet FindByBadPasswordAttempt( DateTime dt, MatchType matchType, Type principalType) { throw new NotSupportedException(StringResources.StoreNotSupportMethod); } internal override ResultSet FindByLogonTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.LogonTime, matchType, dt, principalType); } internal override ResultSet FindByPasswordSetTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.PasswordSetTime, matchType, dt, principalType); } internal override ResultSet FindByExpirationTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.AccountExpirationTime, matchType, dt, principalType); } private ResultSet FindByDate( FindByDateMatcher.DateProperty property, MatchType matchType, DateTime value, Type principalType ) { // We use the same SAMQuery set that we use for query-by-example, but with a different // SAMMatcher class to perform the date-range filter. // Get the entries we'll iterate over. Write access to Children is controlled through the // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; Debug.Assert(entries != null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List<string> schemaTypes = GetSchemaFilter(principalType); // Create the ResultSet that will perform the client-side filtering SAMQuerySet resultSet = new SAMQuerySet( schemaTypes, entries, _ctxBase, -1, // no size limit this, new FindByDateMatcher(property, matchType, value)); return resultSet; } // Get groups of which p is a direct member internal override ResultSet GetGroupsMemberOf(Principal p) { // Enforced by the methods that call us Debug.Assert(p.unpersisted == false); if (!p.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: is real principal"); // No nested groups or computers as members of groups in SAM if (!(p is UserPrincipal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: not a user, returning empty set"); return new EmptySet(); } Debug.Assert(p.UnderlyingObject != null); DirectoryEntry userDE = (DirectoryEntry)p.UnderlyingObject; UnsafeNativeMethods.IADsMembers iadsMembers = (UnsafeNativeMethods.IADsMembers)userDE.Invoke("Groups"); ResultSet resultSet = new SAMGroupsSet(iadsMembers, this, _ctxBase); return resultSet; } else { // ADSI's IADsGroups doesn't work for fake principals like NT AUTHORITY\NETWORK SERVICE // We use the same SAMQuery set that we use for query-by-example, but with a different // SAMMatcher class to match groups which contain the specified principal as a member // Get the entries we'll iterate over. Write access to Children is controlled through the // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; Debug.Assert(entries != null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List<string> schemaTypes = GetSchemaFilter(typeof(GroupPrincipal)); SecurityIdentifier principalSid = p.Sid; byte[] SidB = new byte[principalSid.BinaryLength]; principalSid.GetBinaryForm(SidB, 0); if (principalSid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf: bad SID IC"); throw new InvalidOperationException(StringResources.StoreCtxNeedValueSecurityIdentityClaimToQuery); } // Create the ResultSet that will perform the client-side filtering SAMQuerySet resultSet = new SAMQuerySet( schemaTypes, entries, _ctxBase, -1, // no size limit this, new GroupMemberMatcher(SidB)); return resultSet; } } // Get groups from this ctx which contain a principal corresponding to foreignPrincipal // (which is a principal from foreignContext) internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext) { // If it's a fake principal, we don't need to do any of the lookup to find a local representation. // We'll skip straight to GetGroupsMemberOf(Principal), which will lookup the groups to which it belongs via its SID. if (foreignPrincipal.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): is fake principal"); return GetGroupsMemberOf(foreignPrincipal); } // Get the Principal's SID, so we can look it up by SID in our store SecurityIdentifier Sid = foreignPrincipal.Sid; if (Sid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no SID IC"); throw new InvalidOperationException(StringResources.StoreCtxNeedValueSecurityIdentityClaimToQuery); } // In SAM, only users can be member of SAM groups (no nested groups) UserPrincipal u = UserPrincipal.FindByIdentity(this.OwningContext, IdentityType.Sid, Sid.ToString()); // If no corresponding principal exists in this store, then by definition the principal isn't // a member of any groups in this store. if (u == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no corresponding user, returning empty set"); return new EmptySet(); } // Now that we got the principal in our store, enumerating its group membership can be handled the // usual way. return GetGroupsMemberOf(u); } // Get groups of which p is a member, using AuthZ S4U APIs for recursive membership internal override ResultSet GetGroupsMemberOfAZ(Principal p) { // Enforced by the methods that call us Debug.Assert(p.unpersisted == false); Debug.Assert(p is UserPrincipal); // Get the user SID that AuthZ will use. SecurityIdentifier Sid = p.Sid; if (Sid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: no SID IC"); throw new InvalidOperationException(StringResources.StoreCtxNeedValueSecurityIdentityClaimToQuery); } byte[] Sidb = new byte[Sid.BinaryLength]; Sid.GetBinaryForm(Sidb, 0); if (Sidb == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: Bad SID IC"); throw new ArgumentException(StringResources.StoreCtxSecurityIdentityClaimBadFormat); } try { return new AuthZSet(Sidb, _credentials, _contextOptions, this.MachineFlatName, this, _ctxBase); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } // Get members of group g internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive) { // Enforced by the methods that call us Debug.Assert(g.unpersisted == false); // Fake groups are a member of other groups, but they themselves have no members // (they don't even exist in the store) if (g.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupMembership: is fake principal, returning empty set"); return new EmptySet(); } Debug.Assert(g.UnderlyingObject != null); DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject; UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)groupDE.NativeObject; BookmarkableResultSet resultSet = new SAMMembersSet(groupDE.Path, iADsGroup, recursive, this, _ctxBase); return resultSet; } // Is p a member of g in the store? internal override bool SupportsNativeMembershipTest { get { return false; } } internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) { Debug.Fail("SAMStoreCtx.IsMemberOfInStore: Shouldn't be here."); return false; } // Can a Clear() operation be performed on the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return true; } // Can the given member be removed from the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return true; } // // Cross-store support // // Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that // represents a pointer to another store), maps that representation to the other store's StoreCtx and returns // a Principal from that other StoreCtx. The implementation of this method is highly dependent on the // details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to // interact with other StoreCtxs to fulfill the request. // // This method is typically used by ResultSet implementations, when they're iterating over a collection // (e.g., of group membership) and encounter a entry that represents a foreign principal. internal override Principal ResolveCrossStoreRefToPrincipal(object o) { Debug.Assert(o is DirectoryEntry); // Get the SID of the foreign principal DirectoryEntry foreignDE = (DirectoryEntry)o; if (foreignDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no objectSid found"); throw new PrincipalOperationException(StringResources.SAMStoreCtxCantRetrieveObjectSidForCrossStore); } Debug.Assert(foreignDE.Properties["objectSid"].Count == 1); byte[] sid = (byte[])foreignDE.Properties["objectSid"].Value; // Ask the OS to resolve the SID to its target. int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid failed, err={0}, server={1}", err, this.MachineUserSuppliedName); throw new PrincipalOperationException( String.Format(CultureInfo.CurrentCulture, StringResources.SAMStoreCtxCantResolveSidForCrossStore, err)); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid found {0} in {1}", name, domainName); // Since this is SAM, the remote principal must be an AD principal. // Build a PrincipalContext for the store which owns the principal // Use the ad default options so we turn sign and seal back on. #if USE_CTX_CACHE PrincipalContext remoteCtx = SDSCache.Domain.GetContext(domainName, _credentials, DefaultContextOptions.ADDefaultContextOption); #else PrincipalContext remoteCtx = new PrincipalContext( ContextType.Domain, domainName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), DefaultContextOptions.ADDefaultContextOption); #endif SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); Principal p = remoteCtx.QueryCtx.FindPrincipalByIdentRef( typeof(Principal), UrnScheme.SidScheme, sidObj.ToString(), DateTime.UtcNow); if (p != null) return p; else { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no matching principal"); throw new PrincipalOperationException(StringResources.SAMStoreCtxFailedFindCrossStoreTarget); } } // // Data Validation // // Returns true if AccountInfo is supported for the specified principal, false otherwise. // Used when a application tries to access the AccountInfo property of a newly-inserted // (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed. internal override bool SupportsAccounts(AuthenticablePrincipal p) { // Fake principals do not have store objects, so they certainly don't have stored account info. if (p.fakePrincipal) return false; // Both Computer and User support accounts. return true; } // Returns the set of credential types supported by this store for the specified principal. // Used when a application tries to access the PasswordInfo property of a newly-inserted // (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed. // Also used to implement AuthenticablePrincipal.SupportedCredentialTypes. internal override CredentialTypes SupportedCredTypes(AuthenticablePrincipal p) { // Fake principals do not have store objects, so they certainly don't have stored creds. if (p.fakePrincipal) return (CredentialTypes)0; CredentialTypes supportedTypes = CredentialTypes.Password; // Longhorn SAM supports certificate-based authentication if (this.IsLSAM) supportedTypes |= CredentialTypes.Certificate; return supportedTypes; } // // Construct a fake Principal to represent a well-known SID like // "\Everyone" or "NT AUTHORITY\NETWORK SERVICE" // internal override Principal ConstructFakePrincipalFromSID(byte[] sid) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "ConstructFakePrincipalFromSID: sid={0}, machine={1}", Utils.ByteArrayToString(sid), this.MachineFlatName); Principal p = Utils.ConstructFakePrincipalFromSID( sid, this.OwningContext, this.MachineUserSuppliedName, _credentials, this.MachineUserSuppliedName); // Assign it a StoreKey SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, sid); p.Key = key; return p; } // // Private data // private bool IsLSAM // IsLonghornSAM (also called MSAM or LH-SAM) { get { if (!_isLSAM.HasValue) { lock (_computerInfoLock) { if (!_isLSAM.HasValue) LoadComputerInfo(); } } Debug.Assert(_isLSAM.HasValue); return _isLSAM.Value; } } internal string MachineUserSuppliedName { get { if (_machineUserSuppliedName == null) { lock (_computerInfoLock) { if (_machineUserSuppliedName == null) LoadComputerInfo(); } } Debug.Assert(_machineUserSuppliedName != null); return _machineUserSuppliedName; } } internal string MachineFlatName { get { if (_machineFlatName == null) { lock (_computerInfoLock) { if (_machineFlatName == null) LoadComputerInfo(); } } Debug.Assert(_machineFlatName != null); return _machineFlatName; } } private object _computerInfoLock = new object(); private Nullable<bool> _isLSAM = null; private string _machineUserSuppliedName = null; private string _machineFlatName = null; // computerInfoLock must be held coming in here private void LoadComputerInfo() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo"); Debug.Assert(_ctxBase != null); Debug.Assert(SAMUtils.IsOfObjectClass(_ctxBase, "Computer")); // // Target OS version // int versionMajor; int versionMinor; if (!SAMUtils.GetOSVersion(_ctxBase, out versionMajor, out versionMinor)) { throw new PrincipalOperationException(StringResources.SAMStoreCtxUnableToRetrieveVersion); } Debug.Assert(versionMajor > 0); Debug.Assert(versionMinor >= 0); if (versionMajor >= 6) // 6.0 == Longhorn _isLSAM = true; else _isLSAM = false; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: ver={0}.{1}", versionMajor, versionMinor); // // Machine user-supplied name // // This ADSI property stores the machine name as supplied by the user in the ADsPath. // It could be a flat name or a DNS name. if (_ctxBase.Properties["Name"].Count > 0) { Debug.Assert(_ctxBase.Properties["Name"].Count == 1); _machineUserSuppliedName = (string)_ctxBase.Properties["Name"].Value; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineUserSuppliedName={0}", _machineUserSuppliedName); } else { throw new PrincipalOperationException(StringResources.SAMStoreCtxUnableToRetrieveMachineName); } // // Machine flat name // IntPtr buffer = IntPtr.Zero; try { // This function takes in a flat or DNS name, and returns the flat name of the computer int err = UnsafeNativeMethods.NetWkstaGetInfo(_machineUserSuppliedName, 100, ref buffer); if (err == 0) { UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo = (UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100)); _machineFlatName = wkstaInfo.wki100_computername; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName); } else { throw new PrincipalOperationException( String.Format( CultureInfo.CurrentCulture, StringResources.SAMStoreCtxUnableToRetrieveFlatMachineName, err)); } } finally { if (buffer != IntPtr.Zero) UnsafeNativeMethods.NetApiBufferFree(buffer); } } internal override bool IsValidProperty(Principal p, string propertyName) { ObjectMask value = ObjectMask.None; if (s_validPropertyMap.TryGetValue(propertyName, out value)) { return ((s_maskMap[p.GetType()] & value) > 0 ? true : false); } else { Debug.Assert(false); return false; } } } } // #endif // PAPI_REGSAM
//--------------------------------------------------------------------------- // // <copyright file="OleCmdHelper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This is a helper class used for interop to process the // IOleCommandTarget calls in browser hosting scenario // // History: // 06/09/03: kusumav Moved from Application.cs to separate file. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Threading; using System.Windows; using System.Security; using System.Security.Permissions; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Navigation; using System.Windows.Controls; using MS.Internal.Documents; // DocumentApplicationDocumentViewer using MS.Internal.PresentationFramework; // SecurityHelper using MS.Internal.KnownBoxes; using MS.Win32; namespace MS.Internal.AppModel { #region OleCmdHelper class // <summary> // OleCmd helper class for processing IOleCommandTarget calls in browser hosting scenario // </summary> internal sealed class OleCmdHelper : MarshalByRefObject { internal const int OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100), OLECMDERR_E_DISABLED = unchecked((int)0x80040101), OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104); internal const uint CommandUnsupported = 0; internal const uint CommandEnabled = (uint)(UnsafeNativeMethods.OLECMDF.OLECMDF_ENABLED | UnsafeNativeMethods.OLECMDF.OLECMDF_SUPPORTED); internal const uint CommandDisabled = (uint)UnsafeNativeMethods.OLECMDF.OLECMDF_SUPPORTED; // IMPORTANT: Keep this in [....] with wcp\host\inc\hostservices.idl internal static readonly Guid CGID_ApplicationCommands = new Guid(0xebbc8a63, 0x8559, 0x4892, 0x97, 0xa8, 0x31, 0xe9, 0xb0, 0xe9, 0x85, 0x91); internal static readonly Guid CGID_EditingCommands = new Guid(0xc77ce45, 0xd1c, 0x4f2a, 0xb2, 0x93, 0xed, 0xd5, 0xe2, 0x7e, 0xba, 0x47); internal OleCmdHelper() { } /// <SecurityNote> /// Critical: This code calls into _DoqueryStatus /// </SecurityNote> /// <remarks> /// The native code passes queries here only for the recognized command groups: /// standard (NULL), ApplicaitonCommands, EditingCommands. /// </remarks> [SecurityCritical] internal void QueryStatus(Guid guidCmdGroup, uint cmdId, ref uint flags) { /***IMPORTANT: Make sure to return allowed and appropriate values according to the specification of IOleCommandTarget::QueryStatus(). In particular: - OLECMDF_SUPPORTED without OLECMDF_ENABLED should not be blindly returned for unrecognized commands. - Some code in IE treats OLECMDERR_E_xxx differently from generic failures. - E_NOTIMPL is not an acceptable return value. */ if (Application.Current == null || Application.IsShuttingDown == true) { Marshal.ThrowExceptionForHR(NativeMethods.E_FAIL); } // Get values from mapping here else mark them as disabled ==> // i.e "supported but not enabled" and is the equivalent of disabled since // there is no explicit "disabled" OLECMD flag IDictionary oleCmdMappingTable = GetOleCmdMappingTable(guidCmdGroup); if (oleCmdMappingTable == null) { Marshal.ThrowExceptionForHR(OleCmdHelper.OLECMDERR_E_UNKNOWNGROUP); } CommandWithArgument command = oleCmdMappingTable[cmdId] as CommandWithArgument; if (command == null) { flags = CommandUnsupported; return; } // Go through the Dispatcher in order to use its SynchronizationContext and also // so that any application exception caused during event routing is reported via // Dispatcher.UnhandledException. // The above code is not in the callback, because it throws, and we don't want the // application to get these exceptions. (The COM Interop layer turns them into HRESULTs.) bool enabled = (bool)Application.Current.Dispatcher.Invoke( DispatcherPriority.Send, new DispatcherOperationCallback(QueryEnabled), command); flags = enabled ? CommandEnabled : CommandDisabled; } /// <SecurityNote> /// Critical: Calls the critical CommandWithArgument.QueryEnabled(). /// </SecurityNote> [SecurityCritical] private object QueryEnabled(object command) { if (Application.Current.MainWindow == null) return false; IInputElement target = FocusManager.GetFocusedElement(Application.Current.MainWindow); if (target == null) { // This will always succeed because Window is IInputElement target = (IInputElement)Application.Current.MainWindow; } return BooleanBoxes.Box(((CommandWithArgument)command).QueryEnabled(target, null)); } /// <SecurityNote> /// Critical: This code calls into ExecCommandCallback helper /// </SecurityNote> /// <remarks> /// The native code passes here only commands of the recognized command groups: /// standard (NULL), ApplicaitonCommands, EditingCommands. /// </remarks> [SecurityCritical] internal void ExecCommand(Guid guidCmdGroup, uint commandId, object arg) { if (Application.Current == null || Application.IsShuttingDown == true) { Marshal.ThrowExceptionForHR(NativeMethods.E_FAIL); } int hresult = (int)Application.Current.Dispatcher.Invoke( DispatcherPriority.Send, new DispatcherOperationCallback(ExecCommandCallback), new object[] { guidCmdGroup, commandId, arg }); // Note: ExecCommandCallback() returns an HRESULT instead of throwing for the reason // explained in QueryStatus(). if(hresult < 0) { Marshal.ThrowExceptionForHR(hresult); } } /// <SecurityNote> /// Critical:This API calls into Execute /// </SecurityNote> [SecurityCritical] private object ExecCommandCallback(object arguments) { object[] args = (object[])arguments; Invariant.Assert(args.Length == 3); Guid guidCmdGroup = (Guid)args[0]; uint commandId = (uint)args[1]; object arg = args[2]; IDictionary oleCmdMappingTable = GetOleCmdMappingTable(guidCmdGroup); if (oleCmdMappingTable == null) return OLECMDERR_E_UNKNOWNGROUP; CommandWithArgument command = oleCmdMappingTable[commandId] as CommandWithArgument; if (command == null) return OLECMDERR_E_NOTSUPPORTED; if (Application.Current.MainWindow == null) return OLECMDERR_E_DISABLED; IInputElement target = FocusManager.GetFocusedElement(Application.Current.MainWindow); if (target == null) { // This will always succeed because Window is IInputElement target = (IInputElement)Application.Current.MainWindow; } return command.Execute(target, arg) ? NativeMethods.S_OK : OLECMDERR_E_DISABLED; } /// <SecurityNote> /// Critical:This API accesses the commandmapping table and returns it /// TreatAsSafe: It returns a copy which is safe /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private IDictionary GetOleCmdMappingTable(Guid guidCmdGroup) { IDictionary mappingTable = null; if (guidCmdGroup.Equals(CGID_ApplicationCommands)) { EnsureApplicationCommandsTable(); mappingTable = _applicationCommandsMappingTable.Value; } else if(guidCmdGroup.Equals(Guid.Empty)) { EnsureOleCmdMappingTable(); mappingTable = _oleCmdMappingTable.Value; } else if (guidCmdGroup.Equals(CGID_EditingCommands)) { EnsureEditingCommandsTable(); mappingTable = _editingCommandsMappingTable.Value; } return mappingTable; } /// <SecurityNote> /// Critical: This code initializes the OleCmdMappingTable which is a critical for /// set data structure /// TreatAsSafe: All the values that it adds are predefined handlers in this class /// no external values /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void EnsureOleCmdMappingTable() { if (_oleCmdMappingTable.Value == null) { _oleCmdMappingTable.Value = new SortedList(10); //Add applevel commands here _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_SAVE, new CommandWithArgument(ApplicationCommands.Save)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_SAVEAS, new CommandWithArgument(ApplicationCommands.SaveAs)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_PRINT, new CommandWithArgument(ApplicationCommands.Print)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_CUT, new CommandWithArgument(ApplicationCommands.Cut)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_COPY, new CommandWithArgument(ApplicationCommands.Copy)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_PASTE, new CommandWithArgument(ApplicationCommands.Paste)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_PROPERTIES, new CommandWithArgument(ApplicationCommands.Properties)); //Set the Enabled property of Stop and Refresh commands correctly _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_REFRESH, new CommandWithArgument(NavigationCommands.Refresh)); _oleCmdMappingTable.Value.Add((uint)UnsafeNativeMethods.OLECMDID.OLECMDID_STOP, new CommandWithArgument(NavigationCommands.BrowseStop)); } } /// <SecurityNote> /// Critical: This code initializes the OleCmdMappingTable which is a critical for /// set data structure /// TreatAsSafe: All the values that it adds are predefined handlers in this class /// no external values /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void EnsureApplicationCommandsTable() { if (_applicationCommandsMappingTable.Value == null) { /* we want to possible add 26 entries, so the capacity should be * 26/0.72 = 19 for default of 1.0 load factor*/ _applicationCommandsMappingTable.Value = new Hashtable(19); //Add applevel commands here // Note: The keys are added as uint type so that the default container comparer works // when we try to look up a command by a uint cmdid. _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Cut, new CommandWithArgument(ApplicationCommands.Cut)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Copy, new CommandWithArgument(ApplicationCommands.Copy)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Paste, new CommandWithArgument(ApplicationCommands.Paste)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_SelectAll, new CommandWithArgument(ApplicationCommands.SelectAll)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Find, new CommandWithArgument(ApplicationCommands.Find)); // Add standard navigation commands _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Refresh, new CommandWithArgument(NavigationCommands.Refresh)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Stop, new CommandWithArgument(NavigationCommands.BrowseStop)); // add document viewer commands _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Digitalsignatures_SignDocument, new CommandWithArgument(DocumentApplicationDocumentViewer.Sign)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Digitalsignatures_RequestSignature, new CommandWithArgument(DocumentApplicationDocumentViewer.RequestSigners)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Digitalsignatures_ViewSignature, new CommandWithArgument(DocumentApplicationDocumentViewer.ShowSignatureSummary)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Permission_Set, new CommandWithArgument(DocumentApplicationDocumentViewer.ShowRMPublishingUI)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Permission_View, new CommandWithArgument(DocumentApplicationDocumentViewer.ShowRMPermissions)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.Edit_Permission_Restrict, new CommandWithArgument(DocumentApplicationDocumentViewer.ShowRMCredentialManager)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_In, new CommandWithArgument(NavigationCommands.IncreaseZoom)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_Out, new CommandWithArgument(NavigationCommands.DecreaseZoom)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_400, new CommandWithArgument(NavigationCommands.Zoom, 400)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_250, new CommandWithArgument(NavigationCommands.Zoom, 250)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_150, new CommandWithArgument(NavigationCommands.Zoom, 150)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_100, new CommandWithArgument(NavigationCommands.Zoom, 100)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_75, new CommandWithArgument(NavigationCommands.Zoom, 75)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_50, new CommandWithArgument(NavigationCommands.Zoom, 50)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_25, new CommandWithArgument(NavigationCommands.Zoom, 25)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_PageWidth, new CommandWithArgument(DocumentViewer.FitToWidthCommand)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_WholePage, new CommandWithArgument(DocumentViewer.FitToHeightCommand)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_TwoPages, new CommandWithArgument(DocumentViewer.FitToMaxPagesAcrossCommand, 2)); _applicationCommandsMappingTable.Value.Add((uint)AppCommands.View_Zoom_Thumbnails, new CommandWithArgument(DocumentViewer.ViewThumbnailsCommand)); } } /// <SecurityNote> /// Critical: Initializes _editingCommandsMappingTable, which is a critical for set. /// TreatAsSafe: Only predefined commands are used. EditingCommands are enabled in partial trust. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void EnsureEditingCommandsTable() { if (_editingCommandsMappingTable.Value == null) { _editingCommandsMappingTable.Value = new SortedList(2); // Note: The keys are added as uint type so that the default container comparer works // when we try to look up a command by a uint cmdid. _editingCommandsMappingTable.Value.Add((uint)EditingCommandIds.Backspace, new CommandWithArgument(System.Windows.Documents.EditingCommands.Backspace)); _editingCommandsMappingTable.Value.Add((uint)EditingCommandIds.Delete, new CommandWithArgument(System.Windows.Documents.EditingCommands.Delete)); } } private SecurityCriticalDataForSet<SortedList> _oleCmdMappingTable; private SecurityCriticalDataForSet<Hashtable> _applicationCommandsMappingTable; private SecurityCriticalDataForSet<SortedList> _editingCommandsMappingTable; } #endregion OleCmdHelper class #region CommandAndArgument class /// <summary> /// This wrapper class helps store default arguments for commands. /// The primary scenario for this class is the Zoom command where we /// have multiple menu items and want to fire a single event with an /// argument. We cannot attach an argument value to the native menu /// item so when we do the translation we add it. /// </summary> internal class CommandWithArgument { /// <SecurityNote> /// Critical: This can be used to spoof paste command /// </SecurityNote> [SecurityCritical] public CommandWithArgument(RoutedCommand command) : this(command, null) { } /// <SecurityNote> /// Critical: This can be used to spoof paste command /// </SecurityNote> [SecurityCritical] public CommandWithArgument(RoutedCommand command, object argument) { _command = new SecurityCriticalDataForSet<RoutedCommand>(command); _argument = argument; } /// <SecurityNote> /// Critical:This API calls into ExecuteCore and CriticalCanExecute /// </SecurityNote> [SecurityCritical] public bool Execute(IInputElement target, object argument) { if (argument == null) { argument = _argument; } // ISecureCommand is used to enforce user-initiated invocation. Cut, Copy and Paste // are marked as such. See ApplicationCommands.GetRequiredPermissions. if (_command.Value is ISecureCommand) { bool unused; if (_command.Value.CriticalCanExecute(argument, target, /* trusted: */ true, out unused)) { _command.Value.ExecuteCore(argument, target, /* userInitiated: */ true); return true; } return false; } if (_command.Value.CanExecute(argument, target)) { _command.Value.Execute(argument, target); return true; } return false; } /// <SecurityNote> /// Critical: This code calls into Routedcommand.QueryStatus /// with a trusted bit, that can be used to cause an elevation. /// </SecurityNote> [SecurityCritical] public bool QueryEnabled(IInputElement target, object argument) { if (argument == null) { argument = _argument; } // ISecureCommand is used to enforce user-initiated invocation. Cut, Copy and Paste // are marked as such. See ApplicationCommands.GetRequiredPermissions. if (_command.Value is ISecureCommand) { bool unused; return _command.Value.CriticalCanExecute(argument, target, /* trusted: */ true, out unused); } return _command.Value.CanExecute(argument, target); } public RoutedCommand Command { get { return _command.Value; } } private object _argument; /// <SecurityNote> /// Critical: This data is critical for set since it is used to make a security decision /// </SecurityNote> private SecurityCriticalDataForSet<RoutedCommand> _command; } #endregion }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics associated with a physical network interface /// First published in XenServer 4.0. /// </summary> public partial class PIF_metrics : XenObject<PIF_metrics> { #region Constructors public PIF_metrics() { } public PIF_metrics(string uuid, double io_read_kbs, double io_write_kbs, bool carrier, string vendor_id, string vendor_name, string device_id, string device_name, long speed, bool duplex, string pci_bus_path, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.carrier = carrier; this.vendor_id = vendor_id; this.vendor_name = vendor_name; this.device_id = device_id; this.device_name = device_name; this.speed = speed; this.duplex = duplex; this.pci_bus_path = pci_bus_path; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new PIF_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public PIF_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new PIF_metrics from a Proxy_PIF_metrics. /// </summary> /// <param name="proxy"></param> public PIF_metrics(Proxy_PIF_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PIF_metrics. /// </summary> public override void UpdateFrom(PIF_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; carrier = update.carrier; vendor_id = update.vendor_id; vendor_name = update.vendor_name; device_id = update.device_id; device_name = update.device_name; speed = update.speed; duplex = update.duplex; pci_bus_path = update.pci_bus_path; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFrom(Proxy_PIF_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); carrier = (bool)proxy.carrier; vendor_id = proxy.vendor_id == null ? null : proxy.vendor_id; vendor_name = proxy.vendor_name == null ? null : proxy.vendor_name; device_id = proxy.device_id == null ? null : proxy.device_id; device_name = proxy.device_name == null ? null : proxy.device_name; speed = proxy.speed == null ? 0 : long.Parse(proxy.speed); duplex = (bool)proxy.duplex; pci_bus_path = proxy.pci_bus_path == null ? null : proxy.pci_bus_path; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_PIF_metrics ToProxy() { Proxy_PIF_metrics result_ = new Proxy_PIF_metrics(); result_.uuid = uuid ?? ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.carrier = carrier; result_.vendor_id = vendor_id ?? ""; result_.vendor_name = vendor_name ?? ""; result_.device_id = device_id ?? ""; result_.device_name = device_name ?? ""; result_.speed = speed.ToString(); result_.duplex = duplex; result_.pci_bus_path = pci_bus_path ?? ""; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PIF_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("io_read_kbs")) io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); if (table.ContainsKey("io_write_kbs")) io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); if (table.ContainsKey("carrier")) carrier = Marshalling.ParseBool(table, "carrier"); if (table.ContainsKey("vendor_id")) vendor_id = Marshalling.ParseString(table, "vendor_id"); if (table.ContainsKey("vendor_name")) vendor_name = Marshalling.ParseString(table, "vendor_name"); if (table.ContainsKey("device_id")) device_id = Marshalling.ParseString(table, "device_id"); if (table.ContainsKey("device_name")) device_name = Marshalling.ParseString(table, "device_name"); if (table.ContainsKey("speed")) speed = Marshalling.ParseLong(table, "speed"); if (table.ContainsKey("duplex")) duplex = Marshalling.ParseBool(table, "duplex"); if (table.ContainsKey("pci_bus_path")) pci_bus_path = Marshalling.ParseString(table, "pci_bus_path"); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PIF_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._carrier, other._carrier) && Helper.AreEqual2(this._vendor_id, other._vendor_id) && Helper.AreEqual2(this._vendor_name, other._vendor_name) && Helper.AreEqual2(this._device_id, other._device_id) && Helper.AreEqual2(this._device_name, other._device_name) && Helper.AreEqual2(this._speed, other._speed) && Helper.AreEqual2(this._duplex, other._duplex) && Helper.AreEqual2(this._pci_bus_path, other._pci_bus_path) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<PIF_metrics> ProxyArrayToObjectList(Proxy_PIF_metrics[] input) { var result = new List<PIF_metrics>(); foreach (var item in input) result.Add(new PIF_metrics(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, PIF_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PIF_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static PIF_metrics get_record(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_record(session.opaque_ref, _pif_metrics); else return new PIF_metrics(session.XmlRpcProxy.pif_metrics_get_record(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get a reference to the PIF_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PIF_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PIF_metrics>.Create(session.XmlRpcProxy.pif_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_uuid(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_uuid(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_uuid(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the io/read_kbs field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static double get_io_read_kbs(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_io_read_kbs(session.opaque_ref, _pif_metrics); else return Convert.ToDouble(session.XmlRpcProxy.pif_metrics_get_io_read_kbs(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the io/write_kbs field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static double get_io_write_kbs(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_io_write_kbs(session.opaque_ref, _pif_metrics); else return Convert.ToDouble(session.XmlRpcProxy.pif_metrics_get_io_write_kbs(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the carrier field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static bool get_carrier(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_carrier(session.opaque_ref, _pif_metrics); else return (bool)session.XmlRpcProxy.pif_metrics_get_carrier(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the vendor_id field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_vendor_id(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_vendor_id(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_vendor_id(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the vendor_name field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_vendor_name(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_vendor_name(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_vendor_name(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the device_id field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_device_id(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_device_id(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_device_id(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the device_name field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_device_name(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_device_name(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_device_name(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the speed field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static long get_speed(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_speed(session.opaque_ref, _pif_metrics); else return long.Parse(session.XmlRpcProxy.pif_metrics_get_speed(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the duplex field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static bool get_duplex(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_duplex(session.opaque_ref, _pif_metrics); else return (bool)session.XmlRpcProxy.pif_metrics_get_duplex(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the pci_bus_path field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_pci_bus_path(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_pci_bus_path(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_pci_bus_path(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the last_updated field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static DateTime get_last_updated(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_last_updated(session.opaque_ref, _pif_metrics); else return session.XmlRpcProxy.pif_metrics_get_last_updated(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_other_config(session.opaque_ref, _pif_metrics); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pif_metrics_get_other_config(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pif_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_set_other_config(session.opaque_ref, _pif_metrics, _other_config); else session.XmlRpcProxy.pif_metrics_set_other_config(session.opaque_ref, _pif_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _pif_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_add_to_other_config(session.opaque_ref, _pif_metrics, _key, _value); else session.XmlRpcProxy.pif_metrics_add_to_other_config(session.opaque_ref, _pif_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PIF_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pif_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_remove_from_other_config(session.opaque_ref, _pif_metrics, _key); else session.XmlRpcProxy.pif_metrics_remove_from_other_config(session.opaque_ref, _pif_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the PIF_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PIF_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_all(session.opaque_ref); else return XenRef<PIF_metrics>.Create(session.XmlRpcProxy.pif_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PIF_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PIF_metrics>, PIF_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_all_records(session.opaque_ref); else return XenRef<PIF_metrics>.Create<Proxy_PIF_metrics>(session.XmlRpcProxy.pif_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Read bandwidth (KiB/s) /// </summary> public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_read_kbs; /// <summary> /// Write bandwidth (KiB/s) /// </summary> public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; NotifyPropertyChanged("io_write_kbs"); } } } private double _io_write_kbs; /// <summary> /// Report if the PIF got a carrier or not /// </summary> public virtual bool carrier { get { return _carrier; } set { if (!Helper.AreEqual(value, _carrier)) { _carrier = value; NotifyPropertyChanged("carrier"); } } } private bool _carrier; /// <summary> /// Report vendor ID /// </summary> public virtual string vendor_id { get { return _vendor_id; } set { if (!Helper.AreEqual(value, _vendor_id)) { _vendor_id = value; NotifyPropertyChanged("vendor_id"); } } } private string _vendor_id = ""; /// <summary> /// Report vendor name /// </summary> public virtual string vendor_name { get { return _vendor_name; } set { if (!Helper.AreEqual(value, _vendor_name)) { _vendor_name = value; NotifyPropertyChanged("vendor_name"); } } } private string _vendor_name = ""; /// <summary> /// Report device ID /// </summary> public virtual string device_id { get { return _device_id; } set { if (!Helper.AreEqual(value, _device_id)) { _device_id = value; NotifyPropertyChanged("device_id"); } } } private string _device_id = ""; /// <summary> /// Report device name /// </summary> public virtual string device_name { get { return _device_name; } set { if (!Helper.AreEqual(value, _device_name)) { _device_name = value; NotifyPropertyChanged("device_name"); } } } private string _device_name = ""; /// <summary> /// Speed of the link (if available) /// </summary> public virtual long speed { get { return _speed; } set { if (!Helper.AreEqual(value, _speed)) { _speed = value; NotifyPropertyChanged("speed"); } } } private long _speed; /// <summary> /// Full duplex capability of the link (if available) /// </summary> public virtual bool duplex { get { return _duplex; } set { if (!Helper.AreEqual(value, _duplex)) { _duplex = value; NotifyPropertyChanged("duplex"); } } } private bool _duplex; /// <summary> /// PCI bus path of the pif (if available) /// </summary> public virtual string pci_bus_path { get { return _pci_bus_path; } set { if (!Helper.AreEqual(value, _pci_bus_path)) { _pci_bus_path = value; NotifyPropertyChanged("pci_bus_path"); } } } private string _pci_bus_path = ""; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// 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 Xunit; namespace System.Threading.Tests { public class EventWaitHandleTests : RemoteExecutorTestBase { [Theory] [InlineData(false, EventResetMode.AutoReset)] [InlineData(false, EventResetMode.ManualReset)] [InlineData(true, EventResetMode.AutoReset)] [InlineData(true, EventResetMode.ManualReset)] public void Ctor_StateMode(bool initialState, EventResetMode mode) { using (var ewh = new EventWaitHandle(initialState, mode)) Assert.Equal(initialState, ewh.WaitOne(0)); } [Fact] public void Ctor_InvalidMode() { Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, (EventResetMode)12345)); } [PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix [Fact] public void Ctor_InvalidNames() { Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, EventResetMode.AutoReset, new string('a', 1000))); } [PlatformSpecific(TestPlatforms.AnyUnix)] // names aren't supported on Unix [Fact] public void Ctor_NamesArentSupported_Unix() { Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything")); bool createdNew; Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything", out createdNew)); } [PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix [Theory] [InlineData(false, EventResetMode.AutoReset)] [InlineData(false, EventResetMode.ManualReset)] [InlineData(true, EventResetMode.AutoReset)] [InlineData(true, EventResetMode.ManualReset)] public void Ctor_StateModeNameCreatedNew_Windows(bool initialState, EventResetMode mode) { string name = Guid.NewGuid().ToString("N"); bool createdNew; using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew)) { Assert.True(createdNew); using (new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew)) { Assert.False(createdNew); } } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Theory] [InlineData(EventResetMode.AutoReset)] [InlineData(EventResetMode.ManualReset)] public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows(EventResetMode mode) { string name = Guid.NewGuid().ToString("N"); using (Mutex m = new Mutex(false, name)) Assert.Throws<WaitHandleCannotBeOpenedException>(() => new EventWaitHandle(false, mode, name)); } [Fact] public void SetReset() { using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset)) { Assert.False(are.WaitOne(0)); are.Set(); Assert.True(are.WaitOne(0)); Assert.False(are.WaitOne(0)); are.Set(); are.Reset(); Assert.False(are.WaitOne(0)); } using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset)) { Assert.False(mre.WaitOne(0)); mre.Set(); Assert.True(mre.WaitOne(0)); Assert.True(mre.WaitOne(0)); mre.Set(); Assert.True(mre.WaitOne(0)); mre.Reset(); Assert.False(mre.WaitOne(0)); } } [PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix [Fact] public void OpenExisting_Windows() { string name = Guid.NewGuid().ToString("N"); EventWaitHandle resultHandle; Assert.False(EventWaitHandle.TryOpenExisting(name, out resultHandle)); Assert.Null(resultHandle); using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, name)) { using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(name)) { are1.Set(); Assert.True(are2.WaitOne(0)); Assert.False(are1.WaitOne(0)); Assert.False(are2.WaitOne(0)); are2.Set(); Assert.True(are1.WaitOne(0)); Assert.False(are2.WaitOne(0)); Assert.False(are1.WaitOne(0)); } Assert.True(EventWaitHandle.TryOpenExisting(name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } } [PlatformSpecific(TestPlatforms.AnyUnix)] // OpenExisting not supported on Unix [Fact] public void OpenExisting_NotSupported_Unix() { Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.OpenExisting("anything")); EventWaitHandle ewh; Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.TryOpenExisting("anything", out ewh)); } [PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix [Fact] public void OpenExisting_InvalidNames_Windows() { AssertExtensions.Throws<ArgumentNullException>("name", () => EventWaitHandle.OpenExisting(null)); Assert.Throws<ArgumentException>(() => EventWaitHandle.OpenExisting(string.Empty)); Assert.Throws<ArgumentException>(() => EventWaitHandle.OpenExisting(new string('a', 10000))); } [PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix [Fact] public void OpenExisting_UnavailableName_Windows() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name)); EventWaitHandle ignored; Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored)); } [PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix [Fact] public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Mutex mtx = new Mutex(true, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name)); EventWaitHandle ignored; Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored)); } } [PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix [Theory] [InlineData(EventResetMode.ManualReset)] [InlineData(EventResetMode.AutoReset)] public void PingPong(EventResetMode mode) { // Create names for the two events string outboundName = Guid.NewGuid().ToString("N"); string inboundName = Guid.NewGuid().ToString("N"); // Create the two events and the other process with which to synchronize using (var inbound = new EventWaitHandle(true, mode, inboundName)) using (var outbound = new EventWaitHandle(false, mode, outboundName)) using (var remote = RemoteInvoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName)) { // Repeatedly wait for one event and then set the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); if (mode == EventResetMode.ManualReset) { inbound.Reset(); } outbound.Set(); } } } private static int PingPong_OtherProcess(string modeName, string inboundName, string outboundName) { EventResetMode mode = (EventResetMode)Enum.Parse(typeof(EventResetMode), modeName); // Open the two events using (var inbound = EventWaitHandle.OpenExisting(inboundName)) using (var outbound = EventWaitHandle.OpenExisting(outboundName)) { // Repeatedly wait for one event and then set the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); if (mode == EventResetMode.ManualReset) { inbound.Reset(); } outbound.Set(); } } return SuccessExitCode; } } }
/* * Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v.. * * 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. */ #region Using using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using Microsoft.VisualStudio.TestTools.UnitTesting; using PPWCode.Util.OddsAndEnds.I.Extensions; using Spring.Context.Support; #endregion namespace PPWCode.Kit.Tasks.API_I.RemoteTest { [TestClass] public abstract class BaseTaskTests { #region Test Setup protected ClientTasksDao Svc { get; private set; } [TestInitialize] public void Initialize() { Svc = GetClientTasksDao(); } [TestCleanup] public void Cleanup() { Svc.Dispose(); } #endregion #region Protected Helpers protected static Task CreateTasksWithOneAttribute() { Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "taskType/", }; task.AddAttribute(@"key1", @"value1"); return task; } protected static Task CreateTasksWithTwoAttributes() { Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "taskType/", }; task.AddAttribute(@"key1", @"value1"); task.AddAttribute(@"key2", @"value2"); return task; } protected static Task CreateTasksWithThreeAttributes() { Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "/PensioB/Sempera/Affiliation/ManualCapitalAcquiredVerificationNeeded/", }; task.AddAttribute(@"key1", @"value1"); task.AddAttribute(@"key2", @"value2"); task.AddAttribute(@"key3", @"value3"); return task; } protected IEnumerable<Task> CreateSomeTasksForSearching() { IList<Task> result = new List<Task>(); { IDictionary<string, string> attributes = new Dictionary<string, string> { { "TypeName", "/PensioB/Sempera/Affiliation" }, { "RetirementPlanName", "construo" }, { "AffiliateSynergyID", "2752" }, { "AffiliationID", "107" }, }; Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "/PensioB/Sempera/Affiliation/ManualCapitalAcquiredVerificationNeeded/", }; task.AddAttributes(attributes); result.Add(SaveTask(task)); } { IDictionary<string, string> attributes = new Dictionary<string, string> { { "TypeName", "/PensioB/Sempera/Affiliation" }, { "RetirementPlanName", "construo" }, { "AffiliateSynergyID", "2787" }, { "AffiliationID", "246" }, }; Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "/PensioB/Sempera/Affiliation/ManualCapitalAcquiredVerificationNeeded/", }; task.AddAttributes(attributes); result.Add(SaveTask(task)); } { IDictionary<string, string> attributes = new Dictionary<string, string> { { "TypeName", "/PensioB/Sempera/Affiliation" }, { "RetirementPlanName", "construo" }, { "AffiliateSynergyID", "6788" }, { "AffiliationID", "285" }, }; Task task = new Task { State = TaskStateEnum.CREATED, TaskType = "/PensioB/Sempera/Affiliation/ManualCapitalAcquiredVerificationNeeded/", }; task.AddAttributes(attributes); result.Add(SaveTask(task)); } return result; } private static bool EqualAttributes(Task t1, Task t2) { bool result = t1.Attributes.Count == t2.Attributes.Count; if (result) { foreach (var pair in t1.Attributes) { string value; result = t2.Attributes.TryGetValue(pair.Key, out value); result &= pair.Value.Equals(value); if (!result) { break; } } } return result; } protected Task SaveTask(Task task) { Task createdTask = Svc.Create(task); Assert.IsNotNull(createdTask); Assert.AreEqual(task.State, createdTask.State); Assert.AreEqual(task.TaskType, createdTask.TaskType); Assert.IsTrue(EqualAttributes(task, createdTask)); return createdTask; } #endregion #region Private Helpers private static void ClearContentOfTables() { string connectionString = ConfigurationManager.ConnectionStrings["TasksConnectionString"].ConnectionString; Assert.IsFalse(connectionString == null); using (SqlConnection con = new SqlConnection(connectionString)) { string[] tblNames = new[] { @"dbo.TaskAttributes", @"dbo.Task", @"dbo.AuditLog" }; con.Open(); foreach (string tblName in tblNames) { using (var cmd = con.CreateCommand()) { cmd.CommandText = string.Format("delete from {0}", tblName); cmd.ExecuteNonQuery(); } } con.Close(); } } private static ClientTasksDao GetClientTasksDao() { ClearContentOfTables(); ITasksDao tasks = ContextRegistry.GetContext().GetObject<ITasksDao>("TasksFactory"); ClientTasksDao result = new ClientTasksDao(tasks); result.FlushAllCaches(); return result; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Table; using Orleans.AzureUtils; namespace Orleans.Runtime.ReminderService { internal class ReminderTableEntry : TableEntity { public string GrainReference { get; set; } // Part of RowKey public string ReminderName { get; set; } // Part of RowKey public string ServiceId { get; set; } // Part of PartitionKey public string DeploymentId { get; set; } public string StartAt { get; set; } public string Period { get; set; } public string GrainRefConsistentHash { get; set; } // Part of PartitionKey public static string ConstructRowKey(GrainReference grainRef, string reminderName) { var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName); return AzureStorageUtils.SanitizeTableProperty(key); } public static string ConstructPartitionKey(Guid serviceId, GrainReference grainRef) { return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode()); } public static string ConstructPartitionKey(Guid serviceId, uint number) { // IMPORTANT NOTE: Other code using this return data is very sensitive to format changes, // so take great care when making any changes here!!! // this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly // the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now, // when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative // string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number); var grainHash = String.Format("{0:X8}", number); return String.Format("{0}_{1}", ConstructServiceIdStr(serviceId), grainHash); } public static string ConstructServiceIdStr(Guid serviceId) { return serviceId.ToString(); } public override string ToString() { var sb = new StringBuilder(); sb.Append("Reminder ["); sb.Append(" PartitionKey=").Append(PartitionKey); sb.Append(" RowKey=").Append(RowKey); sb.Append(" GrainReference=").Append(GrainReference); sb.Append(" ReminderName=").Append(ReminderName); sb.Append(" Deployment=").Append(DeploymentId); sb.Append(" ServiceId=").Append(ServiceId); sb.Append(" StartAt=").Append(StartAt); sb.Append(" Period=").Append(Period); sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash); sb.Append("]"); return sb.ToString(); } } internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry> { private const string REMINDERS_TABLE_NAME = "OrleansReminders"; public Guid ServiceId { get; private set; } public string DeploymentId { get; private set; } private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout; public static async Task<RemindersTableManager> GetManager(Guid serviceId, string deploymentId, string storageConnectionString, ILoggerFactory loggerFactory) { var singleton = new RemindersTableManager(serviceId, deploymentId, storageConnectionString, loggerFactory); try { singleton.Logger.Info("Creating RemindersTableManager for service id {0} and deploymentId {1}.", serviceId, deploymentId); await singleton.InitTableAsync() .WithTimeout(initTimeout); } catch (TimeoutException te) { string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}"; singleton.Logger.Error(ErrorCode.AzureTable_38, errorMsg, te); throw new OrleansException(errorMsg, te); } catch (Exception ex) { string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}"; singleton.Logger.Error(ErrorCode.AzureTable_39, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return singleton; } private RemindersTableManager(Guid serviceId, string deploymentId, string storageConnectionString, ILoggerFactory loggerFactory) : base(REMINDERS_TABLE_NAME, storageConnectionString, loggerFactory) { DeploymentId = deploymentId; ServiceId = serviceId; } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end) { // TODO: Determine whether or not a single query could be used here while avoiding a table scan string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin); string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end); string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(ServiceId); string filterOnServiceIdStr = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, serviceIdStr + '_'), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, serviceIdStr + (char)('_' + 1))); if (begin < end) { string filterBetweenBeginAndEnd = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd)); string query = TableQuery.CombineFilters(filterOnServiceIdStr, TableOperators.And, filterBetweenBeginAndEnd); var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } if (begin == end) { var queryResults = await ReadTableEntriesAndEtagsAsync(filterOnServiceIdStr); return queryResults.ToList(); } // (begin > end) string queryOnSBegin = TableQuery.CombineFilters( filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin)); string queryOnSEnd = TableQuery.CombineFilters( filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd)); var resultsOnSBeginQuery = ReadTableEntriesAndEtagsAsync(queryOnSBegin); var resultsOnSEndQuery = ReadTableEntriesAndEtagsAsync(queryOnSEnd); IEnumerable<Tuple<ReminderTableEntry, string>>[] results = await Task.WhenAll(resultsOnSBeginQuery, resultsOnSEndQuery); return results[0].Concat(results[1]).ToList(); } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef) { var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); string filter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.GreaterThan, grainRef.ToKeyString() + '-'), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.LessThanOrEqual, grainRef.ToKeyString() + (char)('-' + 1))); string query = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.Equal, partitionKey), TableOperators.And, filter); var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName) { string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName); return await ReadSingleTableEntryAsync(partitionKey, rowKey); } private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries() { return FindReminderEntries(0, 0); } internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry) { try { return await UpsertTableEntryAsync(reminderEntry); } catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false; } throw; } } internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag) { try { await DeleteTableEntryAsync(reminderEntry, eTag); return true; }catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; } throw; } } #region Table operations internal async Task DeleteTableEntries() { if (ServiceId.Equals(Guid.Empty) && DeploymentId == null) { await DeleteTableAsync(); } else { List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries(); // return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed // group by grain hashcode so each query goes to different partition var tasks = new List<Task>(); var groupedByHash = entries .Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId))) .Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId. .GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList()); foreach (var entriesPerPartition in groupedByHash.Values) { foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) { tasks.Add(DeleteTableEntriesAsync(batch)); } } await Task.WhenAll(tasks); } } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, 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. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Exception information provided through /// a call to one of the Logger.*Exception() methods. /// </summary> [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer, IRawValue { private string _format; private string _innerFormat = string.Empty; private static readonly Dictionary<string, ExceptionRenderingFormat> _formatsMapping = new Dictionary<string, ExceptionRenderingFormat>(StringComparer.OrdinalIgnoreCase) { {"MESSAGE",ExceptionRenderingFormat.Message}, {"TYPE", ExceptionRenderingFormat.Type}, {"SHORTTYPE",ExceptionRenderingFormat.ShortType}, {"TOSTRING",ExceptionRenderingFormat.ToString}, {"METHOD",ExceptionRenderingFormat.Method}, {"TARGETSITE",ExceptionRenderingFormat.Method}, {"SOURCE",ExceptionRenderingFormat.Source}, {"STACKTRACE", ExceptionRenderingFormat.StackTrace}, {"DATA",ExceptionRenderingFormat.Data}, {"@",ExceptionRenderingFormat.Serialize}, {"HRESULT",ExceptionRenderingFormat.HResult}, {"PROPERTIES",ExceptionRenderingFormat.Properties}, }; private static readonly Dictionary<ExceptionRenderingFormat, Action<ExceptionLayoutRenderer, StringBuilder, Exception, Exception>> _renderingfunctions = new Dictionary<ExceptionRenderingFormat, Action<ExceptionLayoutRenderer, StringBuilder, Exception, Exception>>() { {ExceptionRenderingFormat.Message, (layout, sb, ex, aggex) => layout.AppendMessage(sb, ex)}, {ExceptionRenderingFormat.Type, (layout, sb, ex, aggex) => layout.AppendType(sb, ex)}, { ExceptionRenderingFormat.ShortType, (layout, sb, ex, aggex) => layout.AppendShortType(sb, ex)}, { ExceptionRenderingFormat.ToString, (layout, sb, ex, aggex) => layout.AppendToString(sb, ex)}, { ExceptionRenderingFormat.Method, (layout, sb, ex, aggex) => layout.AppendMethod(sb, ex)}, { ExceptionRenderingFormat.Source, (layout, sb, ex, aggex) => layout.AppendSource(sb, ex)}, { ExceptionRenderingFormat.StackTrace, (layout, sb, ex, aggex) => layout.AppendStackTrace(sb, ex)}, { ExceptionRenderingFormat.Data, (layout, sb, ex, aggex) => layout.AppendData(sb, ex, aggex)}, { ExceptionRenderingFormat.Serialize, (layout, sb, ex, aggex) => layout.AppendSerializeObject(sb, ex)}, { ExceptionRenderingFormat.HResult, (layout, sb, ex, aggex) => layout.AppendHResult(sb, ex)}, { ExceptionRenderingFormat.Properties, (layout, sb, ex, aggex) => layout.AppendProperties(sb, ex)}, }; private static readonly HashSet<string> ExcludeDefaultProperties = new HashSet<string>(new[] { "Type", nameof(Exception.Data), nameof(Exception.HelpLink), "HResult", // Not available on NET35 + NET40 nameof(Exception.InnerException), nameof(Exception.Message), nameof(Exception.Source), nameof(Exception.StackTrace), "TargetSite",// Not available on NETSTANDARD1_3 OR NETSTANDARD1_5 }, StringComparer.Ordinal); private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(LoggingConfiguration.GetServiceProvider())); private ObjectReflectionCache _objectReflectionCache; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class. /// </summary> public ExceptionLayoutRenderer() { Format = "TOSTRING,DATA"; } /// <summary> /// Gets or sets the format of the output. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <see cref="Formats"/> /// <see cref="ExceptionRenderingFormat"/> /// <docgen category='Rendering Options' order='10' /> [DefaultParameter] public string Format { get => _format; set { _format = value; Formats = CompileFormat(value, nameof(Format)); } } /// <summary> /// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerFormat { get => _innerFormat; set { _innerFormat = value; InnerFormats = CompileFormat(value, nameof(InnerFormat)); } } /// <summary> /// Gets or sets the separator used to concatenate parts specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Separator { get => _seperator; set => _seperator = new NLog.Layouts.SimpleLayout(value).Render(LogEventInfo.CreateNullEvent()); } private string _seperator = " "; /// <summary> /// Gets or sets the separator used to concatenate exception data specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string ExceptionDataSeparator { get => _exceptionDataSeparator; set => _exceptionDataSeparator = new NLog.Layouts.SimpleLayout(value).Render(LogEventInfo.CreateNullEvent()); } private string _exceptionDataSeparator = ";"; /// <summary> /// Gets or sets the maximum number of inner exceptions to include in the output. /// By default inner exceptions are not enabled for compatibility with NLog 1.0. /// </summary> /// <docgen category='Rendering Options' order='10' /> public int MaxInnerExceptionLevel { get; set; } /// <summary> /// Gets or sets the separator between inner exceptions. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerExceptionSeparator { get; set; } = EnvironmentHelper.NewLine; /// <summary> /// Gets or sets whether to render innermost Exception from <see cref="Exception.GetBaseException()"/> /// </summary> public bool BaseException { get; set; } #if !NET35 /// <summary> /// Gets or sets whether to collapse exception tree using <see cref="AggregateException.Flatten()"/> /// </summary> #else /// <summary> /// Gets or sets whether to collapse exception tree using AggregateException.Flatten() /// </summary> #endif public bool FlattenException { get; set; } = true; /// <summary> /// Gets the formats of the output of inner exceptions to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> Formats { get; private set; } /// <summary> /// Gets the formats of the output to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> InnerFormats { get; private set; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetTopException(logEvent); return true; } private Exception GetTopException(LogEventInfo logEvent) { return BaseException ? logEvent.Exception?.GetBaseException() : logEvent.Exception; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception primaryException = GetTopException(logEvent); if (primaryException != null) { int currentLevel = 0; #if !NET35 if (logEvent.Exception is AggregateException aggregateException) { primaryException = FlattenException ? GetPrimaryException(aggregateException) : aggregateException; AppendException(primaryException, Formats, builder, aggregateException); if (currentLevel < MaxInnerExceptionLevel) { currentLevel = AppendInnerExceptionTree(primaryException, currentLevel, builder); if (currentLevel < MaxInnerExceptionLevel && aggregateException.InnerExceptions?.Count > 1) { AppendAggregateException(aggregateException, currentLevel, builder); } } } else #endif { AppendException(primaryException, Formats, builder); if (currentLevel < MaxInnerExceptionLevel) { AppendInnerExceptionTree(primaryException, currentLevel, builder); } } } } #if !NET35 private static Exception GetPrimaryException(AggregateException aggregateException) { if (aggregateException.InnerExceptions.Count == 1) { var innerException = aggregateException.InnerExceptions[0]; if (!(innerException is AggregateException)) return innerException; // Skip calling Flatten() } aggregateException = aggregateException.Flatten(); if (aggregateException.InnerExceptions.Count == 1) { return aggregateException.InnerExceptions[0]; } return aggregateException; } private void AppendAggregateException(AggregateException primaryException, int currentLevel, StringBuilder builder) { var asyncException = primaryException.Flatten(); if (asyncException.InnerExceptions != null) { for (int i = 0; i < asyncException.InnerExceptions.Count && currentLevel < MaxInnerExceptionLevel; i++, currentLevel++) { var currentException = asyncException.InnerExceptions[i]; if (ReferenceEquals(currentException, primaryException.InnerException)) continue; // Skip firstException when it is innerException if (currentException is null) { InternalLogger.Debug("Skipping rendering exception as exception is null"); continue; } AppendInnerException(currentException, builder); currentLevel++; currentLevel = AppendInnerExceptionTree(currentException, currentLevel, builder); } } } #endif private int AppendInnerExceptionTree(Exception currentException, int currentLevel, StringBuilder sb) { currentException = currentException.InnerException; while (currentException != null && currentLevel < MaxInnerExceptionLevel) { AppendInnerException(currentException, sb); currentLevel++; currentException = currentException.InnerException; } return currentLevel; } private void AppendInnerException(Exception currentException, StringBuilder builder) { // separate inner exceptions builder.Append(InnerExceptionSeparator); AppendException(currentException, InnerFormats ?? Formats, builder); } private void AppendException(Exception currentException, List<ExceptionRenderingFormat> renderFormats, StringBuilder builder, Exception aggregateException = null) { int currentLength = builder.Length; foreach (ExceptionRenderingFormat renderingFormat in renderFormats) { int beforeRenderLength = builder.Length; var currentRenderFunction = _renderingfunctions[renderingFormat]; currentRenderFunction(this, builder, currentException, aggregateException); if (builder.Length != beforeRenderLength) { currentLength = builder.Length; builder.Append(Separator); } } builder.Length = currentLength; } /// <summary> /// Appends the Message of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The exception containing the Message to append.</param> protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose method name should be appended.</param> protected virtual void AppendMethod(StringBuilder sb, Exception ex) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 sb.Append(ex.TargetSite?.ToString()); #else sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace)); #endif } /// <summary> /// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose stack trace should be appended.</param> protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { sb.Append(ex.StackTrace); } /// <summary> /// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose call to ToString() should be appended.</param> protected virtual void AppendToString(StringBuilder sb, Exception ex) { try { sb.Append(ex.ToString()); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendToString(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose type should be appended.</param> protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().FullName); } /// <summary> /// Appends the short type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose short type should be appended.</param> protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } /// <summary> /// Appends the application source of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose source should be appended.</param> protected virtual void AppendSource(StringBuilder sb, Exception ex) { sb.Append(ex.Source); } /// <summary> /// Appends the HResult of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose HResult should be appended.</param> protected virtual void AppendHResult(StringBuilder sb, Exception ex) { #if !NET35 && !NET40 const int S_OK = 0; // Carries no information, so skip const int S_FALSE = 1; // Carries no information, so skip if (ex.HResult != S_OK && ex.HResult != S_FALSE) { sb.AppendFormat("0x{0:X8}", ex.HResult); } #endif } private void AppendData(StringBuilder builder, Exception ex, Exception aggregateException) { if (aggregateException?.Data?.Count > 0 && !ReferenceEquals(ex, aggregateException)) { AppendData(builder, aggregateException); builder.Append(Separator); } AppendData(builder, ex); } /// <summary> /// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose Data property elements should be appended.</param> protected virtual void AppendData(StringBuilder sb, Exception ex) { if (ex.Data?.Count > 0) { string separator = string.Empty; foreach (var key in ex.Data.Keys) { sb.Append(separator); sb.AppendFormat("{0}: {1}", key, ex.Data[key]); separator = ExceptionDataSeparator; } } } /// <summary> /// Appends all the serialized properties of an Exception into the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose properties should be appended.</param> protected virtual void AppendSerializeObject(StringBuilder sb, Exception ex) { ValueFormatter.FormatValue(ex, null, MessageTemplates.CaptureType.Serialize, null, sb); } /// <summary> /// Appends all the additional properties of an Exception like Data key-value-pairs /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose properties should be appended.</param> protected virtual void AppendProperties(StringBuilder sb, Exception ex) { string separator = string.Empty; var exceptionProperties = ObjectReflectionCache.LookupObjectProperties(ex); foreach (var property in exceptionProperties) { if (ExcludeDefaultProperties.Contains(property.Name)) continue; var propertyValue = property.Value?.ToString(); if (string.IsNullOrEmpty(propertyValue)) continue; sb.Append(separator); sb.AppendFormat("{0}: {1}", property.Name, propertyValue); separator = ExceptionDataSeparator; } } /// <summary> /// Split the string and then compile into list of Rendering formats. /// </summary> private static List<ExceptionRenderingFormat> CompileFormat(string formatSpecifier, string propertyName) { List<ExceptionRenderingFormat> formats = new List<ExceptionRenderingFormat>(); string[] parts = formatSpecifier.SplitAndTrimTokens(','); foreach (string s in parts) { ExceptionRenderingFormat renderingFormat; if (_formatsMapping.TryGetValue(s, out renderingFormat)) { formats.Add(renderingFormat); } else { InternalLogger.Warn("Exception-LayoutRenderer assigned unknown {0}: {1}", propertyName, s); // TODO Delay parsing to Initialize and check ThrowConfigExceptions } } return formats; } #if NETSTANDARD1_3 || NETSTANDARD1_5 /// <summary> /// Find name of method on stracktrace. /// </summary> /// <param name="stackTrace">Full stracktrace</param> /// <returns></returns> protected static string ParseMethodNameFromStackTrace(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) return string.Empty; // get the first line of the stack trace string stackFrameLine; int p = stackTrace.IndexOfAny(new[] { '\r', '\n' }); if (p >= 0) { stackFrameLine = stackTrace.Substring(0, p); } else { stackFrameLine = stackTrace; } // stack trace is composed of lines which look like this // // at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something) // // "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis int lastSpace = -1; int startPos = 0; int endPos = stackFrameLine.Length; for (int i = 0; i < stackFrameLine.Length; ++i) { switch (stackFrameLine[i]) { case ' ': lastSpace = i; break; case '(': startPos = lastSpace + 1; break; case ')': endPos = i + 1; // end the loop i = stackFrameLine.Length; break; } } return stackTrace.Substring(startPos, endPos - startPos); } #endif } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedRegionOperationsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRegionOperationRequest, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) DeleteRegionOperationRequest request = new DeleteRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request DeleteRegionOperationResponse response = regionOperationsClient.Delete(request); // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRegionOperationRequest, CallSettings) // Additional: DeleteAsync(DeleteRegionOperationRequest, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) DeleteRegionOperationRequest request = new DeleteRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request DeleteRegionOperationResponse response = await regionOperationsClient.DeleteAsync(request); // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request DeleteRegionOperationResponse response = regionOperationsClient.Delete(project, region, operation); // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request DeleteRegionOperationResponse response = await regionOperationsClient.DeleteAsync(project, region, operation); // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRegionOperationRequest, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) GetRegionOperationRequest request = new GetRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request Operation response = regionOperationsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRegionOperationRequest, CallSettings) // Additional: GetAsync(GetRegionOperationRequest, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) GetRegionOperationRequest request = new GetRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request Operation response = await regionOperationsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request Operation response = regionOperationsClient.Get(project, region, operation); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request Operation response = await regionOperationsClient.GetAsync(project, region, operation); // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRegionOperationsRequest, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) ListRegionOperationsRequest request = new ListRegionOperationsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<OperationList, Operation> response = regionOperationsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Operation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRegionOperationsRequest, CallSettings) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) ListRegionOperationsRequest request = new ListRegionOperationsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<OperationList, Operation> response = regionOperationsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Operation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<OperationList, Operation> response = regionOperationsClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (Operation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<OperationList, Operation> response = regionOperationsClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Operation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Wait</summary> public void WaitRequestObject() { // Snippet: Wait(WaitRegionOperationRequest, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) WaitRegionOperationRequest request = new WaitRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request Operation response = regionOperationsClient.Wait(request); // End snippet } /// <summary>Snippet for WaitAsync</summary> public async Task WaitRequestObjectAsync() { // Snippet: WaitAsync(WaitRegionOperationRequest, CallSettings) // Additional: WaitAsync(WaitRegionOperationRequest, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) WaitRegionOperationRequest request = new WaitRegionOperationRequest { Operation = "", Region = "", Project = "", }; // Make the request Operation response = await regionOperationsClient.WaitAsync(request); // End snippet } /// <summary>Snippet for Wait</summary> public void Wait() { // Snippet: Wait(string, string, string, CallSettings) // Create client RegionOperationsClient regionOperationsClient = RegionOperationsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request Operation response = regionOperationsClient.Wait(project, region, operation); // End snippet } /// <summary>Snippet for WaitAsync</summary> public async Task WaitAsync() { // Snippet: WaitAsync(string, string, string, CallSettings) // Additional: WaitAsync(string, string, string, CancellationToken) // Create client RegionOperationsClient regionOperationsClient = await RegionOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string operation = ""; // Make the request Operation response = await regionOperationsClient.WaitAsync(project, region, operation); // End snippet } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.DeployedDevices.Fleet { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Fetch information about a specific Key credential in the Fleet. /// </summary> public class FetchKeyOptions : IOptions<KeyResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Key. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchKeyOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Key. </param> public FetchKeyOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Delete a specific Key credential from the Fleet, effectively disallowing any inbound client connections that are /// presenting it. /// </summary> public class DeleteKeyOptions : IOptions<KeyResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Key. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteKeyOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Key. </param> public DeleteKeyOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Create a new Key credential in the Fleet, optionally giving it a friendly name and assigning to a Device. /// </summary> public class CreateKeyOptions : IOptions<KeyResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// The human readable description for this Key. /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique identifier of a Key to be authenticated. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new CreateKeyOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> public CreateKeyOptions(string pathFleetSid) { PathFleetSid = pathFleetSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Retrieve a list of all Keys credentials belonging to the Fleet. /// </summary> public class ReadKeyOptions : ReadOptions<KeyResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// Find all Keys authenticating specified Device. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new ReadKeyOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> public ReadKeyOptions(string pathFleetSid) { PathFleetSid = pathFleetSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Update the given properties of a specific Key credential in the Fleet, giving it a friendly name or assigning to a /// Device. /// </summary> public class UpdateKeyOptions : IOptions<KeyResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Key. /// </summary> public string PathSid { get; } /// <summary> /// The human readable description for this Key. /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique identifier of a Key to be authenticated. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new UpdateKeyOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Key. </param> public UpdateKeyOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } return p; } } }
// 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 Test.Utilities; using Xunit; namespace Desktop.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase { private DiagnosticResult GetCA3075LoadCSharpResultAt(int line, int column) { return GetCSharpResultAt(line, column, CA3075RuleId, string.Format(_CA3075LoadXmlMessage, "Load")); } private DiagnosticResult GetCA3075LoadBasicResultAt(int line, int column) { return GetBasicResultAt(line, column, CA3075RuleId, string.Format(_CA3075LoadXmlMessage, "Load")); } [Fact] public void UseXmlDocumentLoadShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(path); } } } ", GetCA3075LoadCSharpResultAt(12, 13) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(path) End Sub End Class End Namespace", GetCA3075LoadBasicResultAt(9, 13) ); } [Fact] public void UseXmlDocumentLoadInGetShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; class TestClass { public XmlDocument Test { get { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); return doc; } } }", GetCA3075LoadCSharpResultAt(12, 13) ); VerifyBasic(@" Imports System.Xml Class TestClass Public ReadOnly Property Test() As XmlDocument Get Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) Return doc End Get End Property End Class", GetCA3075LoadBasicResultAt(10, 13) ); } [Fact] public void UseXmlDocumentLoadInSetShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; class TestClass { XmlDocument privateDoc; public XmlDocument GetDoc { set { if (value == null) { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); privateDoc = doc; } else privateDoc = value; } } }", GetCA3075LoadCSharpResultAt(16, 17) ); VerifyBasic(@" Imports System.Xml Class TestClass Private privateDoc As XmlDocument Public WriteOnly Property GetDoc() As XmlDocument Set If value Is Nothing Then Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) privateDoc = doc Else privateDoc = value End If End Set End Property End Class", GetCA3075LoadBasicResultAt(12, 17) ); } [Fact] public void UseXmlDocumentLoadInTryBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); } catch (Exception) { throw; } finally { } } }", GetCA3075LoadCSharpResultAt(14, 17) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075LoadBasicResultAt(11, 13) ); } [Fact] public void UseXmlDocumentLoadInCatchBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { } catch (Exception) { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); } finally { } } }", GetCA3075LoadCSharpResultAt(15, 17) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) Finally End Try End Sub End Class", GetCA3075LoadBasicResultAt(12, 13) ); } [Fact] public void UseXmlDocumentLoadInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); } } }", GetCA3075LoadCSharpResultAt(16, 13) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) End Try End Sub End Class", GetCA3075LoadBasicResultAt(14, 13) ); } [Fact] public void UseXmlDocumentLoadInAsyncAwaitShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Threading.Tasks; using System.Xml; class TestClass { private async Task TestMethod() { await Task.Run(() => { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075LoadCSharpResultAt(13, 13) ); VerifyBasic(@" Imports System.Threading.Tasks Imports System.Xml Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075LoadBasicResultAt(11, 17) ); } [Fact] public void UseXmlDocumentLoadInDelegateShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; class TestClass { delegate void Del(); Del d = delegate () { var xml = """"; var doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(xml); }; }", GetCA3075LoadCSharpResultAt(12, 9) ); VerifyBasic(@" Imports System.Xml Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim xml = """" Dim doc = New XmlDocument() doc.XmlResolver = Nothing doc.Load(xml) End Sub End Class", GetCA3075LoadBasicResultAt(11, 5) ); } [Fact] public void UseXmlDataDocumentLoadShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { new XmlDataDocument().Load(path); } } } ", GetCA3075LoadCSharpResultAt(10, 13) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Call New XmlDataDocument().Load(path) End Sub End Class End Namespace", GetCA3075LoadBasicResultAt(7, 18) ); } [Fact] public void UseXmlDataDocumentLoadInGetShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; class TestClass { public XmlDataDocument Test { get { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); return doc; } } }", GetCA3075LoadCSharpResultAt(12, 13) ); VerifyBasic(@" Imports System.Xml Class TestClass Public ReadOnly Property Test() As XmlDataDocument Get Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) Return doc End Get End Property End Class", GetCA3075LoadBasicResultAt(11, 13) ); } [Fact] public void UseXmlDataDocumentLoadInTryBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); } catch (Exception) { throw; } finally { } } }", GetCA3075LoadCSharpResultAt(13, 17) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075LoadBasicResultAt(12, 13) ); } [Fact] public void UseXmlDataDocumentLoadInCatchBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { } catch (Exception) { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); } finally { } } }", GetCA3075LoadCSharpResultAt(14, 17) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) Finally End Try End Sub End Class", GetCA3075LoadBasicResultAt(13, 13) ); } [Fact] public void UseXmlDataDocumentLoadInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); } } }", GetCA3075LoadCSharpResultAt(15, 17) ); VerifyBasic(@" Imports System Imports System.Xml Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) End Try End Sub End Class", GetCA3075LoadBasicResultAt(15, 13) ); } [Fact] public void UseXmlDataDocumentLoadInAsyncAwaitShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Threading.Tasks; using System.Xml; class TestClass { private async Task TestMethod() { await Task.Run(() => { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075LoadCSharpResultAt(12, 17) ); VerifyBasic(@" Imports System.Threading.Tasks Imports System.Xml Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075LoadBasicResultAt(12, 9) ); } [Fact] public void UseXmlDataDocumentLoadInDelegateShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; class TestClass { delegate void Del(); Del d = delegate () { var xml = """"; XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null }; doc.Load(xml); }; }", GetCA3075LoadCSharpResultAt(11, 9) ); VerifyBasic(@" Imports System.Xml Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim xml = """" Dim doc As New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(xml) End Sub End Class", GetCA3075LoadBasicResultAt(12, 5) ); } [Fact] public void UseXmlDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { new XmlDocument(){ XmlResolver = null }.Load(reader); } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Call New XmlDocument() With { _ .XmlResolver = Nothing _ }.Load(reader) End Sub End Class End Namespace"); } [Fact] public void UseXmlDataDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { var doc = new XmlDataDocument(){XmlResolver = null}; doc.Load(reader); } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Dim doc = New XmlDataDocument() With { _ .XmlResolver = Nothing _ } doc.Load(reader) End Sub End Class End Namespace"); } } }
// 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.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; namespace System.Reflection.Metadata { public sealed class MethodBodyBlock { private readonly MemoryBlock _il; private readonly int _size; private readonly ushort _maxStack; private readonly bool _localVariablesInitialized; private readonly StandaloneSignatureHandle _localSignature; private readonly ImmutableArray<ExceptionRegion> _exceptionRegions; private MethodBodyBlock( bool localVariablesInitialized, ushort maxStack, StandaloneSignatureHandle localSignatureHandle, MemoryBlock il, ImmutableArray<ExceptionRegion> exceptionRegions, int size) { Debug.Assert(!exceptionRegions.IsDefault); _localVariablesInitialized = localVariablesInitialized; _maxStack = maxStack; _localSignature = localSignatureHandle; _il = il; _exceptionRegions = exceptionRegions; _size = size; } /// <summary> /// Size of the method body - includes the header, IL and exception regions. /// </summary> public int Size { get { return _size; } } public int MaxStack { get { return _maxStack; } } public bool LocalVariablesInitialized { get { return _localVariablesInitialized; } } public StandaloneSignatureHandle LocalSignature { get { return _localSignature; } } public ImmutableArray<ExceptionRegion> ExceptionRegions { get { return _exceptionRegions; } } public byte[] GetILBytes() { return _il.ToArray(); } public ImmutableArray<byte> GetILContent() { byte[] bytes = GetILBytes(); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetILReader() { return new BlobReader(_il); } private const byte ILTinyFormat = 0x02; private const byte ILFatFormat = 0x03; private const byte ILFormatMask = 0x03; private const int ILTinyFormatSizeShift = 2; private const byte ILMoreSects = 0x08; private const byte ILInitLocals = 0x10; private const byte ILFatFormatHeaderSize = 0x03; private const int ILFatFormatHeaderSizeShift = 4; private const byte SectEHTable = 0x01; private const byte SectFatFormat = 0x40; public static MethodBodyBlock Create(BlobReader reader) { int startOffset = reader.Offset; int ilSize; // Error need to check if the Memory Block is empty. This is false for all the calls... byte headByte = reader.ReadByte(); if ((headByte & ILFormatMask) == ILTinyFormat) { // tiny IL can't have locals so technically this shouldn't matter, // but false is consistent with other metadata readers and helps // for use cases involving comparing our output with theirs. const bool initLocalsForTinyIL = false; ilSize = headByte >> ILTinyFormatSizeShift; return new MethodBodyBlock( initLocalsForTinyIL, 8, default(StandaloneSignatureHandle), reader.GetMemoryBlockAt(0, ilSize), ImmutableArray<ExceptionRegion>.Empty, 1 + ilSize // header + IL ); } if ((headByte & ILFormatMask) != ILFatFormat) { throw new BadImageFormatException(SR.Format(SR.InvalidMethodHeader1, headByte)); } // FatILFormat byte headByte2 = reader.ReadByte(); if ((headByte2 >> ILFatFormatHeaderSizeShift) != ILFatFormatHeaderSize) { throw new BadImageFormatException(SR.Format(SR.InvalidMethodHeader2, headByte, headByte2)); } bool localsInitialized = (headByte & ILInitLocals) == ILInitLocals; bool hasExceptionHandlers = (headByte & ILMoreSects) == ILMoreSects; ushort maxStack = reader.ReadUInt16(); ilSize = reader.ReadInt32(); int localSignatureToken = reader.ReadInt32(); StandaloneSignatureHandle localSignatureHandle; if (localSignatureToken == 0) { localSignatureHandle = default(StandaloneSignatureHandle); } else if ((localSignatureToken & TokenTypeIds.TypeMask) == TokenTypeIds.Signature) { localSignatureHandle = StandaloneSignatureHandle.FromRowId((int)((uint)localSignatureToken & TokenTypeIds.RIDMask)); } else { throw new BadImageFormatException(SR.Format(SR.InvalidLocalSignatureToken, unchecked((uint)localSignatureToken))); } var ilBlock = reader.GetMemoryBlockAt(0, ilSize); reader.Offset += ilSize; ImmutableArray<ExceptionRegion> exceptionHandlers; if (hasExceptionHandlers) { reader.Align(4); byte sehHeader = reader.ReadByte(); if ((sehHeader & SectEHTable) != SectEHTable) { throw new BadImageFormatException(SR.Format(SR.InvalidSehHeader, sehHeader)); } bool sehFatFormat = (sehHeader & SectFatFormat) == SectFatFormat; int dataSize = reader.ReadByte(); if (sehFatFormat) { dataSize += reader.ReadUInt16() << 8; exceptionHandlers = ReadFatExceptionHandlers(ref reader, dataSize / 24); } else { reader.Offset += 2; // skip over reserved field exceptionHandlers = ReadSmallExceptionHandlers(ref reader, dataSize / 12); } } else { exceptionHandlers = ImmutableArray<ExceptionRegion>.Empty; } return new MethodBodyBlock( localsInitialized, maxStack, localSignatureHandle, ilBlock, exceptionHandlers, reader.Offset - startOffset); } private static ImmutableArray<ExceptionRegion> ReadSmallExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var kind = (ExceptionRegionKind)memReader.ReadUInt16(); var tryOffset = memReader.ReadUInt16(); var tryLength = memReader.ReadByte(); var handlerOffset = memReader.ReadUInt16(); var handlerLength = memReader.ReadByte(); var classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(kind, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } private static ImmutableArray<ExceptionRegion> ReadFatExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var sehFlags = (ExceptionRegionKind)memReader.ReadUInt32(); int tryOffset = memReader.ReadInt32(); int tryLength = memReader.ReadInt32(); int handlerOffset = memReader.ReadInt32(); int handlerLength = memReader.ReadInt32(); int classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(sehFlags, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using BTDB.Allocators; using BTDB.BTreeLib; using BTDB.Buffer; using BTDB.Collections; using BTDB.KVDBLayer.BTree; using BTDB.KVDBLayer.Implementation; using BTDB.StreamLayer; namespace BTDB.KVDBLayer; public class BTreeKeyValueDB : IHaveSubDB, IKeyValueDBInternal { const int MaxValueSizeInlineInMemory = 7; const int EndOfIndexFileMarker = 0x1234DEAD; IRootNode _lastCommitted; IRootNode? _listHead; // it is long only because Interlock.Read is just long capable, MaxValue means no preserving history long _preserveHistoryUpToCommitUlong; IRootNode? _nextRoot; BTreeKeyValueDBTransaction? _writingTransaction; readonly Queue<TaskCompletionSource<IKeyValueDBTransaction>> _writeWaitingQueue = new(); readonly object _writeLock = new(); uint _fileIdWithTransactionLog; uint _fileIdWithPreviousTransactionLog; IFileCollectionFile? _fileWithTransactionLog; ISpanWriter? _writerWithTransactionLog; static readonly byte[] MagicStartOfTransaction = { (byte)'t', (byte)'R' }; public long MaxTrLogFileSize { get; set; } public IEnumerable<IKeyValueDBTransaction> Transactions() { foreach (var keyValuePair in _transactions) { yield return keyValuePair.Key; } } public ulong CompactorReadBytesPerSecondLimit { get; } public ulong CompactorWriteBytesPerSecondLimit { get; } readonly IOffHeapAllocator _allocator; readonly ICompressionStrategy _compression; readonly IKviCompressionStrategy _kviCompressionStrategy; readonly ICompactorScheduler? _compactorScheduler; readonly IFileCollectionWithFileInfos _fileCollection; readonly Dictionary<long, object> _subDBs = new(); readonly Func<CancellationToken, bool>? _compactFunc; readonly bool _readOnly; readonly bool _lenientOpen; uint? _missingSomeTrlFiles; public BTreeKeyValueDB(IFileCollection fileCollection) : this(fileCollection, new SnappyCompressionStrategy()) { } public BTreeKeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression, uint fileSplitSize = int.MaxValue) : this(fileCollection, compression, fileSplitSize, CompactorScheduler.Instance) { } public BTreeKeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression, uint fileSplitSize, ICompactorScheduler? compactorScheduler) : this(new KeyValueDBOptions { Allocator = new MallocAllocator(), FileCollection = fileCollection, Compression = compression, FileSplitSize = fileSplitSize, CompactorScheduler = compactorScheduler }) { } public BTreeKeyValueDB(KeyValueDBOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); if (options.FileCollection == null) throw new ArgumentNullException(nameof(options.FileCollection)); if (options.FileSplitSize < 1024 || options.FileSplitSize > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(options.FileSplitSize), "Allowed range 1024 - 2G"); Logger = options.Logger; _compactorScheduler = options.CompactorScheduler; _kviCompressionStrategy = options.KviCompressionStrategy; MaxTrLogFileSize = options.FileSplitSize; _readOnly = options.ReadOnly; _lenientOpen = options.LenientOpen; _compression = options.Compression ?? throw new ArgumentNullException(nameof(options.Compression)); DurableTransactions = false; _fileCollection = new FileCollectionWithFileInfos(options.FileCollection); CompactorReadBytesPerSecondLimit = options.CompactorReadBytesPerSecondLimit ?? 0; CompactorWriteBytesPerSecondLimit = options.CompactorWriteBytesPerSecondLimit ?? 0; _allocator = options.Allocator ?? new MallocAllocator(); _lastCommitted = BTreeImpl12.CreateEmptyRoot(_allocator); _lastCommitted.Commit(); _listHead = _lastCommitted; _preserveHistoryUpToCommitUlong = (long)(options.PreserveHistoryUpToCommitUlong ?? ulong.MaxValue); LoadInfoAboutFiles(options.OpenUpToCommitUlong); if (!_readOnly) { _compactFunc = _compactorScheduler?.AddCompactAction(Compact); _compactorScheduler?.AdviceRunning(true); } } public ulong DistanceFromLastKeyIndex(IRootNodeInternal root) { return DistanceFromLastKeyIndex((IRootNode)root); } Span<KeyIndexInfo> IKeyValueDBInternal.BuildKeyIndexInfos() { return BuildKeyIndexInfos(); } uint IKeyValueDBInternal.CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes) { return CalculatePreserveKeyIndexKeyFromKeyIndexInfos(keyIndexes); } public uint GetTrLogFileId(IRootNodeInternal root) { return ((IRootNode)root).TrLogFileId; } public void IterateRoot(IRootNodeInternal root, ValuesIterateAction visit) { ((IRootNode)root).ValuesIterate(visit); } internal Span<KeyIndexInfo> BuildKeyIndexInfos() { var keyIndexes = new StructList<KeyIndexInfo>(); foreach (var fileInfo in _fileCollection.FileInfos) { var keyIndex = fileInfo.Value as IKeyIndex; if (keyIndex == null) continue; keyIndexes.Add(new KeyIndexInfo { Key = fileInfo.Key, Generation = keyIndex.Generation, CommitUlong = keyIndex.CommitUlong }); } if (keyIndexes.Count > 1) keyIndexes.Sort(Comparer<KeyIndexInfo>.Create((l, r) => Comparer<long>.Default.Compare(l.Generation, r.Generation))); return keyIndexes.AsSpan(); } void LoadInfoAboutFiles(ulong? openUpToCommitUlong) { long latestGeneration = -1; uint latestTrLogFileId = 0; foreach (var fileInfo in _fileCollection.FileInfos) { if (!(fileInfo.Value is IFileTransactionLog trLog)) continue; if (trLog.Generation > latestGeneration) { latestGeneration = trLog.Generation; latestTrLogFileId = fileInfo.Key; } } var keyIndexes = BuildKeyIndexInfos(); var preserveKeyIndexKey = CalculatePreserveKeyIndexKeyFromKeyIndexInfos(keyIndexes); var preserveKeyIndexGeneration = CalculatePreserveKeyIndexGeneration(preserveKeyIndexKey); var firstTrLogId = LinkTransactionLogFileIds(latestTrLogFileId); var firstTrLogOffset = 0u; var hasKeyIndex = false; try { while (keyIndexes.Length > 0) { var nearKeyIndex = keyIndexes.Length - 1; if (openUpToCommitUlong.HasValue) { while (nearKeyIndex >= 0) { if (keyIndexes[nearKeyIndex].CommitUlong <= openUpToCommitUlong.Value) break; nearKeyIndex--; } if (nearKeyIndex < 0) { // If we have all trl files we can replay from start if (GetGeneration(firstTrLogId) == 1) break; // Or we have to start with oldest kvi nearKeyIndex = 0; } } var keyIndex = keyIndexes[nearKeyIndex]; keyIndexes.Slice(nearKeyIndex + 1).CopyTo(keyIndexes.Slice(nearKeyIndex)); keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1); var info = (IKeyIndex)_fileCollection.FileInfoByIdx(keyIndex.Key); _nextRoot = _lastCommitted.CreateWritableTransaction(); try { if (LoadKeyIndex(keyIndex.Key, info!) && firstTrLogId <= info.TrLogFileId) { _lastCommitted.Dispose(); _lastCommitted = _nextRoot!; _lastCommitted!.Commit(); _listHead = _lastCommitted; _nextRoot = null; firstTrLogId = info.TrLogFileId; firstTrLogOffset = info.TrLogOffset; hasKeyIndex = true; break; } } finally { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } } // Corrupted kvi - could be removed MarkFileForRemoval(keyIndex.Key); } while (keyIndexes.Length > 0) { var keyIndex = keyIndexes[^1]; keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1); if (keyIndex.Key != preserveKeyIndexKey) MarkFileForRemoval(keyIndex.Key); } if (!hasKeyIndex && _missingSomeTrlFiles.HasValue) { if (_lenientOpen) { Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " + _missingSomeTrlFiles.Value + ". LenientOpen is true, recovering data."); LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong); } else { Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " + _missingSomeTrlFiles.Value); if (!_readOnly) { foreach (var fileInfo in _fileCollection.FileInfos) { var trLog = fileInfo.Value as IFileTransactionLog; if (trLog == null) continue; MarkFileForRemoval(fileInfo.Key); } _fileCollection.DeleteAllUnknownFiles(); _fileIdWithTransactionLog = 0; firstTrLogId = 0; latestTrLogFileId = 0; } } } else { LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong); } if (!_readOnly) { if (openUpToCommitUlong.HasValue || latestTrLogFileId != firstTrLogId && firstTrLogId != 0 || !hasKeyIndex && _fileCollection.FileInfos.Any(p => p.Value.SubDBId == 0)) { // Need to create new trl if cannot append to last one so it is then written to kvi if (openUpToCommitUlong.HasValue && _fileIdWithTransactionLog == 0) { WriteStartOfNewTransactionLogFile(); _fileWithTransactionLog!.HardFlush(); _fileWithTransactionLog.Truncate(); UpdateTransactionLogInBTreeRoot(_lastCommitted); } // When not opening history commit KVI file will be created by compaction if (openUpToCommitUlong.HasValue) { CreateIndexFile(CancellationToken.None, preserveKeyIndexGeneration, true); } } if (_fileIdWithTransactionLog != 0) { if (_writerWithTransactionLog == null) { _fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter(); } if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } } _fileCollection.DeleteAllUnknownFiles(); } foreach (var fileInfo in _fileCollection.FileInfos) { var ft = fileInfo.Value.FileType; if (ft == KVFileType.TransactionLog || ft == KVFileType.PureValuesWithId || ft == KVFileType.PureValues) { _fileCollection.GetFile(fileInfo.Key)?.AdvisePrefetch(); } } } finally { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } } } void MarkFileForRemoval(uint fileId) { var file = _fileCollection.GetFile(fileId); if (file != null) Logger?.FileMarkedForDelete(file.Index); else Logger?.LogWarning($"Marking for delete file id {fileId} unknown in file collection."); _fileCollection.MakeIdxUnknown(fileId); } bool IKeyValueDBInternal.LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info) { return LoadUsedFilesFromKeyIndex(fileId, info); } public long CalculatePreserveKeyIndexGeneration(uint preserveKeyIndexKey) { if (preserveKeyIndexKey <= 0) return -1; return preserveKeyIndexKey < uint.MaxValue ? GetGeneration(preserveKeyIndexKey) : long.MaxValue; } internal uint CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes) { var preserveKeyIndexKey = uint.MaxValue; var preserveHistoryUpToCommitUlong = (ulong)Interlocked.Read(ref _preserveHistoryUpToCommitUlong); if (preserveHistoryUpToCommitUlong != ulong.MaxValue) { var nearKeyIndex = keyIndexes.Length - 1; while (nearKeyIndex >= 0) { if (keyIndexes[nearKeyIndex].CommitUlong <= preserveHistoryUpToCommitUlong) { preserveKeyIndexKey = keyIndexes[nearKeyIndex].Key; break; } nearKeyIndex--; } if (nearKeyIndex < 0) preserveKeyIndexKey = 0; } return preserveKeyIndexKey; } long IKeyValueDBInternal.ReplaceBTreeValues(CancellationToken cancellation, Dictionary<ulong, ulong> newPositionMap) { return ReplaceBTreeValues(cancellation, newPositionMap); } long[] IKeyValueDBInternal.CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration) { return CreateIndexFile(cancellation, preserveKeyIndexGeneration); } ISpanWriter IKeyValueDBInternal.StartPureValuesFile(out uint fileId) { return StartPureValuesFile(out fileId); } long[] CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration, bool fullSpeed = false) { var root = ReferenceAndGetLastCommitted(); try { var idxFileId = CreateKeyIndexFile((IRootNode)root, cancellation, fullSpeed); MarkAsUnknown(_fileCollection.FileInfos.Where(p => p.Value.FileType == KVFileType.KeyIndex && p.Key != idxFileId && p.Value.Generation != preserveKeyIndexGeneration).Select(p => p.Key)); return ((FileKeyIndex)_fileCollection.FileInfoByIdx(idxFileId))!.UsedFilesInOlderGenerations!; } finally { DereferenceRootNodeInternal(root); } } internal bool LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info) { try { var file = FileCollection.GetFile(fileId); var readerController = file!.GetExclusiveReader(); var reader = new SpanReader(readerController); FileKeyIndex.SkipHeader(ref reader); var keyCount = info.KeyValueCount; var usedFileIds = new HashSet<uint>(); if (info.Compression == KeyIndexCompression.Old) { for (var i = 0; i < keyCount; i++) { var keyLength = reader.ReadVInt32(); reader.SkipBlock(keyLength); var vFileId = reader.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); reader.SkipVUInt32(); reader.SkipVInt32(); } reader.Sync(); } else { reader.Sync(); var decompressionController = _kviCompressionStrategy.StartDecompression(info.Compression, readerController); try { reader = new(decompressionController); for (var i = 0; i < keyCount; i++) { reader.SkipVUInt32(); var keyLengthWithoutPrefix = (int)reader.ReadVUInt32(); reader.SkipBlock(keyLengthWithoutPrefix); var vFileId = reader.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); reader.SkipVUInt32(); reader.SkipVInt32(); } reader.Sync(); } finally { _kviCompressionStrategy.FinishDecompression(info.Compression, decompressionController); } } reader = new(readerController); var trlGeneration = GetGeneration(info.TrLogFileId); info.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); return TestKviMagicEndMarker(fileId, ref reader, file); } catch (Exception) { return false; } } bool LoadKeyIndex(uint fileId, IKeyIndex info) { try { var file = FileCollection.GetFile(fileId); var readerController = file!.GetExclusiveReader(); var reader = new SpanReader(readerController); FileKeyIndex.SkipHeader(ref reader); var keyCount = info.KeyValueCount; _nextRoot!.TrLogFileId = info.TrLogFileId; _nextRoot.TrLogOffset = info.TrLogOffset; _nextRoot.CommitUlong = info.CommitUlong; if (info.Ulongs != null) for (var i = 0u; i < info.Ulongs.Length; i++) { _nextRoot.SetUlong(i, info.Ulongs[i]); } var usedFileIds = new HashSet<uint>(); var cursor = _nextRoot.CreateCursor(); if (info.Compression == KeyIndexCompression.Old) { cursor.BuildTree(keyCount, ref reader, (ref SpanReader reader2, ref ByteBuffer key, in Span<byte> trueValue) => { var keyLength = reader2.ReadVInt32(); key = ByteBuffer.NewAsync(new byte[Math.Abs(keyLength)]); reader2.ReadBlock(key); if (keyLength < 0) { _compression.DecompressKey(ref key); } trueValue.Clear(); var vFileId = reader2.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); MemoryMarshal.Write(trueValue, ref vFileId); var valueOfs = reader2.ReadVUInt32(); var valueSize = reader2.ReadVInt32(); if (vFileId == 0) { var len = valueSize >> 24; trueValue[4] = (byte)len; switch (len) { case 7: trueValue[11] = (byte)(valueOfs >> 24); goto case 6; case 6: trueValue[10] = (byte)(valueOfs >> 16); goto case 5; case 5: trueValue[9] = (byte)(valueOfs >> 8); goto case 4; case 4: trueValue[8] = (byte)valueOfs; goto case 3; case 3: trueValue[7] = (byte)valueSize; goto case 2; case 2: trueValue[6] = (byte)(valueSize >> 8); goto case 1; case 1: trueValue[5] = (byte)(valueSize >> 16); break; case 0: break; default: throw new BTDBException("Corrupted DB"); } } else { MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); } }); reader.Sync(); } else { reader.Sync(); var decompressionController = _kviCompressionStrategy.StartDecompression(info.Compression, readerController); try { reader = new(decompressionController); var prevKey = ByteBuffer.NewEmpty(); cursor.BuildTree(keyCount, ref reader, (ref SpanReader reader2, ref ByteBuffer key, in Span<byte> trueValue) => { var prefixLen = (int)reader2.ReadVUInt32(); var keyLengthWithoutPrefix = (int)reader2.ReadVUInt32(); var keyLen = prefixLen + keyLengthWithoutPrefix; key.Expand(keyLen); Array.Copy(prevKey.Buffer!, prevKey.Offset, key.Buffer!, key.Offset, prefixLen); reader2.ReadBlock(key.Slice(prefixLen)); prevKey = key; var vFileId = reader2.ReadVUInt32(); if (vFileId > 0) usedFileIds.Add(vFileId); trueValue.Clear(); MemoryMarshal.Write(trueValue, ref vFileId); var valueOfs = reader2.ReadVUInt32(); var valueSize = reader2.ReadVInt32(); if (vFileId == 0) { var len = valueSize >> 24; trueValue[4] = (byte)len; switch (len) { case 7: trueValue[11] = (byte)(valueOfs >> 24); goto case 6; case 6: trueValue[10] = (byte)(valueOfs >> 16); goto case 5; case 5: trueValue[9] = (byte)(valueOfs >> 8); goto case 4; case 4: trueValue[8] = (byte)valueOfs; goto case 3; case 3: trueValue[7] = (byte)valueSize; goto case 2; case 2: trueValue[6] = (byte)(valueSize >> 8); goto case 1; case 1: trueValue[5] = (byte)(valueSize >> 16); break; case 0: break; default: throw new BTDBException("Corrupted DB"); } } else { MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); } }); reader.Sync(); } finally { _kviCompressionStrategy.FinishDecompression(info.Compression, decompressionController); } } reader = new(readerController); var trlGeneration = GetGeneration(info.TrLogFileId); info.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); return TestKviMagicEndMarker(fileId, ref reader, file); } catch (Exception) { return false; } } bool TestKviMagicEndMarker(uint fileId, ref SpanReader reader, IFileCollectionFile file) { if (reader.Eof) return true; if ((ulong)reader.GetCurrentPosition() + 4 == file.GetSize() && reader.ReadInt32() == EndOfIndexFileMarker) return true; if (_lenientOpen) { Logger?.LogWarning("End of Kvi " + fileId + " had some garbage at " + (reader.GetCurrentPosition() - 4) + " ignoring that because of LenientOpen"); return true; } return false; } void LoadTransactionLogs(uint firstTrLogId, uint firstTrLogOffset, ulong? openUpToCommitUlong) { while (firstTrLogId != 0 && firstTrLogId != uint.MaxValue) { _fileIdWithTransactionLog = 0; if (LoadTransactionLog(firstTrLogId, firstTrLogOffset, openUpToCommitUlong)) { _fileIdWithTransactionLog = firstTrLogId; } firstTrLogOffset = 0; _fileIdWithPreviousTransactionLog = firstTrLogId; var fileInfo = _fileCollection.FileInfoByIdx(firstTrLogId); if (fileInfo == null) return; firstTrLogId = ((IFileTransactionLog)fileInfo).NextFileId; } } // Return true if it is suitable for continuing writing new transactions bool LoadTransactionLog(uint fileId, uint logOffset, ulong? openUpToCommitUlong) { if (openUpToCommitUlong.HasValue && _lastCommitted.CommitUlong >= openUpToCommitUlong) { return false; } Span<byte> trueValue = stackalloc byte[12]; var collectionFile = FileCollection.GetFile(fileId); var readerController = collectionFile!.GetExclusiveReader(); var reader = new SpanReader(readerController); try { if (logOffset == 0) { FileTransactionLog.SkipHeader(ref reader); } else { reader.SkipBlock(logOffset); } if (reader.Eof) return true; var afterTemporaryEnd = false; var finishReading = false; ICursor cursor; ICursor cursor2; if (_nextRoot != null) { cursor = _nextRoot.CreateCursor(); cursor2 = _nextRoot.CreateCursor(); } else { cursor = _lastCommitted.CreateCursor(); cursor2 = _lastCommitted.CreateCursor(); } while (!reader.Eof) { var command = (KVCommandType)reader.ReadUInt8(); if (command == 0 && afterTemporaryEnd) { collectionFile.SetSize(reader.GetCurrentPosition() - 1); return true; } if (finishReading) { return false; } afterTemporaryEnd = false; switch (command & KVCommandType.CommandMask) { case KVCommandType.CreateOrUpdateDeprecated: case KVCommandType.CreateOrUpdate: { if (_nextRoot == null) return false; var keyLen = reader.ReadVInt32(); var valueLen = reader.ReadVInt32(); var key = new byte[keyLen]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } trueValue.Clear(); var valueOfs = (uint)reader.GetCurrentPosition(); var valueSize = (command & KVCommandType.SecondParamCompressed) != 0 ? -valueLen : valueLen; if (valueLen <= MaxValueSizeInlineInMemory && (command & KVCommandType.SecondParamCompressed) == 0) { trueValue[4] = (byte)valueLen; reader.ReadBlock(ref MemoryMarshal.GetReference(trueValue.Slice(5, valueLen)), (uint)valueLen); } else { MemoryMarshal.Write(trueValue, ref fileId); MemoryMarshal.Write(trueValue.Slice(4), ref valueOfs); MemoryMarshal.Write(trueValue.Slice(8), ref valueSize); reader.SkipBlock(valueLen); } cursor.Upsert(keyBuf.AsSyncReadOnlySpan(), trueValue); } break; case KVCommandType.EraseOne: { if (_nextRoot == null) return false; var keyLen = reader.ReadVInt32(); var key = new byte[keyLen]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } if (cursor.FindExact(keyBuf.AsSyncReadOnlySpan())) { cursor.Erase(); } else if (!_lenientOpen) { _nextRoot = null; return false; } } break; case KVCommandType.EraseRange: { if (_nextRoot == null) return false; var keyLen1 = reader.ReadVInt32(); var keyLen2 = reader.ReadVInt32(); var key = new byte[keyLen1]; reader.ReadBlock(key); var keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.FirstParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } var findResult = cursor.Find(keyBuf.AsSyncReadOnlySpan()); if (findResult != FindResult.Exact && !_lenientOpen) { _nextRoot = null; return false; } if (findResult == FindResult.Previous) cursor.MoveNext(); key = new byte[keyLen2]; reader.ReadBlock(key); keyBuf = ByteBuffer.NewAsync(key); if ((command & KVCommandType.SecondParamCompressed) != 0) { _compression.DecompressKey(ref keyBuf); } findResult = cursor2.Find(keyBuf.AsSyncReadOnlySpan()); if (findResult != FindResult.Exact && !_lenientOpen) { _nextRoot = null; return false; } if (findResult == FindResult.Next) cursor2.MovePrevious(); cursor.EraseTo(cursor2); } break; case KVCommandType.DeltaUlongs: { if (_nextRoot == null) return false; var idx = reader.ReadVUInt32(); var delta = reader.ReadVUInt64(); // overflow is expected in case Ulong is decreasing but that should be rare _nextRoot.SetUlong(idx, unchecked(_nextRoot.GetUlong(idx) + delta)); } break; case KVCommandType.TransactionStart: if (!reader.CheckMagic(MagicStartOfTransaction)) return false; if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; return false; } _nextRoot = _lastCommitted.CreateWritableTransaction(); cursor.SetNewRoot(_nextRoot); cursor2.SetNewRoot(_nextRoot); break; case KVCommandType.CommitWithDeltaUlong: if (_nextRoot == null) return false; unchecked // overflow is expected in case commitUlong is decreasing but that should be rare { _nextRoot.CommitUlong += reader.ReadVUInt64(); } goto case KVCommandType.Commit; case KVCommandType.Commit: if (_nextRoot == null) return false; _nextRoot.TrLogFileId = fileId; _nextRoot.TrLogOffset = (uint)reader.GetCurrentPosition(); _lastCommitted.Dispose(); _nextRoot.Commit(); _lastCommitted = _nextRoot; _listHead = _lastCommitted; _nextRoot = null; if (openUpToCommitUlong.HasValue && _lastCommitted.CommitUlong >= openUpToCommitUlong) { finishReading = true; } break; case KVCommandType.Rollback: _nextRoot.Dispose(); _nextRoot = null; break; case KVCommandType.EndOfFile: return false; case KVCommandType.TemporaryEndOfFile: _lastCommitted.TrLogFileId = fileId; _lastCommitted.TrLogOffset = (uint)reader.GetCurrentPosition(); afterTemporaryEnd = true; break; default: if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } return false; } } return afterTemporaryEnd; } catch (EndOfStreamException) { if (_nextRoot != null) { _nextRoot.Dispose(); _nextRoot = null; } return false; } } uint LinkTransactionLogFileIds(uint latestTrLogFileId) { var nextId = 0u; var currentId = latestTrLogFileId; while (currentId != 0) { var fileInfo = _fileCollection.FileInfoByIdx(currentId); var fileTransactionLog = fileInfo as IFileTransactionLog; if (fileTransactionLog == null) { _missingSomeTrlFiles = currentId; break; } fileTransactionLog.NextFileId = nextId; nextId = currentId; currentId = fileTransactionLog.PreviousFileId; } return nextId; } public void Dispose() { _compactorScheduler?.RemoveCompactAction(_compactFunc!); lock (_writeLock) { if (_writingTransaction != null) throw new BTDBException("Cannot dispose KeyValueDB when writing transaction still running"); while (_writeWaitingQueue.Count > 0) { _writeWaitingQueue.Dequeue().TrySetCanceled(); } _lastCommitted.Dereference(); FreeWaitingToDisposeUnsafe(); } if (_writerWithTransactionLog != null) { var writer = new SpanWriter(_writerWithTransactionLog); writer.WriteUInt8((byte)KVCommandType.TemporaryEndOfFile); writer.Sync(); _fileWithTransactionLog!.HardFlushTruncateSwitchToDisposedMode(); } } public bool DurableTransactions { get; set; } public IRootNodeInternal ReferenceAndGetLastCommitted() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { return node; } } } void IKeyValueDBInternal.MarkAsUnknown(IEnumerable<uint> fileIds) { MarkAsUnknown(fileIds); } IFileCollectionWithFileInfos IKeyValueDBInternal.FileCollection => FileCollection; bool IKeyValueDBInternal.ContainsValuesAndDoesNotTouchGeneration(uint fileKey, long dontTouchGeneration) { return ContainsValuesAndDoesNotTouchGeneration(fileKey, dontTouchGeneration); } public IFileCollectionWithFileInfos FileCollection => _fileCollection; bool IKeyValueDBInternal.AreAllTransactionsBeforeFinished(long transactionId) { return AreAllTransactionsBeforeFinished(transactionId); } public IRootNodeInternal ReferenceAndGetOldestRoot() { while (true) { var oldestRoot = _lastCommitted; var usedTransaction = _listHead; while (usedTransaction != null) { if (!usedTransaction.ShouldBeDisposed) { if (unchecked(usedTransaction.TransactionId - oldestRoot.TransactionId) < 0) { oldestRoot = usedTransaction; } } usedTransaction = usedTransaction.Next; } // Memory barrier inside next statement if (!oldestRoot.Reference()) { return oldestRoot; } } } public IKeyValueDBTransaction StartTransaction() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { var tr = new BTreeKeyValueDBTransaction(this, node, false, false); _transactions.Add(tr, null); return tr; } } } readonly ConditionalWeakTable<IKeyValueDBTransaction, object?> _transactions = new(); public IKeyValueDBTransaction StartReadOnlyTransaction() { while (true) { var node = _lastCommitted; // Memory barrier inside next statement if (!node.Reference()) { var tr = new BTreeKeyValueDBTransaction(this, node, false, true); _transactions.Add(tr, null); return tr; } } } public ValueTask<IKeyValueDBTransaction> StartWritingTransaction() { lock (_writeLock) { if (_writingTransaction == null) { var tr = NewWritingTransactionUnsafe(); _transactions.Add(tr, null); return new(tr); } var tcs = new TaskCompletionSource<IKeyValueDBTransaction>(); _writeWaitingQueue.Enqueue(tcs); return new(tcs.Task); } } class FreqStats<K> : RefDictionary<K, uint> where K : IEquatable<K> { public void Inc(K key) { GetOrAddValueRef(key)++; } public void AddToStringBuilder(StringBuilder sb, string name) { sb.Append(name); sb.Append(" => Count\n"); var list = new KeyValuePair<K, uint>[Count]; CopyTo(list, 0); Array.Sort(list, Comparer<KeyValuePair<K, uint>>.Create((a, b) => Comparer<K>.Default.Compare(a.Key, b.Key))); foreach (var t in list) { sb.AppendFormat("{0} => {1}\n", t.Key, t.Value); } } } public string CalcStats() { var oldestRoot = (IRootNode)ReferenceAndGetOldestRoot(); var lastCommitted = (IRootNode)ReferenceAndGetLastCommitted(); try { var sb = new StringBuilder( $"KeyValueCount:{lastCommitted.GetCount()}\nFileCount:{FileCollection.GetCount()}\nFileGeneration:{FileCollection.LastFileGeneration}\n"); sb.Append( $"LastTrId:{lastCommitted.TransactionId},TRL:{lastCommitted.TrLogFileId},ComUlong:{lastCommitted.CommitUlong}\n"); sb.Append( $"OldestTrId:{oldestRoot.TransactionId},TRL:{oldestRoot.TrLogFileId},ComUlong:{oldestRoot.CommitUlong}\n"); foreach (var file in _fileCollection.FileInfos) { sb.AppendFormat("{0} Size:{1} Type:{2} Gen:{3}\n", file.Key, FileCollection.GetSize(file.Key), file.Value.FileType, file.Value.Generation); } return sb.ToString(); } finally { DereferenceRootNodeInternal(oldestRoot); DereferenceRootNodeInternal(lastCommitted); } } public bool Compact(CancellationToken cancellation) { return new Compactor(this, cancellation).Run(); } public void CreateKvi(CancellationToken cancellation) { CreateIndexFile(cancellation, 0); } public IKeyValueDBLogger? Logger { get; set; } public uint CompactorRamLimitInMb { get; set; } public ulong? PreserveHistoryUpToCommitUlong { get { var preserveHistoryUpToCommitUlong = (ulong)Interlocked.Read(ref _preserveHistoryUpToCommitUlong); return preserveHistoryUpToCommitUlong == ulong.MaxValue ? null : (ulong?)preserveHistoryUpToCommitUlong; } set => Interlocked.Exchange(ref _preserveHistoryUpToCommitUlong, (long)(value ?? ulong.MaxValue)); } internal IRootNode MakeWritableTransaction(BTreeKeyValueDBTransaction keyValueDBTransaction, IRootNode btreeRoot) { lock (_writeLock) { if (_writingTransaction != null) throw new BTDBTransactionRetryException("Another writing transaction already running"); if (_lastCommitted != btreeRoot) throw new BTDBTransactionRetryException("Another writing transaction already finished"); _writingTransaction = keyValueDBTransaction; var result = _lastCommitted.CreateWritableTransaction(); btreeRoot.Dereference(); return result; } } internal void CommitFromCompactor(IRootNode root) { lock (_writeLock) { _writingTransaction = null; _lastCommitted.Dereference(); _lastCommitted = root; root.Next = _listHead; _listHead = root; root.Commit(); TryDequeWaiterForWritingTransaction(); } } internal void CommitWritingTransaction(IRootNode root, bool temporaryCloseTransactionLog) { try { var writer = new SpanWriter(_writerWithTransactionLog!); WriteUlongsDiff(ref writer, root, _lastCommitted); var deltaUlong = unchecked(root.CommitUlong - _lastCommitted.CommitUlong); if (deltaUlong != 0) { writer.WriteUInt8((byte)KVCommandType.CommitWithDeltaUlong); writer.WriteVUInt64(deltaUlong); } else { writer.WriteUInt8((byte)KVCommandType.Commit); } writer.Sync(); if (DurableTransactions) { _fileWithTransactionLog!.HardFlush(); } else { _fileWithTransactionLog!.Flush(); } UpdateTransactionLogInBTreeRoot(root); if (temporaryCloseTransactionLog) { writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.TemporaryEndOfFile); writer.Sync(); _fileWithTransactionLog!.Flush(); _fileWithTransactionLog.Truncate(); } lock (_writeLock) { _writingTransaction = null; _lastCommitted.Dereference(); _lastCommitted = root; root.Next = _listHead; _listHead = root; root.Commit(); root = null; TryDequeWaiterForWritingTransaction(); } } finally { root?.Dispose(); } } void WriteUlongsDiff(ref SpanWriter writer, IRootNode newArray, IRootNode oldArray) { var newCount = newArray.GetUlongCount(); var oldCount = oldArray.GetUlongCount(); var maxCount = Math.Max(newCount, oldCount); for (var i = 0u; i < maxCount; i++) { var oldValue = i < oldCount ? oldArray.GetUlong(i) : 0; var newValue = i < newCount ? newArray.GetUlong(i) : 0; var deltaUlong = unchecked(newValue - oldValue); if (deltaUlong != 0) { writer.WriteUInt8((byte)KVCommandType.DeltaUlongs); writer.WriteVUInt32(i); writer.WriteVUInt64(deltaUlong); } } } void UpdateTransactionLogInBTreeRoot(IRootNode root) { if (root.TrLogFileId != _fileIdWithTransactionLog && root.TrLogFileId != 0) { _compactorScheduler?.AdviceRunning(false); } root.TrLogFileId = _fileIdWithTransactionLog; if (_writerWithTransactionLog != null) { root.TrLogOffset = (uint)_writerWithTransactionLog.GetCurrentPositionWithoutWriter(); } else { root.TrLogOffset = 0; } } void TryDequeWaiterForWritingTransaction() { FreeWaitingToDisposeUnsafe(); if (_writeWaitingQueue.Count == 0) return; var tcs = _writeWaitingQueue.Dequeue(); var tr = NewWritingTransactionUnsafe(); _transactions.Add(tr, null); tcs.SetResult(tr); } void TryFreeWaitingToDispose() { var taken = false; try { Monitor.TryEnter(_writeLock, ref taken); if (taken && _writingTransaction == null) { FreeWaitingToDisposeUnsafe(); } } finally { if (taken) Monitor.Exit(_writeLock); } } BTreeKeyValueDBTransaction NewWritingTransactionUnsafe() { if (_readOnly) throw new BTDBException("Database opened in readonly mode"); FreeWaitingToDisposeUnsafe(); var newTransactionRoot = _lastCommitted.CreateWritableTransaction(); try { var tr = new BTreeKeyValueDBTransaction(this, newTransactionRoot, true, false); _writingTransaction = tr; return tr; } catch { newTransactionRoot.Dispose(); throw; } } void FreeWaitingToDisposeUnsafe() { while (_listHead is { ShouldBeDisposed: true }) { _listHead.Dispose(); _listHead = _listHead.Next; } var cur = _listHead; var next = cur?.Next; while (next != null) { if (next.ShouldBeDisposed) { cur.Next = next.Next; next.Dispose(); } else { cur = next; } next = next.Next; } } internal void RevertWritingTransaction(IRootNode writtenToTransactionLog, bool nothingWrittenToTransactionLog) { writtenToTransactionLog.Dispose(); if (!nothingWrittenToTransactionLog) { var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.Rollback); writer.Sync(); _fileWithTransactionLog!.Flush(); lock (_writeLock) { _writingTransaction = null; UpdateTransactionLogInBTreeRoot(_lastCommitted); TryDequeWaiterForWritingTransaction(); } } else { lock (_writeLock) { _writingTransaction = null; TryDequeWaiterForWritingTransaction(); } } } internal void WriteStartTransaction() { if (_fileIdWithTransactionLog == 0) { WriteStartOfNewTransactionLogFile(); } else { if (_writerWithTransactionLog == null) { _fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter(); } if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.TransactionStart); writer.WriteByteArrayRaw(MagicStartOfTransaction); writer.Sync(); } void WriteStartOfNewTransactionLogFile() { SpanWriter writer; if (_writerWithTransactionLog != null) { writer = new SpanWriter(_writerWithTransactionLog); writer.WriteUInt8((byte)KVCommandType.EndOfFile); writer.Sync(); _fileWithTransactionLog!.HardFlushTruncateSwitchToReadOnlyMode(); _fileIdWithPreviousTransactionLog = _fileIdWithTransactionLog; } _fileWithTransactionLog = FileCollection.AddFile("trl"); Logger?.TransactionLogCreated(_fileWithTransactionLog.Index); _fileIdWithTransactionLog = _fileWithTransactionLog.Index; var transactionLog = new FileTransactionLog(FileCollection.NextGeneration(), FileCollection.Guid, _fileIdWithPreviousTransactionLog); _writerWithTransactionLog = _fileWithTransactionLog.GetAppenderWriter(); writer = new SpanWriter(_writerWithTransactionLog); transactionLog.WriteHeader(ref writer); writer.Sync(); FileCollection.SetInfo(_fileIdWithTransactionLog, transactionLog); } public void WriteCreateOrUpdateCommand(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value, in Span<byte> trueValue) { var trlPos = _writerWithTransactionLog!.GetCurrentPositionWithoutWriter(); if (trlPos > 256 && trlPos + key.Length + 16 + value.Length > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.CreateOrUpdate); writer.WriteVInt32(key.Length); writer.WriteVInt32(value.Length); writer.WriteBlock(key); if (value.Length != 0) { if (value.Length <= MaxValueSizeInlineInMemory) { trueValue[4] = (byte)value.Length; Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(trueValue), 0); value.CopyTo(trueValue.Slice(5)); } else { Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(trueValue), _fileIdWithTransactionLog); var valueOfs = (uint)writer.GetCurrentPosition(); Unsafe.WriteUnaligned( ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(trueValue), (IntPtr)4), valueOfs); Unsafe.WriteUnaligned( ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(trueValue), (IntPtr)8), value.Length); } writer.WriteBlock(value); } else { trueValue.Clear(); } writer.Sync(); } public uint CalcValueSize(uint valueFileId, uint valueOfs, int valueSize) { if (valueFileId == 0) { return valueOfs & 0xff; } return (uint)Math.Abs(valueSize); } public ReadOnlySpan<byte> ReadValue(ReadOnlySpan<byte> trueValue) { var valueFileId = MemoryMarshal.Read<uint>(trueValue); if (valueFileId == 0) { var len = trueValue[4]; return trueValue.Slice(5, len); } var valueSize = MemoryMarshal.Read<int>(trueValue.Slice(8)); if (valueSize == 0) return new ReadOnlySpan<byte>(); var valueOfs = MemoryMarshal.Read<uint>(trueValue.Slice(4)); var compressed = false; if (valueSize < 0) { compressed = true; valueSize = -valueSize; } Span<byte> result = new byte[valueSize]; var file = FileCollection.GetFile(valueFileId); if (file == null) throw new BTDBException( $"ReadValue({valueFileId},{valueOfs},{valueSize}) compressed: {compressed} file does not exist in {CalcStats()}"); file.RandomRead(result, valueOfs, false); if (compressed) result = _compression.DecompressValue(result); return result; } public ReadOnlySpan<byte> ReadValue(ReadOnlySpan<byte> trueValue, ref byte buffer, int bufferLength) { var valueFileId = MemoryMarshal.Read<uint>(trueValue); if (valueFileId == 0) { var len = trueValue[4]; var res = trueValue.Slice(5, len); if (len <= bufferLength) { Unsafe.CopyBlockUnaligned(ref buffer, ref MemoryMarshal.GetReference(res), len); return MemoryMarshal.CreateReadOnlySpan(ref buffer, len); } return res.ToArray(); } var valueSize = MemoryMarshal.Read<int>(trueValue[8..]); if (valueSize == 0) return new ReadOnlySpan<byte>(); var valueOfs = MemoryMarshal.Read<uint>(trueValue[4..]); var compressed = false; if (valueSize < 0) { compressed = true; valueSize = -valueSize; } Span<byte> result = bufferLength < valueSize ? new byte[valueSize] : MemoryMarshal.CreateSpan(ref buffer, valueSize); var file = FileCollection.GetFile(valueFileId); if (file == null) throw new BTDBException( $"ReadValue({valueFileId},{valueOfs},{valueSize}) compressed: {compressed} file does not exist in {CalcStats()}"); file.RandomRead(result, valueOfs, false); if (compressed) result = _compression.DecompressValue(result); return result; } public void WriteEraseOneCommand(in ReadOnlySpan<byte> key) { if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.EraseOne); writer.WriteVInt32(key.Length); writer.WriteBlock(key); writer.Sync(); } public void WriteEraseRangeCommand(in ReadOnlySpan<byte> firstKey, in ReadOnlySpan<byte> secondKey) { if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize) { WriteStartOfNewTransactionLogFile(); } var writer = new SpanWriter(_writerWithTransactionLog!); writer.WriteUInt8((byte)KVCommandType.EraseRange); writer.WriteVInt32(firstKey.Length); writer.WriteVInt32(secondKey.Length); writer.WriteBlock(firstKey); writer.WriteBlock(secondKey); writer.Sync(); } uint CreateKeyIndexFile(IRootNode root, CancellationToken cancellation, bool fullSpeed) { var bytesPerSecondLimiter = new BytesPerSecondLimiter(fullSpeed ? 0 : CompactorWriteBytesPerSecondLimit); var file = FileCollection.AddFile("kvi"); var writerController = file.GetExclusiveAppenderWriter(); var writer = new SpanWriter(writerController); var keyCount = root.GetCount(); if (root.TrLogFileId != 0) FileCollection.ConcurentTemporaryTruncate(root.TrLogFileId, root.TrLogOffset); var (compressionType, compressionController) = _kviCompressionStrategy.StartCompression((ulong)keyCount, writerController); var keyIndex = new FileKeyIndex(FileCollection.NextGeneration(), FileCollection.Guid, root.TrLogFileId, root.TrLogOffset, keyCount, root.CommitUlong, compressionType, root.UlongsArray); keyIndex.WriteHeader(ref writer); writer.Sync(); ulong originalSize; var usedFileIds = new HashSet<uint>(); try { writer = new(compressionController); if (keyCount > 0) { var keyValueIterateCtx = new KeyValueIterateCtx { CancellationToken = cancellation, Writer = writer }; root.KeyValueIterate(ref keyValueIterateCtx, (ref KeyValueIterateCtx ctx) => { ref var writerReference = ref ctx.Writer; var memberValue = ctx.CurrentValue; writerReference.WriteVUInt32(ctx.PreviousCurrentCommonLength); writerReference.WriteVUInt32((uint)(ctx.CurrentPrefix.Length + ctx.CurrentSuffix.Length - ctx.PreviousCurrentCommonLength)); if (ctx.CurrentPrefix.Length <= ctx.PreviousCurrentCommonLength) { writerReference.WriteBlock( ctx.CurrentSuffix.Slice((int)ctx.PreviousCurrentCommonLength - ctx.CurrentPrefix.Length)); } else { writerReference.WriteBlock(ctx.CurrentPrefix.Slice((int)ctx.PreviousCurrentCommonLength)); writerReference.WriteBlock(ctx.CurrentSuffix); } var vFileId = MemoryMarshal.Read<uint>(memberValue); if (vFileId > 0) usedFileIds.Add(vFileId); writerReference.WriteVUInt32(vFileId); if (vFileId == 0) { uint valueOfs; int valueSize; var inlineValueBuf = memberValue[5..]; var valueLen = memberValue[4]; switch (valueLen) { case 0: valueOfs = 0; valueSize = 0; break; case 1: valueOfs = 0; valueSize = 0x1000000 | (inlineValueBuf[0] << 16); break; case 2: valueOfs = 0; valueSize = 0x2000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8); break; case 3: valueOfs = 0; valueSize = 0x3000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 4: valueOfs = inlineValueBuf[3]; valueSize = 0x4000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 5: valueOfs = inlineValueBuf[3] | ((uint)inlineValueBuf[4] << 8); valueSize = 0x5000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 6: valueOfs = inlineValueBuf[3] | ((uint)inlineValueBuf[4] << 8) | ((uint)inlineValueBuf[5] << 16); valueSize = 0x6000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; case 7: valueOfs = inlineValueBuf[3] | ((uint)inlineValueBuf[4] << 8) | ((uint)inlineValueBuf[5] << 16) | ((uint)inlineValueBuf[6] << 24); valueSize = 0x7000000 | (inlineValueBuf[0] << 16) | (inlineValueBuf[1] << 8) | inlineValueBuf[2]; break; default: throw new ArgumentOutOfRangeException(); } writerReference.WriteVUInt32(valueOfs); writerReference.WriteVInt32(valueSize); } else { var valueOfs = MemoryMarshal.Read<uint>(memberValue[4..]); var valueSize = MemoryMarshal.Read<int>(memberValue[8..]); writerReference.WriteVUInt32(valueOfs); writerReference.WriteVInt32(valueSize); } bytesPerSecondLimiter.Limit((ulong)writerReference.GetCurrentPosition()); }); writer = keyValueIterateCtx.Writer; } writer.Sync(); } finally { originalSize = (ulong)compressionController.GetCurrentPositionWithoutWriter(); _kviCompressionStrategy.FinishCompression(compressionType, compressionController); } file.HardFlush(); writer = new(writerController); writer.WriteInt32(EndOfIndexFileMarker); writer.Sync(); file.HardFlushTruncateSwitchToDisposedMode(); var trlGeneration = GetGeneration(keyIndex.TrLogFileId); keyIndex.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing) .Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray(); FileCollection.SetInfo(file.Index, keyIndex); Logger?.KeyValueIndexCreated(file.Index, keyIndex.KeyValueCount, file.GetSize(), TimeSpan.FromMilliseconds(bytesPerSecondLimiter.TotalTimeInMs), originalSize); return file.Index; } internal bool ContainsValuesAndDoesNotTouchGeneration(uint fileId, long dontTouchGeneration) { var info = FileCollection.FileInfoByIdx(fileId); if (info == null) return false; if (info.Generation >= dontTouchGeneration) return false; return info.FileType == KVFileType.TransactionLog || info.FileType == KVFileType.PureValues; } internal ISpanWriter StartPureValuesFile(out uint fileId) { var fId = FileCollection.AddFile("pvl"); fileId = fId.Index; var pureValues = new FilePureValues(FileCollection.NextGeneration(), FileCollection.Guid); var writerController = fId.GetAppenderWriter(); FileCollection.SetInfo(fId.Index, pureValues); var writer = new SpanWriter(writerController); pureValues.WriteHeader(ref writer); writer.Sync(); return writerController; } long ReplaceBTreeValues(CancellationToken cancellation, Dictionary<ulong, ulong> newPositionMap) { byte[] restartKey = null; while (true) { var iterationTimeOut = DateTime.UtcNow + TimeSpan.FromMilliseconds(50); using (var tr = StartWritingTransaction().Result) { var newRoot = ((BTreeKeyValueDBTransaction)tr).BTreeRoot; var cursor = newRoot!.CreateCursor(); if (restartKey != null) { cursor.Find(restartKey); cursor.MovePrevious(); } else { cursor.MoveNext(); } var ctx = default(ValueReplacerCtx); ctx._operationTimeout = iterationTimeOut; ctx._interrupted = false; ctx._positionMap = newPositionMap; ctx._cancellation = cancellation; cursor.ValueReplacer(ref ctx); restartKey = ctx._interruptedKey; cancellation.ThrowIfCancellationRequested(); ((BTreeKeyValueDBTransaction)tr).CommitFromCompactor(); if (!ctx._interrupted) { return newRoot.TransactionId; } } Thread.Sleep(10); } } long IKeyValueDBInternal.GetGeneration(uint fileId) { return GetGeneration(fileId); } internal void MarkAsUnknown(IEnumerable<uint> fileIds) { foreach (var fileId in fileIds) { MarkFileForRemoval(fileId); } } internal long GetGeneration(uint fileId) { if (fileId == 0) return -1; var fileInfo = FileCollection.FileInfoByIdx(fileId); if (fileInfo == null) { throw new ArgumentOutOfRangeException(nameof(fileId)); } return fileInfo.Generation; } internal long GetGenerationIgnoreMissing(uint fileId) { if (fileId == 0) return -1; var fileInfo = FileCollection.FileInfoByIdx(fileId); if (fileInfo == null) { return -1; } return fileInfo.Generation; } internal bool AreAllTransactionsBeforeFinished(long transactionId) { var usedTransaction = _listHead; while (usedTransaction != null) { if (!usedTransaction.ShouldBeDisposed && usedTransaction.TransactionId - transactionId < 0) { return false; } usedTransaction = usedTransaction.Next; } return true; } internal ulong DistanceFromLastKeyIndex(IRootNode root) { var keyIndex = FileCollection.FileInfos.Where(p => p.Value.FileType == KVFileType.KeyIndex) .Select(p => (IKeyIndex)p.Value).FirstOrDefault(); if (keyIndex == null) { if (FileCollection.FileInfos.Count(p => p.Value.SubDBId == 0) > 1) return ulong.MaxValue; return root.TrLogOffset; } if (root.TrLogFileId != keyIndex.TrLogFileId) return ulong.MaxValue; return root.TrLogOffset - keyIndex.TrLogOffset; } public T? GetSubDB<T>(long id) where T : class { if (_subDBs.TryGetValue(id, out var subDB)) { if (!(subDB is T db)) throw new ArgumentException($"SubDB of id {id} is not type {typeof(T).FullName}"); return db; } if (typeof(T) == typeof(IChunkStorage)) { subDB = new ChunkStorageInKV(id, _fileCollection, MaxTrLogFileSize); } _subDBs.Add(id, subDB); return (T)subDB; } public void DereferenceRoot(IRootNode currentRoot) { if (currentRoot.Dereference()) { TryFreeWaitingToDispose(); } } public void DereferenceRootNodeInternal(IRootNodeInternal root) { DereferenceRoot((IRootNode)root); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The implementation of the intervals // #define TRACE_PERFORMANCE #define CACHE using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Text; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.DataStructures; namespace Microsoft.Research.AbstractDomains.Numerical { #if DEBUG using ReadOnlyIntervalList = ReadOnlyCollection<Interval>; #else using ReadOnlyIntervalList = List<Interval>; #endif /// <summary> /// An interval is a pair<code>(LowerBound, UpperBound)</code>. /// LowerBound and UpperBound are rational numbers over <code>Int32</code>. /// They can be +oo or -oo /// </summary> [ContractVerification(true)] public sealed class Interval : IntervalBase<Interval, Rational> { #region Private state readonly private bool isBottom; readonly private bool isTop; #endregion #region Static Constructor #if CACHE static private readonly Dictionary<Pair<Rational, Rational>, Interval> common; #endif static private readonly Dictionary<Pair<Rational, Rational>, int> countIntv; private static readonly Interval cachedBottom; private static readonly Interval cachedTop; private static readonly Interval cachedPositiveInterval; private static readonly Interval cachedNegativeInterval; static Interval() { countIntv = new Dictionary<Pair<Rational, Rational>, int>(); common = new Dictionary<Pair<Rational, Rational>, Interval>(); common.Add(new Pair<Rational, Rational>(Rational.For(0), Rational.For(0)), new Interval(Rational.For(0), Rational.For(0))); common.Add(new Pair<Rational, Rational>(Rational.For(1), Rational.For(1)), new Interval(Rational.For(1), Rational.For(1))); common.Add(new Pair<Rational, Rational>(Rational.For(0), Rational.PlusInfinity), new Interval(Rational.For(0), Rational.PlusInfinity)); common.Add(new Pair<Rational, Rational>(Rational.MinusInfinity, Rational.For(0)), new Interval(Rational.MinusInfinity, Rational.For(0))); common.Add(new Pair<Rational, Rational>(Rational.MinusInfinity, Rational.PlusInfinity), new Interval(Rational.MinusInfinity, Rational.PlusInfinity)); cachedBottom = new Interval(Rational.PlusInfinity, Rational.MinusInfinity); cachedTop = new Interval(Rational.MinusInfinity, Rational.PlusInfinity); cachedPositiveInterval = new Interval(0, Rational.PlusInfinity); cachedNegativeInterval = new Interval(Rational.MinusInfinity, 0); } public static Interval UnknownInterval { get { Contract.Ensures(Contract.Result<Interval>() != null); return cachedTop; } } public static Interval UnreachedInterval { get { Contract.Ensures(Contract.Result<Interval>() != null); return cachedBottom; } } public static Interval PositiveInterval { get { Contract.Ensures(Contract.Result<Interval>() != null); return cachedPositiveInterval; } } public static Interval NegativeInterval { get { Contract.Ensures(Contract.Result<Interval>() != null); return cachedNegativeInterval; } } #endregion #region For static public Interval For(Rational lower, Rational upper) { Contract.Requires(!object.Equals(lower, null)); Contract.Requires(!object.Equals(upper, null)); Contract.Ensures(Contract.Result<Interval>() != null); #if CACHE var key = new Pair<Rational, Rational>(lower, upper); Interval val; if (common.TryGetValue(key, out val)) { Contract.Assume(val != null); return val; } #endif var res = new Interval(lower, upper); return res; } static public Interval For(Rational r) { Contract.Requires(!object.Equals(r, null)); Contract.Ensures(Contract.Result<Interval>() != null); return For(r, r); } static public Interval For(Double lower, Double upper, bool dummy) { Contract.Ensures(Contract.Result<Interval>() != null); // We do not cache intervals for doubles return new Interval(lower, upper, dummy); } static public Interval For(Int64 lower, Rational upper) { Contract.Requires((object)upper != null); Contract.Ensures(Contract.Result<Interval>() != null); return For(Rational.For(lower), upper); } static public Interval For(Rational lower, Int64 upper) { Contract.Requires((object)lower != null); Contract.Ensures(Contract.Result<Interval>() != null); return For(lower, Rational.For(upper)); } static public Interval For(Int64 lower, Int64 upper) { Contract.Ensures(Contract.Result<Interval>() != null); return For(Rational.For(lower), Rational.For(upper)); } static public Interval For(UInt32 lower, UInt32 upper) { Contract.Ensures(Contract.Result<Interval>() != null); return For(Rational.For(lower), Rational.For(upper)); } static public Interval For(Int64 i) { Contract.Ensures(Contract.Result<Interval>() != null); var r = Rational.For(i); return For(r, r); } // [SuppressMessage("Microsoft.Contracts", "Ensures-26-45", Justification="We know that getting an interval from a byte always gives a normal interval")] static public Interval For(Byte i) { Contract.Ensures(Contract.Result<Interval>() != null); Contract.Ensures(Contract.Result<Interval>().IsNormal); var r = Rational.For(i); return For(r, r); } static public Interval For(UInt32 i) { Contract.Ensures(Contract.Result<Interval>() != null); var r = Rational.For(i); return For(r, r); } static public Interval For(UInt64 i) { Contract.Ensures(Contract.Result<Interval>() != null); var r = Rational.For(i); return For(r, r); } #endregion #region Constructors private Interval(Int64 lower, Rational upper) : this(Rational.For(lower), upper) { Contract.Requires(((object)upper) != null); } private Interval(Rational lower, Int64 upper) : this(lower, Rational.For(upper)) { Contract.Requires(((object)lower) != null); } private Interval(Int64 lower, Int64 upper) : this(Rational.For(lower), Rational.For(upper)) { } public static string Stats { get { var x = new Pair<int, Pair<Rational, Rational>>[countIntv.Count]; int i = 0; foreach (var pair in countIntv) { Contract.Assert(x.Length == countIntv.Count); // F: we should assume it because we have no way of relating the iteration counter, i and the enumerator for countIntv Contract.Assume(i < x.Length); x[i] = new Pair<int, Pair<Rational, Rational>>(pair.Value, pair.Key); i++; } Array.Sort(x, (k1, k2) => k1.One < k2.One ? 1 : (k1.One == k2.One ? 0 : -1)); StringBuilder res = new StringBuilder(); res.Append("Intervals allocation statistics" + Environment.NewLine); res.AppendFormat("Total allocated intervals: {0}" + Environment.NewLine, x.Length); for (i = 0; i < x.Length; i++) { res.AppendFormat("[{0},{1}] : {2}" + Environment.NewLine, x[i].Two.One, x[i].Two.Two, x[i].One); } return res.ToString(); } } [Conditional("TRACE_PERFORMANCE")] private void UpdateStatistics(Rational lower, Rational upper) { // begin debug int val; if (countIntv.TryGetValue(new Pair<Rational, Rational>(lower, upper), out val)) { val++; } else { val = 1; } countIntv[new Pair<Rational, Rational>(lower, upper)] = val; // end debug } private Interval(Rational lower, Rational upper) : base(lower, upper) { Contract.Requires(!object.Equals(lower, null)); Contract.Requires(!object.Equals(upper, null)); UpdateStatistics(lower, upper); if (lower.IsPlusInfinity && upper.IsPlusInfinity) // the case [+oo, +oo] { this.lowerBound = lower - 1; this.upperBound = upper; } else if (lower.IsMinusInfinity && upper.IsMinusInfinity) // the case [-oo, -oo] { this.lowerBound = lower; this.upperBound = Rational.PlusInfinity; Contract.Assert(!object.Equals(this.lowerBound, null)); Contract.Assert(!object.Equals(this.upperBound, null)); } else { this.lowerBound = lower; this.upperBound = upper; } isBottom = this.lowerBound > this.upperBound; isTop = this.lowerBound.IsMinusInfinity && this.upperBound.IsPlusInfinity; Contract.Assert(!object.Equals(this.lowerBound, null)); Contract.Assert(!object.Equals(this.upperBound, null)); } private Interval(Double inf, Double sup, bool dummy) : base(Rational.MinusInfinity, Rational.PlusInfinity) { if (Double.IsNaN(inf) || Double.IsNaN(sup)) { this.lowerBound = Rational.MinusInfinity; this.upperBound = Rational.PlusInfinity; return; } if (Double.IsNegativeInfinity(inf)) { this.lowerBound = Rational.MinusInfinity; } else { var tmp = (Int64)Math.Floor(inf); // Overflow checking if (OppositeSigns(tmp, inf)) { this.lowerBound = Rational.MinusInfinity; } else { this.lowerBound = Rational.For(tmp); } } if (Double.IsPositiveInfinity(sup)) { this.upperBound = Rational.PlusInfinity; } else { var tmp = (Int64)Math.Ceiling(sup); if (OppositeSigns(tmp, sup)) { this.upperBound = Rational.PlusInfinity; } else { this.upperBound = Rational.For(tmp); } } isBottom = this.lowerBound > this.upperBound; isTop = this.LowerBound.IsMinusInfinity && this.UpperBound.IsPlusInfinity; } private Interval(Rational r) : this(r, r) { Contract.Requires((object)r != null); } private Interval(uint lower, uint upper) : this(Rational.For(lower), Rational.For(upper)) { } /// <summary> /// Useful to check overflows /// </summary> private bool OppositeSigns(long tmp, double inf) { return (tmp < 0 && inf > 0) || (tmp > 0 && inf < 0); } #endregion #region Overridden override public bool IsLowerBoundMinusInfinity { get { return this.LowerBound.IsMinusInfinity; } } override public bool IsUpperBoundPlusInfinity { get { return this.UpperBound.IsPlusInfinity; } } public override bool IsNormal { get { return !this.IsBottom && !this.IsTop; } } public override bool IsInt32 { get { if (this.IsNormal) { try { var blow = this.IsLowerBoundMinusInfinity || this.lowerBound >= Int32.MinValue; var bupp = this.IsUpperBoundPlusInfinity || this.upperBound <= Int32.MaxValue; return blow && bupp; } catch (ArithmeticException) { return false; } } return false; } } public override bool IsInt64 { get { throw new NotImplementedException(); } } #endregion #region Interval Members public bool IsFiniteAndInt64(out Int64 low, out Int64 upp) { if (base.IsFinite && this.LowerBound.IsInteger && this.UpperBound.IsInteger) { try { checked { low = (Int64)this.LowerBound; upp = (Int64)this.UpperBound; } return true; } catch (ArithmeticException) { low = upp = default(Int64); return false; } } low = upp = default(Int64); return false; } public bool IsFiniteAndInt32(out Int32 low, out Int32 upp) { if (base.IsFinite && this.LowerBound.IsInt32 && this.UpperBound.IsInt32) { try { checked { low = (Int32)this.LowerBound; upp = (Int32)this.UpperBound; } return true; } catch (ArithmeticException) { low = upp = default(Int32); return false; } } low = upp = default(Int32); return false; } public bool IsFiniteAndInt32Singleton(out Int32 value) { int low, upp; if (this.IsFiniteAndInt32(out low, out upp) && low == upp) { value = low; return true; } value = -567895; return false; } public bool IsFiniteAndInt64Singleton(out Int64 value) { long low, upp; if (this.IsFiniteAndInt64(out low, out upp) && low == upp) { value = low; return true; } value = -567895; return false; } /// <returns> /// true iff <code>x</code> is not included in this interval /// </returns> public bool DoesNotInclude(int x) { return !this.IsBottom && (x < this.LowerBound || x > this.UpperBound); } public bool DoesInclude(int x) { return this.IsNormal && (this.LowerBound <= x && x <= this.UpperBound); } public bool OverlapsWith(Interval other) { Contract.Requires(other != null); return !this.Meet(other).IsBottom; } public bool OnTheLeftOf(Interval other) { Contract.Requires(other != null); if (!this.IsNormal || !other.IsNormal) { return false; } return this.UpperBound <= other.LowerBound; } #endregion #region Arithmetic operations on Intervals /// <summary> /// The addition of intervals. /// If the evaluation causes an overflow, the top interval is returned /// </summary> /// <returns></returns> static public Interval operator +(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) // Propagate bottom return UnreachedInterval; if (left.IsTop || right.IsTop) // Propagate top return UnknownInterval; Rational lower, upper; if (Rational.TryAdd(left.LowerBound, right.LowerBound, out lower) && Rational.TryAdd(left.UpperBound, right.UpperBound, out upper)) { return Interval.For(lower, upper); } else { return UnknownInterval; } } static public Interval operator -(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) // Propagate bottom return left.Bottom; if (left.IsTop || right.IsTop) // Propagate top return UnknownInterval; Rational lower, upper; if (Rational.TrySub(left.LowerBound, right.UpperBound, out lower) && Rational.TrySub(left.UpperBound, right.LowerBound, out upper)) { return new Interval ( lower.IsPlusInfinity ? Rational.MinusInfinity : lower, upper.IsMinusInfinity ? Rational.PlusInfinity : upper ); } else { return UnknownInterval; } } static public Interval operator -(Interval left) { Contract.Requires(left != null); Contract.Ensures(Contract.Result<Interval>() != null); if (!left.IsNormal) { return left; } else { return Interval.For(-left.UpperBound, -left.LowerBound); } } static public Interval operator *(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) // Propagate bottom return UnreachedInterval; if (left.IsTop || right.IsTop) // Propagate top return UnknownInterval; Rational llrl, lurl, llru, luru; Rational lower, upper; if (Rational.TryMul(left.LowerBound, right.LowerBound, out llrl) && Rational.TryMul(left.UpperBound, right.LowerBound, out lurl) && Rational.TryMul(left.LowerBound, right.UpperBound, out llru) && Rational.TryMul(left.UpperBound, right.UpperBound, out luru)) { lower = Rational.Min(Rational.Min(llrl, lurl), Rational.Min(llru, luru)); upper = Rational.Max(Rational.Max(llrl, lurl), Rational.Max(llru, luru)); return Interval.For(lower, upper); } else { return UnknownInterval; } } static public Interval operator /(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) // Propagate bottom return UnreachedInterval; if (left.IsTop || right.IsTop) // Propagate top return UnknownInterval; Rational llrl, lurl, llru, luru; Rational lower, upper; if (right.LowerBound.IsZero || right.UpperBound.IsZero) { return UnknownInterval; } if (Rational.TryDiv(left.LowerBound, right.LowerBound, out llrl) && Rational.TryDiv(left.UpperBound, right.LowerBound, out lurl) && Rational.TryDiv(left.LowerBound, right.UpperBound, out llru) && Rational.TryDiv(left.UpperBound, right.UpperBound, out luru)) { lower = Rational.Min(Rational.Min(llrl, lurl), Rational.Min(llru, luru)); upper = Rational.Max(Rational.Max(llrl, lurl), Rational.Max(llru, luru)); return Interval.For(lower, upper); } else { return UnknownInterval; } } static public Interval operator %(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) // Propagate bottom return left.Bottom; int leftLow, leftUpp, rightLow, rightUpp; try { // Easy cases if (left.IsFiniteAndInt32(out leftLow, out leftUpp) && right.IsFiniteAndInt32(out rightLow, out rightUpp) && rightLow != 0 && rightUpp != 0) { // k % [a,b] if (leftLow == leftUpp) { var ll = leftLow % rightLow; var lu = leftLow % rightUpp; var ul = leftUpp % rightLow; var uu = leftUpp % rightUpp; var min = Math.Min(Math.Min(ll, lu), Math.Min(ul, uu)); var max = Math.Max(Math.Max(ll, lu), Math.Max(ul, uu)); return Interval.For(min, max); } // [a,b] % [c, d] { var ll = leftLow % rightLow; var lu = leftLow % rightUpp; var ul = leftUpp % rightLow; var uu = leftUpp % rightUpp; // We need to min with 0 and max with (rightUpp-1) because % is no monotonic var min = Math.Min(0, Math.Min(Math.Min(ll, lu), Math.Min(ul, uu))); var max = Math.Max(Math.Max(Math.Max(ll, lu), Math.Max(ul, uu)), rightUpp - 1); return Interval.For(min, max); } } if (right.IsTop) { if (left.LowerBound >= 0) { // We ignore the case when right == 0, this should be proven by some other analysis return Interval.For(0, Rational.PlusInfinity); } else { // Propagate top return UnknownInterval; } } // left % 0 if (right.LowerBound.IsZero && right.UpperBound.IsZero) { return UnknownInterval; } if (!right.UpperBound.IsInfinity) { if (left.IsSingleton && right.IsSingleton) { if (right.LowerBound.IsNotZero && left.LowerBound.IsInteger && right.LowerBound.IsInteger) { Contract.Assume(((Int32)right.LowerBound.PreviousInt32) != 0); return new Interval(Rational.For(((Int32)left.LowerBound) % ((Int32)right.LowerBound.PreviousInt32))); } else { return Interval.UnknownInterval; } } if (right.UpperBound.IsMinusInfinity || right.UpperBound.IsMinValue) { return Interval.UnknownInterval; } var absUpperBound = Rational.Abs(right.UpperBound); if (left.LowerBound >= 0) { return Interval.For(0, absUpperBound - 1); } else if (left.UpperBound <= 0) { return Interval.For(-absUpperBound + 1, 0); } else { return Interval.For(-absUpperBound + 1, absUpperBound - 1); } } else if (right.LowerBound > 0) { if (left.LowerBound >= 0) { return Interval.PositiveInterval; } else { return Interval.For(Rational.MinusInfinity, 0); } } } catch (ArithmeticException) { return UnknownInterval; } return UnknownInterval; } static public Interval operator &(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) { return left.Bottom; } if (right.IsTop) { return right; } long l1, l2, r1, r2; if (left.IsFiniteAndInt64(out l1, out l2) && right.IsFiniteAndInt64(out r1, out r2)) { // Is it a singleton? if (l1 == l2 && r1 == r2) { return new Interval(Rational.For(l1 & r1)); } // If one of the two is non negative, the result will be non-negative if (l1 >= 0 || r1 >= 0) { // if l1 >= 0 && r1 >= 0 && l2 < r1 then the result is zero if (l1 >= 0 && r1 >= 0 && l2 < r1) { return new Interval(0, 0); } return new Interval(0, Math.Min(l2, r2)); } return new Interval(Math.Min(l1, r1), Math.Max(l2, r2)); } if (right.LowerBound >= 0) { if (left.IsTop) { // [-oo, +oo] & [0, r.Upp] return Interval.For(0, right.UpperBound); } if (left.UpperBound < 0) { // [-oo, a] & [0, r.Upp] return Interval.For(0, right.UpperBound); } if (left.LowerBound >= 0) { // [0 <= a, +oo] & [0, r.Upp] return Interval.For(0, right.UpperBound); } return Interval.PositiveInterval; } if (left.LowerBound >= 0) { if (right.IsTop) { // [0, r.Upp] & [-oo, +oo] return Interval.For(0, left.UpperBound); } if (right.UpperBound < 0) { // [0, r.Upp] & [-oo, a] return Interval.For(0, left.UpperBound); } if (right.LowerBound >= 0) { // [0, r.Upp] & [0 <= a, +oo] return Interval.For(0, left.UpperBound); } return Interval.PositiveInterval; } return UnknownInterval; } static public Interval operator |(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) { return UnreachedInterval; } if (left.IsTop || right.IsTop) { return UnknownInterval; } Interval posInterval; Rational k; if (left.LowerBound.IsInteger && left.UpperBound.IsInteger && right.LowerBound.IsInteger && right.UpperBound.IsInteger) { if (left.LowerBound >= 0 && right.LowerBound >= 0 && !left.UpperBound.IsInfinity && !right.UpperBound.IsInfinity) { // F: Assumptions below follow form the Contract.Assert(left.LowerBound.IsInteger); Contract.Assert(left.UpperBound.IsInteger); Contract.Assert(right.LowerBound.IsInteger); Contract.Assert(right.UpperBound.IsInteger); uint min, max; WarrenAlgorithmForBitewiseOr(ToUint(left.LowerBound), ToUint(left.UpperBound), ToUint(right.LowerBound), ToUint(right.UpperBound), out min, out max); return Interval.For(min, max); } else if (MatchWithPositiveAndConstant(left, right, out posInterval, out k)) { if (k > 0) {// we have ([k1, +oo] | k2) >= max(k1, k2) return Interval.For(Rational.Max(posInterval.LowerBound, k), Rational.PlusInfinity); } else if (k < 0) { return Interval.For(k, Rational.PlusInfinity); } else { return posInterval; } } } return UnknownInterval; } static public Interval operator ^(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) { return UnreachedInterval; } if (left.IsTop || right.IsTop) { return UnknownInterval; } long leftVal, rightVal; if (left.IsFiniteAndInt64Singleton(out leftVal) && right.IsFiniteAndInt64Singleton(out rightVal)) { var result = leftVal ^ rightVal; return new Interval(Rational.For(result)); } return UnknownInterval; } static public Interval ShiftLeft(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) { return UnreachedInterval; } if (left.IsTop || right.IsTop) { return UnknownInterval; } Rational valForRight; if (right.TryGetSingletonValue(out valForRight)) { if (valForRight > 32 || !valForRight.IsInteger) { // According to the ECMA standard, Partition III pag. 92 return UnknownInterval; } else { // It is a multiplication by 2^(valForRight) double d = Math.Ceiling(Math.Pow(2, (double)valForRight.NextInt32)); // We know it will not raise an exception... int pow = (int)d; return left * (Interval.For(pow)); } } else { return UnknownInterval; } } static public Interval ShiftRight(Interval left, Interval right) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(Contract.Result<Interval>() != null); if (left.IsBottom || right.IsBottom) { return left.Bottom; } if (left.IsTop || right.IsTop) { return UnknownInterval; } if (left.LowerBound >= 0) { if (left.IsFinite && right.IsFinite) { var low = ((Int64)left.LowerBound.PreviousInt64) >> (Int32)right.UpperBound.NextInt32; var upp = ((Int64)left.UpperBound.NextInt64) >> (Int32)right.LowerBound.PreviousInt32; return Interval.For(low, upp); } Rational v; if (right.TryGetSingletonValue(out v) && v.IsInteger) { Rational sq; try { var value = (int)v; Contract.Assume(value >= 0); sq = Rational.ToThePowerOfTwo(value); } catch (ArithmeticExceptionRational) { return UnknownInterval; } if (sq <= 0) { return UnknownInterval; } try { var newLower = left.LowerBound / sq; var newUpper = left.UpperBound / sq; return Interval.For(newLower, newUpper); } catch (ArithmeticExceptionRational) { return UnknownInterval; } } return PositiveInterval; } return UnknownInterval; } #endregion #region Arithmetic operations onRationals and Intervals public static Interval operator +(Rational r, Interval i) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); if (i.IsTop || i.IsBottom) return i; try { return Interval.For(r + i.LowerBound, r + i.UpperBound); } catch (ArithmeticExceptionRational) { return Interval.UnknownInterval; } } public static Interval operator +(Interval i, Rational r) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); return r + i; } public static Interval operator -(Rational r, Interval i) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); if (i.IsTop || i.IsBottom) return i; try { return Interval.For(r - i.UpperBound, r - i.LowerBound); } catch (ArithmeticExceptionRational) { return Interval.UnknownInterval; } } public static Interval operator *(Rational r, Interval i) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); if (i.IsTop || i.IsBottom) return i; if (r.IsZero) return Interval.For(0); if (r.Sign < 0) { return Interval.For( Rational.MultiplyWithDefault(r, i.UpperBound, Rational.MinusInfinity), Rational.MultiplyWithDefault(r, i.LowerBound, Rational.PlusInfinity)); } else { return Interval.For( Rational.MultiplyWithDefault(r, i.LowerBound, Rational.MinusInfinity), Rational.MultiplyWithDefault(r, i.UpperBound, Rational.PlusInfinity)); } } public static Interval operator *(Interval i, Rational r) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); return r * i; } public static Interval operator /(Interval i, Rational r) { Contract.Requires(i != null); Contract.Requires((object)r != null); Contract.Ensures(Contract.Result<Interval>() != null); if (i.IsTop || i.IsBottom) return i; if (r.IsZero) return Interval.UnknownInterval; if (r.Sign < 0) { return Interval.For( Rational.DivideWithDefault(i.UpperBound, r, Rational.MinusInfinity), Rational.DivideWithDefault(i.LowerBound, r, Rational.PlusInfinity)); } else { return Interval.For( Rational.DivideWithDefault(i.LowerBound, r, Rational.MinusInfinity), Rational.DivideWithDefault(i.UpperBound, r, Rational.PlusInfinity)); } } #endregion #region Conversion public DisInterval AsDisInterval { get { Contract.Ensures(Contract.Result<DisInterval>() != null); return DisInterval.For(this); } } public override Interval ToUnsigned() { int val; if (this.IsFiniteAndInt32Singleton(out val)) { if (val >= 0) { return this; } else { return Interval.For((uint)val); } } else { return ApplyConversion(ExpressionOperator.ConvertToUInt32, this); } } public Interval ApplyConversion(ExpressionOperator conversionType) { return ApplyConversion(conversionType, this); } static public Interval ApplyConversion(ExpressionOperator conversionType, Interval val) { Contract.Requires(val != null); Contract.Ensures(Contract.Result<Interval>() != null); if (val.IsBottom) { return val; } switch (conversionType) { case ExpressionOperator.ConvertToInt8: { return val.RefineIntervalWithTypeRanges(SByte.MinValue, SByte.MaxValue); } case ExpressionOperator.ConvertToInt16: { return val.RefineIntervalWithTypeRanges(Int16.MinValue, Int16.MaxValue); } case ExpressionOperator.ConvertToInt32: { return val.RefineIntervalWithTypeRanges(Int32.MinValue, Int32.MaxValue); } case ExpressionOperator.ConvertToInt64: { return val.RefineIntervalWithTypeRanges(Int64.MinValue, Int64.MaxValue); } case ExpressionOperator.ConvertToUInt8: { return val.RefineIntervalWithTypeRanges(Byte.MinValue, Byte.MaxValue); } case ExpressionOperator.ConvertToUInt16: { return val.RefineIntervalWithTypeRanges(UInt16.MinValue, UInt16.MaxValue); } case ExpressionOperator.ConvertToUInt32: { if (val.IsSingleton && val.LowerBound.IsInteger) { if (val.LowerBound < Int32.MinValue || val.UpperBound > Int32.MaxValue) { return val; } else { var asInt = (Int32)val.LowerBound; var asUint = (UInt32)(Int32)val.LowerBound; if (asUint < Int32.MaxValue) { return Interval.For((int)asUint); } else { return Interval.For(asUint); } } } else { if (val.LowerBound >= 0) { // (UInt32)[a, b], con a >= 0 return val; } else { return new Interval(0, (long)UInt32.MaxValue); } } } case ExpressionOperator.ConvertToUInt64: // TODO case ExpressionOperator.ConvertToFloat32: case ExpressionOperator.ConvertToFloat64: default: return val; } } public Interval RefineIntervalWithTypeRanges(Int32 min, Int32 max) { var low = this.LowerBound.IsInfinity || !this.LowerBound.IsInRange(min, max) ? Rational.MinusInfinity : this.LowerBound.PreviousInt32; var upp = this.UpperBound.IsInfinity || !this.UpperBound.IsInRange(min, max) ? Rational.PlusInfinity : this.UpperBound.NextInt32; return Interval.For(low, upp); } public Interval RefineIntervalWithTypeRanges(Int64 min, Int64 max) { var low = this.LowerBound.IsInfinity || !this.LowerBound.IsInRange(min, max) ? Rational.MinusInfinity : this.LowerBound.PreviousInt64; var upp = this.UpperBound.IsInfinity || !this.UpperBound.IsInRange(min, max) ? Rational.PlusInfinity : this.UpperBound.NextInt64; return Interval.For(low, upp); } public Interval RefineIntervalWithTypeRanges(UInt32 min, UInt32 max) { var low = this.LowerBound.IsInfinity || !this.LowerBound.IsInRange(min, max) ? Rational.MinusInfinity : this.LowerBound.PreviousInt32; var upp = this.UpperBound.IsInfinity || !this.UpperBound.IsInRange(min, max) ? Rational.PlusInfinity : this.UpperBound.NextInt32; return Interval.For(low, upp); } #endregion #region IAbstractDomain Members override public bool IsBottom { get { return isBottom; // return this.lowerBound > this.upperBound; } } override public bool IsTop { get { return isTop; //return this.upperBound.IsPlusInfinity && this.lowerBound.IsMinusInfinity; } } public override Interval Bottom { get { return UnreachedInterval; } } public override Interval Top { get { return UnknownInterval; } } [Pure] override public bool LessEqual(Interval right) { bool result; if (AbstractDomainsHelper.TryTrivialLessEqual(this, right, out result)) { return result; } return this.LowerBound >= right.LowerBound && this.UpperBound <= right.UpperBound; } [Pure] public bool LessEqual(ReadOnlyIntervalList right) { Contract.Requires(right != null); foreach (var intv in right) { Contract.Assume(intv != null); if (this.LessEqual(intv)) { return true; } } return false; } [Pure] override public Interval/*!*/ Join(Interval/*!*/ right) { Interval/*!*/ result; if (AbstractDomainsHelper.TryTrivialJoin(this, right, out result)) { return result; } var joinInf = Rational.Min(this.LowerBound, right.LowerBound); var joinSup = Rational.Max(this.UpperBound, right.UpperBound); return Interval.For(joinInf, joinSup); } [Pure] override public Interval/*!*/ Meet(Interval/*!*/ right) { Interval trivialMeet; if (AbstractDomainsHelper.TryTrivialMeet(this, right, out trivialMeet)) { return trivialMeet; } var meetInf = Rational.Max(this.LowerBound, right.LowerBound); var meetSup = Rational.Min(this.UpperBound, right.UpperBound); return Interval.For(meetInf, meetSup); } [Pure] override public Interval/*!*/ Widening(Interval/*!*/ prev) { // Trivial cases if (this.IsBottom) return prev; if (this.IsTop) return this; if (prev.IsBottom) return this; if (prev.IsTop) return prev; var wideningInf = this.LowerBound < prev.LowerBound ? ThresholdDB.GetPrevious(this.LowerBound) : prev.LowerBound; Contract.Assert(((object)wideningInf) != null); var wideningSup = this.UpperBound > prev.UpperBound ? ThresholdDB.GetNext(this.upperBound) : prev.UpperBound; Contract.Assert(((object)wideningSup) != null); return Interval.For(wideningInf, wideningSup); } #endregion #region ICloneable Members public override Interval DuplicateMe() { return Interval.For(this.lowerBound, this.upperBound); } #endregion #region Overridden (To, ToString, GetHash, Equals) public override T To<T>(IFactory<T> factory) { T varName; if (this.IsBottom) { return factory.Constant(false); } else if (this.IsTop) { return factory.Constant(true); } else if (factory.TryGetName(out varName)) { T low = default(T), upp = default(T); bool lowSet = false, uppSet = false; if (this.lowerBound.IsInteger) { low = factory.LessEqualThan(this.lowerBound.To(factory), varName); lowSet = true; } if (this.upperBound.IsInteger) { upp = factory.LessEqualThan(varName, this.upperBound.To(factory)); uppSet = true; } if (lowSet && uppSet) { return factory.And(low, upp); } return lowSet ? low : upp; } return factory.Constant(true); } public override int GetHashCode() { return (Int32)(this.lowerBound + this.upperBound); } [Pure] public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) { return true; } var asIntv = obj as Interval; if (asIntv == null) { return false; } Contract.Assume(((object)asIntv.upperBound) != null); Contract.Assume(((object)asIntv.lowerBound) != null); return this.upperBound == asIntv.upperBound && this.lowerBound == asIntv.lowerBound; } #endregion #region Utils static public bool AreConsecutiveIntegers(Interval prev, Interval next) { Contract.Requires(prev != null); Contract.Requires(next != null); if (!prev.IsNormal || !next.IsNormal) { return false; } return prev.UpperBound.IsInteger && next.LowerBound.IsInteger && prev.UpperBound + 1 == next.LowerBound; } #endregion #region Private, helper methods [Pure] static private uint ToUint(Rational r) { Contract.Requires(!object.ReferenceEquals(r, null)); Contract.Requires(r.IsInteger); return (uint)((int)r); } static private bool MatchWithPositiveAndConstant(Interval left, Interval right, out Interval posInterval, out Rational k) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out posInterval) != null); Contract.Ensures(!Contract.Result<bool>() || !object.Equals(Contract.ValueAtReturn(out k), null)); bool result; if (left.LowerBound >= 0 && right.IsSingleton) { posInterval = left; k = right.LowerBound; result = true; } else if (right.LowerBound >= 0 && left.IsSingleton) { posInterval = right; k = left.LowerBound; result = true; } else { posInterval = null; k = default(Rational); result = false; } return result; } private static bool IsPowerOfTwoMinusOne(Rational r) { Contract.Requires((object)r != null); return r == 15 || r == 31 || r == 63 || r == 127 || r == 255 || r == 511 || r == 1023 || r == 2047 || r == 4095 || r == 8191 || r == 16385 || r == 32767 || r == 65535 || r == 131071 || r == 262143 || r == 524287 || r == 1048575 || r == 2097151 || r == 4194303 || r == 8388607 || r == 16777215; } /// <summary> /// The Warren algorithm to find the min and max of two intervals. /// Given <code> a \leq x \leq b</code> and <code>c \leq y \leq d</code>, it finds the <code>min</code> and <code>max</code> of <code>x | y</code> /// </summary> static private void WarrenAlgorithmForBitewiseOr(uint a, uint b, uint c, uint d, out uint min, out uint max) { min = MinOr(a, b, c, d); max = MaxOr(a, b, c, d); } static private uint MinOr(uint a, uint b, uint c, uint d) { uint m, tmp; m = 0x80000000; while (m != 0) { if ((~a & c & m) != 0) { tmp = (a | m) & ~m; if (tmp <= b) { a = tmp; break; } } else if ((a & ~c & m) != 0) { tmp = (c | m) & ~m; if (tmp <= d) { c = tmp; break; } } m = m >> 1; } return a | c; } static private uint MaxOr(uint a, uint b, uint c, uint d) { uint m, tmp; m = 0x80000000; while (m != 0) { if ((b & d & m) != 0) { tmp = (b - m) | (m - 1); if (tmp >= a) { b = tmp; break; } tmp = (d - m) | (m - 1); if (tmp >= c) { d = tmp; break; } } m = m >> 1; } return b | d; } #endregion #region Ranges for basic types static public class Ranges { private static readonly Interval uint8Range = Interval.For(Byte.MinValue, Byte.MaxValue); private static readonly Interval uint16Range = Interval.For(UInt16.MinValue, UInt16.MaxValue); private static readonly Interval uint32Range = Interval.For(UInt32.MinValue, UInt32.MaxValue); private static readonly Interval uint64Range = Interval.For(0, Rational.PlusInfinity); private static readonly Interval int8Range = Interval.For(SByte.MinValue, SByte.MaxValue); private static readonly Interval int16Range = Interval.For(Int16.MinValue, Int16.MaxValue); private static readonly Interval int32Range = Interval.For(Int32.MinValue, Int32.MaxValue); private static readonly Interval int64Range = Interval.For(Int64.MinValue, Int64.MaxValue); public static Interval UInt8Range { get { return uint8Range; } } public static Interval UInt16Range { get { return uint16Range; } } public static Interval UInt32Range { get { return uint32Range; } } public static Interval UInt64Range { get { return uint64Range; } } public static Interval Int8Range { get { return int8Range; } } public static Interval Int16Range { get { return int16Range; } } public static Interval Int32Range { get { return int32Range; } } public static Interval Int64Range { get { return int64Range; } } public static Interval EnumRange<Type>(Type t, Func<Type, List<int>> enumranges) { Contract.Requires(enumranges != null); Contract.Ensures(Contract.Result<Interval>() != null); var ranges = enumranges(t); if (ranges != null) { var min = Int32.MaxValue; var max = Int32.MinValue; foreach (var x in ranges) { if (x < min) { min = x; } if (x > max) { max = x; } } if (min <= max) { return Interval.For(min, max); } } return Ranges.Int32Range; } } #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 Xunit; namespace System.IO.Tests { public class File_Create_str : FileSystemTest { public virtual FileStream Create(string path) { return File.Create(path); } #region UniversalTests [Fact] public void NullPath() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyPath() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void NonExistentPath() { Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); } [Fact] public void CreateCurrentDirectory() { Assert.Throws<UnauthorizedAccessException>(() => Create(".")); } [Fact] public void ValidCreation() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix public void ValidCreation_ExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix, long path public void ValidCreation_LongPathExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500)); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] public void CreateInParentDirectory() { string testFile = GetTestFileName(); using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile))) { Assert.True(File.Exists(Path.Combine(TestDirectory, testFile))); } } [Fact] public void LegalSymbols() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&"); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); } } [Fact] public void InvalidDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName()); Assert.Throws<DirectoryNotFoundException>(() => Create(testFile)); } [Fact] public void FileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Throws<IOException>(() => Create(testFile)); } } [Fact] public void FileAlreadyExists() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void OverwriteReadOnly() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void LongPathSegment() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); // Long path should throw PathTooLongException on Desktop and IOException // elsewhere. if (PlatformDetection.IsFullFramework) { Assert.Throws<PathTooLongException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } else { AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException, PathTooLongException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void LongDirectoryName() { // 255 = NAME_MAX on Linux and macOS DirectoryInfo path = Directory.CreateDirectory(Path.Combine(GetTestFilePath(), new string('a', 255))); Assert.True(Directory.Exists(path.FullName)); Directory.Delete(path.FullName); Assert.False(Directory.Exists(path.FullName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void LongFileName() { // 255 = NAME_MAX on Linux and macOS var dir = GetTestFilePath(); Directory.CreateDirectory(dir); var path = Path.Combine(dir, new string('b', 255)); File.Create(path).Dispose(); Assert.True(File.Exists(path)); File.Delete(path); Assert.False(File.Exists(path)); } [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) using (File.Create(testFile + "aAAa")) { Assert.False(File.Exists(testFile + "AaAa")); Assert.True(File.Exists(testFile + "AAAA")); Assert.True(File.Exists(testFile + "aAAa")); Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length); } Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void CaseInsensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); File.Create(testFile + "AAAA").Dispose(); File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose(); Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public void WindowsWildCharacterPath_Desktop() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3)))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t"))); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void WindowsWildCharacterPath_Core() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3)))); Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "*"))); Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "Test*t"))); Assert.ThrowsAny<IOException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t"))); } [Theory, InlineData(" "), InlineData(""), InlineData("\0"), InlineData(" ")] [PlatformSpecific(TestPlatforms.Windows)] public void WindowsEmptyPath(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Theory, InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\t")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public void WindowsInvalidPath_Desktop(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Theory, InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\t")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void WindowsInvalidPath_Core(string path) { Assert.ThrowsAny<IOException>(() => Create(Path.Combine(TestDirectory, path))); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void CreateNullThrows_Unix() { Assert.Throws<ArgumentException>(() => Create("\0")); } [Theory, InlineData(" "), InlineData(" "), InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\t")] [PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix public void UnixWhitespacePath(string path) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (Create(Path.Combine(testDir.FullName, path))) { Assert.True(File.Exists(Path.Combine(testDir.FullName, path))); } } [Theory, InlineData(":bar"), InlineData(":bar:$DATA"), InlineData("::$DATA")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void WindowsAlternateDataStream(string streamName) { DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath()); streamName = Path.Combine(testDirectory.FullName, GetTestFileName()) + streamName; using (Create(streamName)) { Assert.True(File.Exists(streamName)); } } [Theory, InlineData(":bar"), InlineData(":bar:$DATA")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void WindowsAlternateDataStream_OnExisting(string streamName) { DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath()); // On closed file string fileName = Path.Combine(testDirectory.FullName, GetTestFileName()); Create(fileName).Dispose(); streamName = fileName + streamName; using (Create(streamName)) { Assert.True(File.Exists(streamName)); } // On open file fileName = Path.Combine(testDirectory.FullName, GetTestFileName()); using (Create(fileName)) using (Create(streamName)) { Assert.True(File.Exists(streamName)); } } #endregion } public class File_Create_str_i : File_Create_str { public override FileStream Create(string path) { return File.Create(path, 4096); // Default buffer size } public virtual FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize); } [Fact] public void NegativeBuffer() { Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100)); } } public class File_Create_str_i_fo : File_Create_str_i { public override FileStream Create(string path) { return File.Create(path, 4096, FileOptions.Asynchronous); } public override FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize, FileOptions.Asynchronous); } } }
// 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.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime; namespace System.Runtime { public enum RhFailFastReason { Unknown = 0, InternalError = 1, // "Runtime internal error" UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope." UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method." ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object." IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code." PN_UnhandledException = 6, // ProjectN: "unhandled exception" PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition." Max } // Keep this synchronized with the duplicate definition in DebugEventSource.cpp [Flags] internal enum ExceptionEventKind { Thrown = 1, CatchHandlerFound = 2, Unhandled = 4, FirstPassFrameEntered = 8 } internal static unsafe class DebuggerNotify { // We cache the events a debugger is interested on the C# side to avoid p/invokes when the // debugger isn't attached. // // Ideally we would like the managed debugger to start toggling this directly so that // it stays perfectly up-to-date. However as a reasonable approximation we fetch // the value from native code at the beginning of each exception dispatch. If the debugger // attempts to enroll in more events mid-exception handling we aren't going to see it. private static ExceptionEventKind s_cachedEventMask; internal static void BeginFirstPass(object exceptionObj, byte* faultingIP, UIntPtr faultingFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.Thrown) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Thrown, faultingIP, faultingFrameSP); } internal static void FirstPassFrameEntered(object exceptionObj, byte* enteredFrameIP, UIntPtr enteredFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.FirstPassFrameEntered) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.FirstPassFrameEntered, enteredFrameIP, enteredFrameSP); } internal static void EndFirstPass(object exceptionObj, byte* handlerIP, UIntPtr handlingFrameSP) { if (handlerIP == null) { if ((s_cachedEventMask & ExceptionEventKind.Unhandled) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Unhandled, null, UIntPtr.Zero); } else { if ((s_cachedEventMask & ExceptionEventKind.CatchHandlerFound) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.CatchHandlerFound, handlerIP, handlingFrameSP); } } internal static void BeginSecondPass() { //desktop debugging has an unwind begin event, however it appears that is unneeded for now, and possibly // will never be needed? } } internal static unsafe class EH { internal static UIntPtr MaxSP { get { return (UIntPtr)(void*)(-1); } } private enum RhEHClauseKind { RH_EH_CLAUSE_TYPED = 0, RH_EH_CLAUSE_FAULT = 1, RH_EH_CLAUSE_FILTER = 2, RH_EH_CLAUSE_UNUSED = 3, } private struct RhEHClause { internal RhEHClauseKind _clauseKind; internal uint _tryStartOffset; internal uint _tryEndOffset; internal byte* _filterAddress; internal byte* _handlerAddress; internal void* _pTargetType; ///<summary> /// We expect the stackwalker to adjust return addresses to point at 'return address - 1' so that we /// can use an interval here that is closed at the start and open at the end. When a hardware fault /// occurs, the IP is pointing at the start of the instruction and will not be adjusted by the /// stackwalker. Therefore, it will naturally work with an interval that has a closed start and open /// end. ///</summary> public bool ContainsCodeOffset(uint codeOffset) { return ((codeOffset >= _tryStartOffset) && (codeOffset < _tryEndOffset)); } } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__EHEnum)] private struct EHEnum { [FieldOffset(0)] private IntPtr _dummy; // For alignment } // This is a fail-fast function used by the runtime as a last resort that will terminate the process with // as little effort as possible. No guarantee is made about the semantics of this fail-fast. internal static void FallbackFailFast(RhFailFastReason reason, object unhandledException) { InternalCalls.RhpFallbackFailFast(); } // Constants used with RhpGetClasslibFunction, to indicate which classlib function // we are interested in. // Note: make sure you change the def in EHHelpers.cpp if you change this! internal enum ClassLibFunctionId { GetRuntimeException = 0, FailFast = 1, // UnhandledExceptionHandler = 2, // unused AppendExceptionStackFrame = 3, CheckStaticClassConstruction = 4, GetSystemArrayEEType = 5, } // Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast // function and invoke it. Any failure to find and invoke the function, or if it returns, results in // MRT-defined fail-fast behavior. internal static void FailFastViaClasslib(RhFailFastReason reason, object unhandledException, IntPtr classlibAddress) { // Find the classlib function that will fail fast. This is a RuntimeExport function from the // classlib module, and is therefore managed-callable. IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { // The classlib didn't provide a function, so we fail our way... FallbackFailFast(reason, unhandledException); } try { // Invoke the classlib fail fast function. CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, IntPtr.Zero, IntPtr.Zero); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's function should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } #if AMD64 [StructLayout(LayoutKind.Explicit, Size = 0x4d0)] #elif ARM [StructLayout(LayoutKind.Explicit, Size=0x1a0)] #elif X86 [StructLayout(LayoutKind.Explicit, Size=0x2cc)] #else [StructLayout(LayoutKind.Explicit, Size = 0x10)] // this is small enough that it should trip an assert in RhpCopyContextFromExInfo #endif private struct OSCONTEXT { } internal static unsafe void* PointerAlign(void* ptr, int alignmentInBytes) { int alignMask = alignmentInBytes - 1; #if BIT64 return (void*)((((long)ptr) + alignMask) & ~alignMask); #else return (void*)((((int)ptr) + alignMask) & ~alignMask); #endif } [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe void UnhandledExceptionFailFastViaClasslib( RhFailFastReason reason, object unhandledException, IntPtr classlibAddress, ref ExInfo exInfo) { IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { FailFastViaClasslib( reason, unhandledException, classlibAddress); } // 16-byte align the context. This is overkill on x86 and ARM, but simplifies things slightly. const int contextAlignment = 16; byte* pbBuffer = stackalloc byte[sizeof(OSCONTEXT) + contextAlignment]; void* pContext = PointerAlign(pbBuffer, contextAlignment); InternalCalls.RhpCopyContextFromExInfo(pContext, sizeof(OSCONTEXT), exInfo._pExContext); try { CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, exInfo._pExContext->IP, (IntPtr)pContext); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's funciton should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } private enum RhEHFrameType { RH_EH_FIRST_FRAME = 1, RH_EH_FIRST_RETHROW_FRAME = 2, } private static void AppendExceptionStackFrameViaClasslib(object exception, IntPtr IP, ref bool isFirstRethrowFrame, ref bool isFirstFrame) { IntPtr pAppendStackFrame = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(IP, ClassLibFunctionId.AppendExceptionStackFrame); if (pAppendStackFrame != IntPtr.Zero) { int flags = (isFirstFrame ? (int)RhEHFrameType.RH_EH_FIRST_FRAME : 0) | (isFirstRethrowFrame ? (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME : 0); try { CalliIntrinsics.CallVoid(pAppendStackFrame, exception, IP, flags); } catch { // disallow all exceptions leaking out of callbacks } // Clear flags only if we called the function isFirstRethrowFrame = false; isFirstFrame = false; } } // Given an ExceptionID and an address pointing somewhere into a managed module, get // an exception object of a type that the module containing the given address will understand. // This finds the classlib-defined GetRuntimeException function and asks it for the exception object. internal static Exception GetClasslibException(ExceptionIDs id, IntPtr address) { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. IntPtr pGetRuntimeExceptionFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(address, ClassLibFunctionId.GetRuntimeException); // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, address); } return e; } // Given an ExceptionID and an EEtype address, get an exception object of a type that the module containing // the given address will understand. This finds the classlib-defined GetRuntimeException function and asks // it for the exception object. internal static Exception GetClasslibExceptionFromEEType(ExceptionIDs id, IntPtr pEEType) { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. IntPtr pGetRuntimeExceptionFunction = IntPtr.Zero; if (pEEType != IntPtr.Zero) { pGetRuntimeExceptionFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromEEtype(pEEType, ClassLibFunctionId.GetRuntimeException); } // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, pEEType); } return e; } // RhExceptionHandling_ functions are used to throw exceptions out of our asm helpers. We tail-call from // the asm helpers to these functions, which performs the throw. The tail-call is important: it ensures that // the stack is crawlable from within these functions. [RuntimeExport("RhExceptionHandling_ThrowClasslibOverflowException")] public static void ThrowClasslibOverflowException(IntPtr address) { // Throw the overflow exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.Overflow, address); } [RuntimeExport("RhExceptionHandling_ThrowClasslibDivideByZeroException")] public static void ThrowClasslibDivideByZeroException(IntPtr address) { // Throw the divide by zero exception defined by the classlib, using the return address of the asm helper // to find the correct classlib. throw GetClasslibException(ExceptionIDs.DivideByZero, address); } [RuntimeExport("RhExceptionHandling_FailedAllocation")] public static void FailedAllocation(EETypePtr pEEType, bool fIsOverflow) { ExceptionIDs exID = fIsOverflow ? ExceptionIDs.Overflow : ExceptionIDs.OutOfMemory; // Throw the out of memory exception defined by the classlib, using the input EEType* // to find the correct classlib. throw pEEType.ToPointer()->GetClasslibException(exID); } #if !INPLACE_RUNTIME private static OutOfMemoryException s_theOOMException = new OutOfMemoryException(); // MRT exports GetRuntimeException for the few cases where we have a helper that throws an exception // and may be called by either MRT or other classlibs and that helper needs to throw an exception. // There are only a few cases where this happens now (the fast allocation helpers), so we limit the // exception types that MRT will return. [RuntimeExport("GetRuntimeException")] public static Exception GetRuntimeException(ExceptionIDs id) { switch (id) { case ExceptionIDs.OutOfMemory: // Throw a preallocated exception to avoid infinite recursion. return s_theOOMException; case ExceptionIDs.Overflow: return new OverflowException(); case ExceptionIDs.InvalidCast: return new InvalidCastException(); default: Debug.Assert(false, "unexpected ExceptionID"); FallbackFailFast(RhFailFastReason.InternalError, null); return null; } } #endif private enum HwExceptionCode : uint { STATUS_REDHAWK_NULL_REFERENCE = 0x00000000u, STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE = 0x00000042u, STATUS_DATATYPE_MISALIGNMENT = 0x80000002u, STATUS_ACCESS_VIOLATION = 0xC0000005u, STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094u, STATUS_INTEGER_OVERFLOW = 0xC0000095u, } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__PAL_LIMITED_CONTEXT)] public struct PAL_LIMITED_CONTEXT { [FieldOffset(AsmOffsets.OFFSETOF__PAL_LIMITED_CONTEXT__IP)] internal IntPtr IP; // the rest of the struct is left unspecified. } // N.B. -- These values are burned into the throw helper assembly code and are also known the the // StackFrameIterator code. [Flags] internal enum ExKind : byte { None = 0, Throw = 1, HardwareFault = 2, KindMask = 3, RethrowFlag = 4, SupersededFlag = 8, InstructionFaultFlag = 0x10 } [StackOnly] [StructLayout(LayoutKind.Explicit)] public struct ExInfo { internal void Init(object exceptionObj, bool instructionFault = false) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _kind -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; if (instructionFault) _kind |= ExKind.InstructionFaultFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal void Init(object exceptionObj, ref ExInfo rethrownExInfo) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _kind = rethrownExInfo._kind | ExKind.RethrowFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal object ThrownException { get { return _exception; } } [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pPrevExInfo)] internal void* _pPrevExInfo; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pExContext)] internal PAL_LIMITED_CONTEXT* _pExContext; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_exception)] private object _exception; // actual object reference, specially reported by GcScanRootsWorker [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_kind)] internal ExKind _kind; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_passNumber)] internal byte _passNumber; // BEWARE: This field is used by the stackwalker to know if the dispatch code has reached the // point at which a handler is called. In other words, it serves as an "is a handler // active" state where '_idxCurClause == MaxTryRegionIdx' means 'no'. [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_idxCurClause)] internal uint _idxCurClause; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_frameIter)] internal StackFrameIterator _frameIter; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_notifyDebuggerSP)] volatile internal UIntPtr _notifyDebuggerSP; } // // Called by RhpThrowHwEx // [RuntimeExport("RhThrowHwEx")] public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); IntPtr faultingCodeAddress = exInfo._pExContext->IP; bool instructionFault = true; ExceptionIDs exceptionId; switch (exceptionCode) { case (uint)HwExceptionCode.STATUS_REDHAWK_NULL_REFERENCE: exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE: // The write barrier where the actual fault happened has been unwound already. // The IP of this fault needs to be treated as return address, not as IP of // faulting instruction. instructionFault = false; exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_DATATYPE_MISALIGNMENT: exceptionId = ExceptionIDs.DataMisaligned; break; // N.B. -- AVs that have a read/write address lower than 64k are already transformed to // HwExceptionCode.REDHAWK_NULL_REFERENCE prior to calling this routine. case (uint)HwExceptionCode.STATUS_ACCESS_VIOLATION: exceptionId = ExceptionIDs.AccessViolation; break; case (uint)HwExceptionCode.STATUS_INTEGER_DIVIDE_BY_ZERO: exceptionId = ExceptionIDs.DivideByZero; break; case (uint)HwExceptionCode.STATUS_INTEGER_OVERFLOW: exceptionId = ExceptionIDs.Overflow; break; default: // We don't wrap SEH exceptions from foreign code like CLR does, so we believe that we // know the complete set of HW faults generated by managed code and do not need to handle // this case. FailFastViaClasslib(RhFailFastReason.InternalError, null, faultingCodeAddress); exceptionId = ExceptionIDs.NullReference; break; } Exception exceptionToThrow = GetClasslibException(exceptionId, faultingCodeAddress); exInfo.Init(exceptionToThrow, instructionFault); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } private const uint MaxTryRegionIdx = 0xFFFFFFFFu; [RuntimeExport("RhThrowEx")] public static void RhThrowEx(object exceptionObj, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // Transform attempted throws of null to a throw of NullReferenceException. if (exceptionObj == null) { IntPtr faultingCodeAddress = exInfo._pExContext->IP; exceptionObj = GetClasslibException(ExceptionIDs.NullReference, faultingCodeAddress); } exInfo.Init(exceptionObj); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); FallbackFailFast(RhFailFastReason.InternalError, null); } [RuntimeExport("RhRethrow")] public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // We need to copy the exception object to this stack location because collided unwinds // will cause the original stack location to go dead. object rethrownException = activeExInfo.ThrownException; exInfo.Init(rethrownException, ref activeExInfo); DispatchEx(ref exInfo._frameIter, ref exInfo, activeExInfo._idxCurClause); FallbackFailFast(RhFailFastReason.InternalError, null); } private static void DispatchEx(ref StackFrameIterator frameIter, ref ExInfo exInfo, uint startIdx) { Debug.Assert(exInfo._passNumber == 1, "expected asm throw routine to set the pass"); object exceptionObj = exInfo.ThrownException; // ------------------------------------------------ // // First pass // // ------------------------------------------------ UIntPtr handlingFrameSP = MaxSP; byte* pCatchHandler = null; uint catchingTryRegionIdx = MaxTryRegionIdx; bool isFirstRethrowFrame = (startIdx != MaxTryRegionIdx); bool isFirstFrame = true; byte* prevControlPC = null; UIntPtr prevFramePtr = UIntPtr.Zero; bool unwoundReversePInvoke = false; bool isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0); Debug.Assert(isValid, "RhThrowEx called with an unexpected context"); DebuggerNotify.BeginFirstPass(exceptionObj, frameIter.ControlPC, frameIter.SP); for (; isValid; isValid = frameIter.Next(out startIdx, out unwoundReversePInvoke)) { // For GC stackwalking, we'll happily walk across native code blocks, but for EH dispatch, we // disallow dispatching exceptions across native code. if (unwoundReversePInvoke) break; prevControlPC = frameIter.ControlPC; DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); // A debugger can subscribe to get callbacks at a specific frame of exception dispatch // exInfo._notifyDebuggerSP can be populated by the debugger from out of process // at any time. if (exInfo._notifyDebuggerSP == frameIter.SP) DebuggerNotify.FirstPassFrameEntered(exceptionObj, frameIter.ControlPC, frameIter.SP); UpdateStackTrace(exceptionObj, ref exInfo, ref isFirstRethrowFrame, ref prevFramePtr, ref isFirstFrame); byte* pHandler; if (FindFirstPassHandler(exceptionObj, startIdx, ref frameIter, out catchingTryRegionIdx, out pHandler)) { handlingFrameSP = frameIter.SP; pCatchHandler = pHandler; DebugVerifyHandlingFrame(handlingFrameSP); break; } } DebuggerNotify.EndFirstPass(exceptionObj, pCatchHandler, handlingFrameSP); if (pCatchHandler == null) { UnhandledExceptionFailFastViaClasslib( RhFailFastReason.PN_UnhandledException, exceptionObj, (IntPtr)prevControlPC, // IP of the last frame that did not handle the exception ref exInfo); } // We FailFast above if the exception goes unhandled. Therefore, we cannot run the second pass // without a catch handler. Debug.Assert(pCatchHandler != null, "We should have a handler if we're starting the second pass"); DebuggerNotify.BeginSecondPass(); // ------------------------------------------------ // // Second pass // // ------------------------------------------------ // Due to the stackwalker logic, we cannot tolerate triggering a GC from the dispatch code once we // are in the 2nd pass. This is because the stackwalker applies a particular unwind semantic to // 'collapse' funclets which gets confused when we walk out of the dispatch code and encounter the // 'main body' without first encountering the funclet. The thunks used to invoke 2nd-pass // funclets will always toggle this mode off before invoking them. InternalCalls.RhpSetThreadDoNotTriggerGC(); exInfo._passNumber = 2; startIdx = MaxTryRegionIdx; isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0); for (; isValid && ((byte*)frameIter.SP <= (byte*)handlingFrameSP); isValid = frameIter.Next(out startIdx)) { Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly"); DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); if (frameIter.SP == handlingFrameSP) { // invoke only a partial second-pass here... InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx); break; } InvokeSecondPass(ref exInfo, startIdx); } // ------------------------------------------------ // // Call the handler and resume execution // // ------------------------------------------------ exInfo._idxCurClause = catchingTryRegionIdx; InternalCalls.RhpCallCatchFunclet( exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo); // currently, RhpCallCatchFunclet will resume after the catch Debug.Assert(false, "unreachable"); FallbackFailFast(RhFailFastReason.InternalError, null); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugScanCallFrame(int passNumber, byte* ip, UIntPtr sp) { Debug.Assert(ip != null, "IP address must not be null"); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugVerifyHandlingFrame(UIntPtr handlingFrameSP) { Debug.Assert(handlingFrameSP != MaxSP, "Handling frame must have an SP value"); Debug.Assert(((UIntPtr*)handlingFrameSP) > &handlingFrameSP, "Handling frame must have a valid stack frame pointer"); } private static void UpdateStackTrace(object exceptionObj, ref ExInfo exInfo, ref bool isFirstRethrowFrame, ref UIntPtr prevFramePtr, ref bool isFirstFrame) { // We use the fact that all funclet stack frames belonging to the same logical method activation // will have the same FramePointer value. Additionally, the stackwalker will return a sequence of // callbacks for all the funclet stack frames, one right after the other. The classlib doesn't // want to know about funclets, so we strip them out by only reporting the first frame of a // sequence of funclets. This is correct because the leafmost funclet is first in the sequence // and corresponds to the current 'IP state' of the method. UIntPtr curFramePtr = exInfo._frameIter.FramePointer; if ((prevFramePtr == UIntPtr.Zero) || (curFramePtr != prevFramePtr)) { AppendExceptionStackFrameViaClasslib(exceptionObj, (IntPtr)exInfo._frameIter.ControlPC, ref isFirstRethrowFrame, ref isFirstFrame); } prevFramePtr = curFramePtr; } private static bool FindFirstPassHandler(object exception, uint idxStart, ref StackFrameIterator frameIter, out uint tryRegionIdx, out byte* pHandler) { pHandler = null; tryRegionIdx = MaxTryRegionIdx; EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref frameIter, &pbMethodStartAddress, &ehEnum)) return false; byte* pbControlPC = frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause); curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; // We are done skipping. This is required to handle empty finally block markers that are used // to separate runs of different try blocks with same native code offsets. idxStart = MaxTryRegionIdx; } RhEHClauseKind clauseKind = ehClause._clauseKind; if (((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_TYPED) && (clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FILTER)) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. if (clauseKind == RhEHClauseKind.RH_EH_CLAUSE_TYPED) { if (ShouldTypedClauseCatchThisException(exception, (EEType*)ehClause._pTargetType)) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } else { byte* pFilterFunclet = ehClause._filterAddress; bool shouldInvokeHandler = InternalCalls.RhpCallFilterFunclet(exception, pFilterFunclet, frameIter.RegisterSet); if (shouldInvokeHandler) { pHandler = ehClause._handlerAddress; tryRegionIdx = curIdx; return true; } } } return false; } private static EEType* s_pLowLevelObjectType; private static bool ShouldTypedClauseCatchThisException(object exception, EEType* pClauseType) { if (TypeCast.IsInstanceOfClass(exception, pClauseType) != null) return true; if (s_pLowLevelObjectType == null) { // TODO: Avoid allocating here as that may fail s_pLowLevelObjectType = new System.Object().EEType; } // This allows the typical try { } catch { }--which expands to a typed catch of System.Object--to work on // all objects when the clause is in the low level runtime code. This special case is needed because // objects from foreign type systems are sometimes throw back up at runtime code and this is the only way // to catch them outside of having a filter with no type check in it, which isn't currently possible to // write in C#. See https://github.com/dotnet/roslyn/issues/4388 if (pClauseType->IsEquivalentTo(s_pLowLevelObjectType)) return true; return false; } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart) { InvokeSecondPass(ref exInfo, idxStart, MaxTryRegionIdx); } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxLimit) { EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref exInfo._frameIter, &pbMethodStartAddress, &ehEnum)) return; byte* pbControlPC = exInfo._frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause) && curIdx < idxLimit; curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; // We are done skipping. This is required to handle empty finally block markers that are used // to separate runs of different try blocks with same native code offsets. idxStart = MaxTryRegionIdx; } RhEHClauseKind clauseKind = ehClause._clauseKind; if ((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FAULT) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. // N.B. -- We need to suppress GC "in-between" calls to finallys in this loop because we do // not have the correct next-execution point live on the stack and, therefore, may cause a GC // hole if we allow a GC between invocation of finally funclets (i.e. after one has returned // here to the dispatcher, but before the next one is invoked). Once they are running, it's // fine for them to trigger a GC, obviously. // // As a result, RhpCallFinallyFunclet will set this state in the runtime upon return from the // funclet, and we need to reset it if/when we fall out of the loop and we know that the // method will no longer get any more GC callbacks. byte* pFinallyHandler = ehClause._handlerAddress; exInfo._idxCurClause = curIdx; InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet); exInfo._idxCurClause = MaxTryRegionIdx; } } [NativeCallable(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallingConvention = CallingConvention.Cdecl)] public static void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, PInvokeCallsiteReturnAddr); } [RuntimeExport("RhpFailFastForPInvokeExceptionCoop")] public static void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, classlibBreadcrumb); } } // static class EH }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics.Particle; using FlatRedBall.Utilities; #if FRB_MDX using Format = Microsoft.DirectX.Direct3D.Format; #endif namespace FlatRedBall.Graphics { #region Enums public enum ColorOperation { Texture, Add, Subtract, Modulate, InverseTexture, Color, ColorTextureAlpha, Modulate2X, Modulate4X, InterpolateColor } public enum BlendOperation { Regular, Add, Modulate, Modulate2X, NonPremultipliedAlpha, SubtractAlpha } public enum SortType { /// <summary> /// No sorting will be performed, objects will remain in the the same order that they've been added to their respective list /// </summary> None, /// <summary> /// Objects will sort by their Z value /// </summary> Z, DistanceFromCamera, DistanceAlongForwardVector, /// <summary> /// Objects will be sorted based on their Z value first. Objects with identical Z values will sort using their top parent Y values. /// </summary> ZSecondaryParentY, CustomComparer, Texture } public enum TextureCoordinateType { UV, Pixel } public enum CameraModelCullMode { Frustum, None } public enum CameraCullMode { UnrotatedDownZ, None } public enum OrderingMode { Undefined, DistanceFromCamera, ZBuffered } #endregion public static class GraphicalEnumerations { #region Fields #if FRB_MDX public static float MaxColorComponentValue { get { if (GraphicsOptions.UseXnaColors) { return 1; } else { return 255; } } } #else public const float MaxColorComponentValue = 1.0f; #endif public static List<String> mConvertableSpriteProperties = new List<string> ( new string[8] { "Alpha", "AlphaRate", "Blue", "BlueRate", "Green", "GreenRate", "Red", "RedRate" } ); #endregion #region Properties public static List<String> ConvertableSpriteProperties { get { return mConvertableSpriteProperties; } } #endregion #region BlendOperation Methods public static BlendOperation TranslateBlendOperation(string op) { if (string.IsNullOrEmpty(op)) { return FlatRedBall.Graphics.BlendOperation.Regular; } switch (op.ToLower()) { case "regular": return FlatRedBall.Graphics.BlendOperation.Regular; case "add": return FlatRedBall.Graphics.BlendOperation.Add; case "alphaadd": return FlatRedBall.Graphics.BlendOperation.Add; case "modulate": return FlatRedBall.Graphics.BlendOperation.Modulate; case "modulate2x": return FlatRedBall.Graphics.BlendOperation.Modulate2X; case "nonpremultipliedalpha": return BlendOperation.NonPremultipliedAlpha; default: throw new NotImplementedException("Color Operation " + op + " not implemented"); } } // TODO: Need to add this in once FRB MDX uses strings instead of BlendOperationSave /* public static string TranslateBlendOperation(BlendOperation op) { switch (op) { case FlatRedBall.Graphics.BlendOperation.Add: return "ADD"; // case "ALPHAADD": // TODO: Add ALPHAADD //throw new System.NotImplementedException("ALPHAADD is currently not supported in FlatRedBall XNA"); // return FlatRedBall.Graphics.BlendOperation.Add; case FlatRedBall.Graphics.BlendOperation.Modulate: return "MODULATE"; case FlatRedBall.Graphics.BlendOperation.Modulate2X: // TODO: Add Modulate2X return "MODULATE2X"; //break; case FlatRedBall.Graphics.BlendOperation.Regular: return "REGULAR"; default: throw new NotImplementedException("Color Operation " + op + " not implemented"); } } */ public static string BlendOperationToFlatRedBallMdxString(FlatRedBall.Graphics.BlendOperation op) { switch (op) { case FlatRedBall.Graphics.BlendOperation.Add: return "ADD"; case FlatRedBall.Graphics.BlendOperation.Modulate: return "MODULATE"; case FlatRedBall.Graphics.BlendOperation.Modulate2X: return "MODULATE2X"; //break; case FlatRedBall.Graphics.BlendOperation.Regular: return "REGULAR"; default: throw new NotImplementedException("Color Operation " + op + " not implemented"); } } #endregion #region ColorOperation Methods public static ColorOperation TranslateColorOperation(string op) { // This is likely not going to compile on all platforms, need to test it out. switch (op) { case "Add": return FlatRedBall.Graphics.ColorOperation.Add; //break; case "Modulate": return FlatRedBall.Graphics.ColorOperation.Modulate; //break; case "SelectArg1": case "Texture": case "None": case "": case null: return FlatRedBall.Graphics.ColorOperation.Texture; //break; case "InverseTexture": return ColorOperation.InverseTexture; case "Color": return ColorOperation.Color; case "SelectArg2": case "ColorTextureAlpha": return FlatRedBall.Graphics.ColorOperation.ColorTextureAlpha; //break; case "Subtract": return FlatRedBall.Graphics.ColorOperation.Subtract; //break; case "Modulate2X": return FlatRedBall.Graphics.ColorOperation.Modulate2X; //break; case "Modulate4X": return FlatRedBall.Graphics.ColorOperation.Modulate4X; //break; case "InterpolateColor": return ColorOperation.InterpolateColor; default: throw new System.NotImplementedException( op + " is currently not supported in FlatRedBall XNA"); //break; } } public static string ColorOperationToFlatRedBallMdxString(ColorOperation op) { switch (op) { case FlatRedBall.Graphics.ColorOperation.Add: return "Add"; //break; case ColorOperation.InverseTexture: return "InverseTexture"; //break; case ColorOperation.InterpolateColor: return "InterpolateColor"; //break; case FlatRedBall.Graphics.ColorOperation.Modulate: return "Modulate"; //break; case FlatRedBall.Graphics.ColorOperation.Texture: return "SelectArg1"; //break; case ColorOperation.Color: case FlatRedBall.Graphics.ColorOperation.ColorTextureAlpha: return "SelectArg2"; //break; case FlatRedBall.Graphics.ColorOperation.Subtract: return "Subtract"; //break; case FlatRedBall.Graphics.ColorOperation.Modulate2X: return "Modulate2X"; // break; case FlatRedBall.Graphics.ColorOperation.Modulate4X: return "Modulate4X"; // break; default: throw new System.NotImplementedException( op + " is currently not supported in FlatRedBall XNA"); //break; } } public static void SetColors(IColorable colorable, float desiredRed, float desiredGreen, float desiredBlue, string op) { if (op == "AddSigned") { desiredRed -= 127.5f; desiredGreen -= 127.5f; desiredBlue -= 127.5f; op = "Add"; } colorable.ColorOperation = TranslateColorOperation(op); colorable.Red = desiredRed / 255.0f; colorable.Green = desiredGreen / 255.0f; colorable.Blue = desiredBlue / 255.0f; } #endregion #region AreaEmissionType public static Emitter.AreaEmissionType TranslateAreaEmissionType(string op) { switch (op) { case "Point": case null: case "": return Emitter.AreaEmissionType.Point; //break; case "Rectangle": return Emitter.AreaEmissionType.Rectangle; //break; case "Cube": return Emitter.AreaEmissionType.Cube; //break; default: throw new System.NotImplementedException( op + " is currently not supported in FlatRedBall XNA"); //break; } } public static string TranslateAreaEmissionType(Emitter.AreaEmissionType op) { switch (op) { case Emitter.AreaEmissionType.Point: return "Point"; //break; case Emitter.AreaEmissionType.Rectangle: return "Rectangle"; //break; case Emitter.AreaEmissionType.Cube: return "Cube"; //break; default: throw new System.NotImplementedException( op + " is currently not supported in FlatRedBall XNA"); //break; } } #endregion #region Texture Methods #if FRB_MDX public static int BitsPerPixelInFormat(Microsoft.DirectX.Direct3D.Format imageFormat) { switch (imageFormat) { case Format.A4L4: case Format.A8: case Format.L8: case Format.P8: case Format.R3G3B2: return 8; break; case Format.A1R5G5B5: case Format.A4R4G4B4: case Format.A8L8: case Format.A8P8: case Format.A8R3G3B2: case Format.D15S1: case Format.D16: case Format.D16Lockable: case Format.L16: case Format.L6V5U5: case Format.R16F: case Format.R5G6B5: case Format.V8U8: case Format.X1R5G5B5: case Format.X4R4G4B4: return 16; break; case Format.R8G8B8: return 24; break; case Format.A2B10G10R10: case Format.A2R10G10B10: case Format.A2W10V10U10: case Format.A8B8G8R8: case Format.A8R8G8B8: case Format.CxV8U8: case Format.D24S8: case Format.D24SingleS8: case Format.D24X4S4: case Format.D24X8: case Format.D32: case Format.D32SingleLockable: case Format.G16R16: case Format.G16R16F: case Format.G8R8G8B8: case Format.Q8W8V8U8: case Format.R32F: case Format.R8G8B8G8: case Format.V16U16: case Format.X8B8G8R8: case Format.X8L8V8U8: case Format.X8R8G8B8: return 32; break; case Format.A16B16G16R16: case Format.A16B16G16R16F: case Format.G32R32F: case Format.Q16W16V16U16: return 64; break; case Format.A32B32G32R32F: return 128; default: return 32; // assume 32 bpp break; } } #endif #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Relators; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Persistence.Repositories { /// <summary> /// Represents a repository for doing CRUD operations for <see cref="DictionaryItem"/> /// </summary> internal class DictionaryRepository : PetaPocoRepositoryBase<int, IDictionaryItem>, IDictionaryRepository { private readonly ILanguageRepository _languageRepository; public DictionaryRepository(IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider syntax, ILanguageRepository languageRepository) : base(work, cache, logger, syntax) { _languageRepository = languageRepository; } #region Overrides of RepositoryBase<int,DictionaryItem> protected override IDictionaryItem PerformGet(int id) { var sql = GetBaseQuery(false) .Where(GetBaseWhereClause(), new {Id = id}) .OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); var dto = Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql).FirstOrDefault(); if (dto == null) return null; //This will be cached var allLanguages = _languageRepository.GetAll().ToArray(); var entity = ConvertFromDto(dto, allLanguages); //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 ((Entity)entity).ResetDirtyProperties(false); return entity; } protected override IEnumerable<IDictionaryItem> PerformGetAll(params int[] ids) { var sql = GetBaseQuery(false).Where("cmsDictionary.pk > 0"); if (ids.Any()) { sql.Where("cmsDictionary.pk in (@ids)", new { ids = ids }); } //This will be cached var allLanguages = _languageRepository.GetAll().ToArray(); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(dto => ConvertFromDto(dto, allLanguages)); } protected override IEnumerable<IDictionaryItem> PerformGetByQuery(IQuery<IDictionaryItem> query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator<IDictionaryItem>(sqlClause, query); var sql = translator.Translate(); sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); //This will be cached var allLanguages = _languageRepository.GetAll().ToArray(); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(x => ConvertFromDto(x, allLanguages)); } #endregion #region Overrides of PetaPocoRepositoryBase<int,DictionaryItem> protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql(); if(isCount) { sql.Select("COUNT(*)") .From<DictionaryDto>(SqlSyntax); } else { sql.Select("*") .From<DictionaryDto>(SqlSyntax) .LeftJoin<LanguageTextDto>(SqlSyntax) .On<DictionaryDto, LanguageTextDto>(SqlSyntax, left => left.UniqueId, right => right.UniqueId); } return sql; } protected override string GetBaseWhereClause() { return "cmsDictionary.pk = @Id"; } protected override IEnumerable<string> GetDeleteClauses() { return new List<string>(); } protected override Guid NodeObjectTypeId { get { throw new NotImplementedException(); } } #endregion #region Unit of Work Implementation protected override void PersistNewItem(IDictionaryItem entity) { ((DictionaryItem)entity).AddingEntity(); foreach (var translation in entity.Translations) translation.Value = translation.Value.ToValidXmlString(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(entity); var id = Convert.ToInt32(Database.Insert(dto)); entity.Id = id; var translationFactory = new DictionaryTranslationFactory(entity.Key, null); foreach (var translation in entity.Translations) { var textDto = translationFactory.BuildDto(translation); translation.Id = Convert.ToInt32(Database.Insert(textDto)); translation.Key = entity.Key; } entity.ResetDirtyProperties(); } protected override void PersistUpdatedItem(IDictionaryItem entity) { ((Entity)entity).UpdatingEntity(); foreach (var translation in entity.Translations) translation.Value = translation.Value.ToValidXmlString(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(entity); Database.Update(dto); var translationFactory = new DictionaryTranslationFactory(entity.Key, null); foreach (var translation in entity.Translations) { var textDto = translationFactory.BuildDto(translation); if(translation.HasIdentity) { Database.Update(textDto); } else { translation.Id = Convert.ToInt32(Database.Insert(textDto)); translation.Key = entity.Key; } } entity.ResetDirtyProperties(); //Clear the cache entries that exist by uniqueid/item key RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.ItemKey)); RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.Key)); } protected override void PersistDeletedItem(IDictionaryItem entity) { RecursiveDelete(entity.Key); Database.Delete<LanguageTextDto>("WHERE UniqueId = @Id", new { Id = entity.Key}); Database.Delete<DictionaryDto>("WHERE id = @Id", new { Id = entity.Key }); //Clear the cache entries that exist by uniqueid/item key RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.ItemKey)); RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.Key)); } private void RecursiveDelete(Guid parentId) { var list = Database.Fetch<DictionaryDto>("WHERE parent = @ParentId", new {ParentId = parentId}); foreach (var dto in list) { RecursiveDelete(dto.UniqueId); Database.Delete<LanguageTextDto>("WHERE UniqueId = @Id", new { Id = dto.UniqueId }); Database.Delete<DictionaryDto>("WHERE id = @Id", new { Id = dto.UniqueId }); //Clear the cache entries that exist by uniqueid/item key RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(dto.Key)); RuntimeCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(dto.UniqueId)); } } #endregion protected IDictionaryItem ConvertFromDto(DictionaryDto dto, ILanguage[] allLanguages) { var factory = new DictionaryItemFactory(); var entity = factory.BuildEntity(dto); var list = new List<IDictionaryTranslation>(); foreach (var textDto in dto.LanguageTextDtos) { //Assuming this is cached! var language = allLanguages.FirstOrDefault(x => x.Id == textDto.LanguageId); if (language == null) continue; var translationFactory = new DictionaryTranslationFactory(dto.UniqueId, language); list.Add(translationFactory.BuildEntity(textDto)); } entity.Translations = list; return entity; } public IDictionaryItem Get(Guid uniqueId) { using (var uniqueIdRepo = new DictionaryByUniqueIdRepository(this, UnitOfWork, RepositoryCache, Logger, SqlSyntax)) { return uniqueIdRepo.Get(uniqueId); } } public IDictionaryItem Get(string key) { using (var keyRepo = new DictionaryByKeyRepository(this, UnitOfWork, RepositoryCache, Logger, SqlSyntax)) { return keyRepo.Get(key); } } private IEnumerable<IDictionaryItem> GetRootDictionaryItems() { var query = Query<IDictionaryItem>.Builder.Where(x => x.ParentId == null); return GetByQuery(query); } public IEnumerable<IDictionaryItem> GetDictionaryItemDescendants(Guid? parentId) { //This will be cached var allLanguages = _languageRepository.GetAll().ToArray(); //This methods will look up children at each level, since we do not store a path for dictionary (ATM), we need to do a recursive // lookup to get descendants. Currently this is the most efficient way to do it Func<Guid[], IEnumerable<IEnumerable<IDictionaryItem>>> getItemsFromParents = guids => { //needs to be in groups of 2000 because we are doing an IN clause and there's a max parameter count that can be used. return guids.InGroupsOf(2000) .Select(@group => { var sqlClause = GetBaseQuery(false) .Where<DictionaryDto>(x => x.Parent != null) .Where(string.Format("{0} IN (@parentIds)", SqlSyntax.GetQuotedColumnName("parent")), new { parentIds = @group }); var translator = new SqlTranslator<IDictionaryItem>(sqlClause, Query<IDictionaryItem>.Builder); var sql = translator.Translate(); sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(x => ConvertFromDto(x, allLanguages)); }); }; var childItems = parentId.HasValue == false ? new[] { GetRootDictionaryItems() } : getItemsFromParents(new[] { parentId.Value }); return childItems.SelectRecursive(items => getItemsFromParents(items.Select(x => x.Key).ToArray())).SelectMany(items => items); } private class DictionaryByUniqueIdRepository : SimpleGetRepository<Guid, IDictionaryItem, DictionaryDto> { private readonly DictionaryRepository _dictionaryRepository; public DictionaryByUniqueIdRepository(DictionaryRepository dictionaryRepository, IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _dictionaryRepository = dictionaryRepository; } protected override IEnumerable<DictionaryDto> PerformFetch(Sql sql) { return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql); } protected override Sql GetBaseQuery(bool isCount) { return _dictionaryRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("id") + " = @Id"; } protected override IDictionaryItem ConvertToEntity(DictionaryDto dto) { //This will be cached var allLanguages = _dictionaryRepository._languageRepository.GetAll().ToArray(); return _dictionaryRepository.ConvertFromDto(dto, allLanguages); } protected override object GetBaseWhereClauseArguments(Guid id) { return new {Id = id}; } protected override string GetWhereInClauseForGetAll() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("id") + " in (@ids)"; } } private class DictionaryByKeyRepository : SimpleGetRepository<string, IDictionaryItem, DictionaryDto> { private readonly DictionaryRepository _dictionaryRepository; public DictionaryByKeyRepository(DictionaryRepository dictionaryRepository, IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _dictionaryRepository = dictionaryRepository; } protected override IEnumerable<DictionaryDto> PerformFetch(Sql sql) { return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql); } protected override Sql GetBaseQuery(bool isCount) { return _dictionaryRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("key") + " = @Id"; } protected override IDictionaryItem ConvertToEntity(DictionaryDto dto) { //This will be cached var allLanguages = _dictionaryRepository._languageRepository.GetAll().ToArray(); return _dictionaryRepository.ConvertFromDto(dto, allLanguages); } protected override object GetBaseWhereClauseArguments(string id) { return new { Id = id }; } protected override string GetWhereInClauseForGetAll() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("key") + " in (@ids)"; } } /// <summary> /// Dispose disposable properties /// </summary> /// <remarks> /// Ensure the unit of work is disposed /// </remarks> protected override void DisposeResources() { _languageRepository.Dispose(); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Linq; using Csla; using Csla.Data; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// ProductTypeUpdatedByRootList (read only list).<br/> /// This is a generated <see cref="ProductTypeUpdatedByRootList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// Updated by ProductTypeEdit /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeUpdatedByRootList : ReadOnlyBindingListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #else public partial class ProductTypeUpdatedByRootList : ReadOnlyListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeUpdatedByRootInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeUpdatedByRootInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeUpdatedByRootInfo in this) { if (productTypeUpdatedByRootInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeUpdatedByRootList"/> collection.</returns> public static ProductTypeUpdatedByRootList GetProductTypeUpdatedByRootList() { return DataPortal.Fetch<ProductTypeUpdatedByRootList>(); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeUpdatedByRootList(EventHandler<DataPortalResult<ProductTypeUpdatedByRootList>> callback) { DataPortal.BeginFetch<ProductTypeUpdatedByRootList>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeUpdatedByRootList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeUpdatedByRootList() { // Use factory methods and do not use direct creation. ProductTypeEditSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeEdit"/> to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeEdit)e.NewObject; if (((ProductTypeEdit)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeUpdatedByRootInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeEdit)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeUpdatedByRootList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IProductTypeUpdatedByRootListDal>(); var data = dal.Fetch(); LoadCollection(data); } OnFetchPost(args); } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="ProductTypeUpdatedByRootList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(DataPortal.FetchChild<ProductTypeUpdatedByRootInfo>(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion #region ProductTypeEditSaved nested class // TODO: edit "ProductTypeUpdatedByRootList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeEditSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeEdit"/> /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> private static class ProductTypeEditSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeUpdatedByRootList instance to handle Saved events. /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeUpdatedByRootList instance.</param> public static void Register(ProductTypeUpdatedByRootList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeUpdatedByRootList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeEdit.ProductTypeEditSaved += ProductTypeEditSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeEdit"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeUpdatedByRootList) reference.Target).ProductTypeEditSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeUpdatedByRootList instances. /// </summary> public static void Unregister() { ProductTypeEdit.ProductTypeEditSaved -= ProductTypeEditSavedHandler; _references = null; } } #endregion } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. #pragma warning disable IDE0051 using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.VM; using System; using System.Linq; using System.Numerics; namespace Neo.SmartContract.Native { /// <summary> /// A native contract for storing all blocks and transactions. /// </summary> public sealed class LedgerContract : NativeContract { private const byte Prefix_BlockHash = 9; private const byte Prefix_CurrentBlock = 12; private const byte Prefix_Block = 5; private const byte Prefix_Transaction = 11; internal LedgerContract() { } internal override ContractTask OnPersist(ApplicationEngine engine) { TransactionState[] transactions = engine.PersistingBlock.Transactions.Select(p => new TransactionState { BlockIndex = engine.PersistingBlock.Index, Transaction = p, State = VMState.NONE }).ToArray(); engine.Snapshot.Add(CreateStorageKey(Prefix_BlockHash).AddBigEndian(engine.PersistingBlock.Index), new StorageItem(engine.PersistingBlock.Hash.ToArray())); engine.Snapshot.Add(CreateStorageKey(Prefix_Block).Add(engine.PersistingBlock.Hash), new StorageItem(Trim(engine.PersistingBlock).ToArray())); foreach (TransactionState tx in transactions) { engine.Snapshot.Add(CreateStorageKey(Prefix_Transaction).Add(tx.Transaction.Hash), new StorageItem(tx)); } engine.SetState(transactions); return ContractTask.CompletedTask; } internal override ContractTask PostPersist(ApplicationEngine engine) { HashIndexState state = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_CurrentBlock), () => new StorageItem(new HashIndexState())).GetInteroperable<HashIndexState>(); state.Hash = engine.PersistingBlock.Hash; state.Index = engine.PersistingBlock.Index; return ContractTask.CompletedTask; } internal bool Initialized(DataCache snapshot) { return snapshot.Find(CreateStorageKey(Prefix_Block).ToArray()).Any(); } private bool IsTraceableBlock(DataCache snapshot, uint index, uint maxTraceableBlocks) { uint currentIndex = CurrentIndex(snapshot); if (index > currentIndex) return false; return index + maxTraceableBlocks > currentIndex; } /// <summary> /// Gets the hash of the specified block. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="index">The index of the block.</param> /// <returns>The hash of the block.</returns> public UInt256 GetBlockHash(DataCache snapshot, uint index) { StorageItem item = snapshot.TryGet(CreateStorageKey(Prefix_BlockHash).AddBigEndian(index)); if (item is null) return null; return new UInt256(item.Value); } /// <summary> /// Gets the hash of the current block. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <returns>The hash of the current block.</returns> [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] public UInt256 CurrentHash(DataCache snapshot) { return snapshot[CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>().Hash; } /// <summary> /// Gets the index of the current block. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <returns>The index of the current block.</returns> [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] public uint CurrentIndex(DataCache snapshot) { return snapshot[CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>().Index; } /// <summary> /// Determine whether the specified block is contained in the blockchain. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the block.</param> /// <returns><see langword="true"/> if the blockchain contains the block; otherwise, <see langword="false"/>.</returns> public bool ContainsBlock(DataCache snapshot, UInt256 hash) { return snapshot.Contains(CreateStorageKey(Prefix_Block).Add(hash)); } /// <summary> /// Determine whether the specified transaction is contained in the blockchain. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the transaction.</param> /// <returns><see langword="true"/> if the blockchain contains the transaction; otherwise, <see langword="false"/>.</returns> public bool ContainsTransaction(DataCache snapshot, UInt256 hash) { return snapshot.Contains(CreateStorageKey(Prefix_Transaction).Add(hash)); } /// <summary> /// Gets a <see cref="TrimmedBlock"/> with the specified hash. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the block.</param> /// <returns>The trimmed block.</returns> public TrimmedBlock GetTrimmedBlock(DataCache snapshot, UInt256 hash) { StorageItem item = snapshot.TryGet(CreateStorageKey(Prefix_Block).Add(hash)); if (item is null) return null; return item.Value.AsSerializable<TrimmedBlock>(); } [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] private TrimmedBlock GetBlock(ApplicationEngine engine, byte[] indexOrHash) { UInt256 hash; if (indexOrHash.Length < UInt256.Length) hash = GetBlockHash(engine.Snapshot, (uint)new BigInteger(indexOrHash)); else if (indexOrHash.Length == UInt256.Length) hash = new UInt256(indexOrHash); else throw new ArgumentException(null, nameof(indexOrHash)); if (hash is null) return null; TrimmedBlock block = GetTrimmedBlock(engine.Snapshot, hash); if (block is null || !IsTraceableBlock(engine.Snapshot, block.Index, engine.ProtocolSettings.MaxTraceableBlocks)) return null; return block; } /// <summary> /// Gets a block with the specified hash. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the block.</param> /// <returns>The block with the specified hash.</returns> public Block GetBlock(DataCache snapshot, UInt256 hash) { TrimmedBlock state = GetTrimmedBlock(snapshot, hash); if (state is null) return null; return new Block { Header = state.Header, Transactions = state.Hashes.Select(p => GetTransaction(snapshot, p)).ToArray() }; } /// <summary> /// Gets a block with the specified index. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="index">The index of the block.</param> /// <returns>The block with the specified index.</returns> public Block GetBlock(DataCache snapshot, uint index) { UInt256 hash = GetBlockHash(snapshot, index); if (hash is null) return null; return GetBlock(snapshot, hash); } /// <summary> /// Gets a block header with the specified hash. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the block.</param> /// <returns>The block header with the specified hash.</returns> public Header GetHeader(DataCache snapshot, UInt256 hash) { return GetTrimmedBlock(snapshot, hash)?.Header; } /// <summary> /// Gets a block header with the specified index. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="index">The index of the block.</param> /// <returns>The block header with the specified index.</returns> public Header GetHeader(DataCache snapshot, uint index) { UInt256 hash = GetBlockHash(snapshot, index); if (hash is null) return null; return GetHeader(snapshot, hash); } /// <summary> /// Gets a <see cref="TransactionState"/> with the specified hash. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the transaction.</param> /// <returns>The <see cref="TransactionState"/> with the specified hash.</returns> public TransactionState GetTransactionState(DataCache snapshot, UInt256 hash) { return snapshot.TryGet(CreateStorageKey(Prefix_Transaction).Add(hash))?.GetInteroperable<TransactionState>(); } /// <summary> /// Gets a transaction with the specified hash. /// </summary> /// <param name="snapshot">The snapshot used to read data.</param> /// <param name="hash">The hash of the transaction.</param> /// <returns>The transaction with the specified hash.</returns> public Transaction GetTransaction(DataCache snapshot, UInt256 hash) { return GetTransactionState(snapshot, hash)?.Transaction; } [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates, Name = "getTransaction")] private Transaction GetTransactionForContract(ApplicationEngine engine, UInt256 hash) { TransactionState state = GetTransactionState(engine.Snapshot, hash); if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return null; return state.Transaction; } [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] private VMState GetTransactionVMState(ApplicationEngine engine, UInt256 hash) { TransactionState state = GetTransactionState(engine.Snapshot, hash); if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return VMState.NONE; return state.State; } [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] private int GetTransactionHeight(ApplicationEngine engine, UInt256 hash) { TransactionState state = GetTransactionState(engine.Snapshot, hash); if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return -1; return (int)state.BlockIndex; } [ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.ReadStates)] private Transaction GetTransactionFromBlock(ApplicationEngine engine, byte[] blockIndexOrHash, int txIndex) { UInt256 hash; if (blockIndexOrHash.Length < UInt256.Length) hash = GetBlockHash(engine.Snapshot, (uint)new BigInteger(blockIndexOrHash)); else if (blockIndexOrHash.Length == UInt256.Length) hash = new UInt256(blockIndexOrHash); else throw new ArgumentException(null, nameof(blockIndexOrHash)); if (hash is null) return null; TrimmedBlock block = GetTrimmedBlock(engine.Snapshot, hash); if (block is null || !IsTraceableBlock(engine.Snapshot, block.Index, engine.ProtocolSettings.MaxTraceableBlocks)) return null; if (txIndex < 0 || txIndex >= block.Hashes.Length) throw new ArgumentOutOfRangeException(nameof(txIndex)); return GetTransaction(engine.Snapshot, block.Hashes[txIndex]); } private static TrimmedBlock Trim(Block block) { return new TrimmedBlock { Header = block.Header, Hashes = block.Transactions.Select(p => p.Hash).ToArray() }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Framework.Testing; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Cursor; using osu.Game.Graphics.UserInterface; using osu.Game.Resources.Localisation.Web; using osuTK; namespace osu.Game.Skinning.Editor { [Cached(typeof(SkinEditor))] public class SkinEditor : VisibilityContainer { public const double TRANSITION_DURATION = 500; public readonly BindableList<ISkinnableDrawable> SelectedComponents = new BindableList<ISkinnableDrawable>(); protected override bool StartHidden => true; private readonly Drawable targetScreen; private OsuTextFlowContainer headerText; private Bindable<Skin> currentSkin; [Resolved] private SkinManager skins { get; set; } [Resolved] private OsuColour colours { get; set; } private bool hasBegunMutating; public SkinEditor(Drawable targetScreen) { this.targetScreen = targetScreen; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = new OsuContextMenuContainer { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { headerText = new OsuTextFlowContainer { TextAnchor = Anchor.TopCentre, Padding = new MarginPadding(20), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X }, new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension() }, Content = new[] { new Drawable[] { new SkinComponentToolbox(600) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, RequestPlacement = placeComponent }, new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new SkinBlueprintContainer(targetScreen), new TriangleButton { Margin = new MarginPadding(10), Text = CommonStrings.ButtonsClose, Width = 100, Action = Hide, }, new FillFlowContainer { Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Spacing = new Vector2(5), Padding = new MarginPadding { Top = 10, Left = 10, }, Margin = new MarginPadding { Right = 10, Bottom = 10, }, Children = new Drawable[] { new TriangleButton { Text = "Save Changes", Width = 140, Action = Save, }, new DangerousTriangleButton { Text = "Revert to default", Width = 140, Action = revert, }, } }, } }, } } } } }; } protected override void LoadComplete() { base.LoadComplete(); Show(); // as long as the skin editor is loaded, let's make sure we can modify the current skin. currentSkin = skins.CurrentSkin.GetBoundCopy(); // schedule ensures this only happens when the skin editor is visible. // also avoid some weird endless recursion / bindable feedback loop (something to do with tracking skins across three different bindable types). // probably something which will be factored out in a future database refactor so not too concerning for now. currentSkin.BindValueChanged(skin => { hasBegunMutating = false; Scheduler.AddOnce(skinChanged); }, true); } private void skinChanged() { headerText.Clear(); headerText.AddParagraph("Skin editor", cp => cp.Font = OsuFont.Default.With(size: 24)); headerText.NewParagraph(); headerText.AddText("Currently editing ", cp => { cp.Font = OsuFont.Default.With(size: 12); cp.Colour = colours.Yellow; }); headerText.AddText($"{currentSkin.Value.SkinInfo}", cp => { cp.Font = OsuFont.Default.With(size: 12, weight: FontWeight.Bold); cp.Colour = colours.Yellow; }); skins.EnsureMutableSkin(); hasBegunMutating = true; } private void placeComponent(Type type) { var targetContainer = getTarget(SkinnableTarget.MainHUDComponents); if (targetContainer == null) return; if (!(Activator.CreateInstance(type) is ISkinnableDrawable component)) throw new InvalidOperationException($"Attempted to instantiate a component for placement which was not an {typeof(ISkinnableDrawable)}."); var drawableComponent = (Drawable)component; // give newly added components a sane starting location. drawableComponent.Origin = Anchor.TopCentre; drawableComponent.Anchor = Anchor.TopCentre; drawableComponent.Y = targetContainer.DrawSize.Y / 2; targetContainer.Add(component); SelectedComponents.Clear(); SelectedComponents.Add(component); } private IEnumerable<ISkinnableTarget> availableTargets => targetScreen.ChildrenOfType<ISkinnableTarget>(); private ISkinnableTarget getTarget(SkinnableTarget target) { return availableTargets.FirstOrDefault(c => c.Target == target); } private void revert() { ISkinnableTarget[] targetContainers = availableTargets.ToArray(); foreach (var t in targetContainers) { currentSkin.Value.ResetDrawableTarget(t); // add back default components getTarget(t.Target).Reload(); } } public void Save() { if (!hasBegunMutating) return; ISkinnableTarget[] targetContainers = availableTargets.ToArray(); foreach (var t in targetContainers) currentSkin.Value.UpdateDrawableTarget(t); skins.Save(skins.CurrentSkin.Value); } protected override bool OnHover(HoverEvent e) => true; protected override bool OnMouseDown(MouseDownEvent e) => true; protected override void PopIn() { this.FadeIn(TRANSITION_DURATION, Easing.OutQuint); } protected override void PopOut() { this.FadeOut(TRANSITION_DURATION, Easing.OutQuint); } public void DeleteItems(ISkinnableDrawable[] items) { foreach (var item in items) availableTargets.FirstOrDefault(t => t.Components.Contains(item))?.Remove(item); } } }
/* * 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.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using Npgsql; namespace OpenSim.Data.PGSQL { /// <summary> /// A PGSQL interface for the inventory server /// </summary> public class PGSQLInventoryData : IInventoryDataPlugin { private const string _migrationStore = "InventoryStore"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The database manager /// </summary> private PGSQLManager database; private string m_connectionString; #region IPlugin members [Obsolete("Cannot be default-initialized!")] public void Initialise() { m_log.Info("[PGSQLInventoryData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } /// <summary> /// Loads and initialises the PGSQL inventory storage interface /// </summary> /// <param name="connectionString">connect string</param> /// <remarks>use PGSQL_connection.ini</remarks> public void Initialise(string connectionString) { m_connectionString = connectionString; database = new PGSQLManager(connectionString); //New migrations check of store database.CheckMigration(_migrationStore); } /// <summary> /// The name of this DB provider /// </summary> /// <returns>A string containing the name of the DB provider</returns> public string Name { get { return "PGSQL Inventory Data Interface"; } } /// <summary> /// Closes this DB provider /// </summary> public void Dispose() { database = null; } /// <summary> /// Returns the version of this DB provider /// </summary> /// <returns>A string containing the DB provider</returns> public string Version { get { return database.getVersion(); } } #endregion #region Folder methods /// <summary> /// Returns a list of the root folders within a users inventory /// </summary> /// <param name="user">The user whos inventory is to be searched</param> /// <returns>A list of folder objects</returns> public List<InventoryFolderBase> getUserRootFolders(UUID user) { if (user == UUID.Zero) return new List<InventoryFolderBase>(); return getInventoryFolders(UUID.Zero, user); } /// <summary> /// see InventoryItemBase.getUserRootFolder /// </summary> /// <param name="user">the User UUID</param> /// <returns></returns> public InventoryFolderBase getUserRootFolder(UUID user) { List<InventoryFolderBase> items = getUserRootFolders(user); InventoryFolderBase rootFolder = null; // There should only ever be one root folder for a user. However, if there's more // than one we'll simply use the first one rather than failing. It would be even // nicer to print some message to this effect, but this feels like it's too low a // to put such a message out, and it's too minor right now to spare the time to // suitably refactor. if (items.Count > 0) { rootFolder = items[0]; } return rootFolder; } /// <summary> /// Returns a list of folders in a users inventory contained within the specified folder /// </summary> /// <param name="parentID">The folder to search</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { return getInventoryFolders(parentID, UUID.Zero); } /// <summary> /// Returns a specified inventory folder /// </summary> /// <param name="folderID">The folder to return</param> /// <returns>A folder class</returns> public InventoryFolderBase getInventoryFolder(UUID folderID) { string sql = "SELECT * FROM inventoryfolders WHERE \"folderID\" = :folderID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("folderID", folderID)); conn.Open(); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { return readInventoryFolder(reader); } } } m_log.InfoFormat("[INVENTORY DB] : Found no inventory folder with ID : {0}", folderID); return null; } /// <summary> /// Returns all child folders in the hierarchy from the parent folder and down. /// Does not return the parent folder itself. /// </summary> /// <param name="parentID">The folder to get subfolders for</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { //Note maybe change this to use a Dataset that loading in all folders of a user and then go throw it that way. //Note this is changed so it opens only one connection to the database and not everytime it wants to get data. /* NOTE: the implementation below is very inefficient (makes a separate request to get subfolders for * every found folder, recursively). Inventory code for other DBs has been already rewritten to get ALL * inventory for a specific user at once. * * Meanwhile, one little thing is corrected: getFolderHierarchy(UUID.Zero) doesn't make sense and should never * be used, so check for that and return an empty list. */ List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); if (parentID == UUID.Zero) return folders; string sql = "SELECT * FROM inventoryfolders WHERE \"parentFolderID\" = :parentID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("parentID", parentID)); conn.Open(); folders.AddRange(getInventoryFolders(cmd)); List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>(); foreach (InventoryFolderBase folderBase in folders) { tempFolders.AddRange(getFolderHierarchy(folderBase.ID, cmd)); } if (tempFolders.Count > 0) { folders.AddRange(tempFolders); } } return folders; } /// <summary> /// Creates a new inventory folder /// </summary> /// <param name="folder">Folder to create</param> public void addInventoryFolder(InventoryFolderBase folder) { string sql = "INSERT INTO inventoryfolders (\"folderID\", \"agentID\", \"parentFolderID\", \"folderName\", type, version) " + " VALUES (:folderID, :agentID, :parentFolderID, :folderName, :type, :version);"; string folderName = folder.Name; if (folderName.Length > 64) { folderName = folderName.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on add"); } using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); cmd.Parameters.Add(database.CreateParameter("folderName", folderName)); cmd.Parameters.Add(database.CreateParameter("type", folder.Type)); cmd.Parameters.Add(database.CreateParameter("version", folder.Version)); conn.Open(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void updateInventoryFolder(InventoryFolderBase folder) { string sql = @"UPDATE inventoryfolders SET ""agentID"" = :agentID, ""parentFolderID"" = :parentFolderID, ""folderName"" = :folderName, type = :type, version = :version WHERE folderID = :folderID"; string folderName = folder.Name; if (folderName.Length > 64) { folderName = folderName.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on update"); } using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); cmd.Parameters.Add(database.CreateParameter("folderName", folderName)); cmd.Parameters.Add(database.CreateParameter("type", folder.Type)); cmd.Parameters.Add(database.CreateParameter("version", folder.Version)); conn.Open(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void moveInventoryFolder(InventoryFolderBase folder) { string sql = @"UPDATE inventoryfolders SET ""parentFolderID"" = :parentFolderID WHERE ""folderID"" = :folderID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); conn.Open(); try { cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Delete an inventory folder /// </summary> /// <param name="folderID">Id of folder to delete</param> public void deleteInventoryFolder(UUID folderID) { string sql = @"SELECT * FROM inventoryfolders WHERE ""parentFolderID"" = :parentID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { List<InventoryFolderBase> subFolders; cmd.Parameters.Add(database.CreateParameter("parentID", UUID.Zero)); conn.Open(); subFolders = getFolderHierarchy(folderID, cmd); //Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { DeleteOneFolder(f.ID, conn); DeleteItemsInFolder(f.ID, conn); } //Delete the actual row DeleteOneFolder(folderID, conn); DeleteItemsInFolder(folderID, conn); } } #endregion #region Item Methods /// <summary> /// Returns a list of items in a specified folder /// </summary> /// <param name="folderID">The folder to search</param> /// <returns>A list containing inventory items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { string sql = @"SELECT * FROM inventoryitems WHERE ""parentFolderID"" = :parentFolderID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("parentFolderID", folderID)); conn.Open(); List<InventoryItemBase> items = new List<InventoryItemBase>(); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { items.Add(readInventoryItem(reader)); } } return items; } } /// <summary> /// Returns a specified inventory item /// </summary> /// <param name="itemID">The item ID</param> /// <returns>An inventory item</returns> public InventoryItemBase getInventoryItem(UUID itemID) { string sql = @"SELECT * FROM inventoryitems WHERE ""inventoryID"" = :inventoryID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID)); conn.Open(); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { return readInventoryItem(reader); } } } m_log.InfoFormat("[INVENTORY DB]: Found no inventory item with ID : {0}", itemID); return null; } /// <summary> /// Adds a specified item to the database /// </summary> /// <param name="item">The inventory item</param> public void addInventoryItem(InventoryItemBase item) { if (getInventoryItem(item.ID) != null) { updateInventoryItem(item); return; } string sql = @"INSERT INTO inventoryitems (""inventoryID"", ""assetID"", ""assetType"", ""parentFolderID"", ""avatarID"", ""inventoryName"", ""inventoryDescription"", ""inventoryNextPermissions"", ""inventoryCurrentPermissions"", ""invType"", ""creatorID"", ""inventoryBasePermissions"", ""inventoryEveryOnePermissions"", ""inventoryGroupPermissions"", ""salePrice"", ""SaleType"", ""creationDate"", ""groupID"", ""groupOwned"", flags) VALUES (:inventoryID, :assetID, :assetType, :parentFolderID, :avatarID, :inventoryName, :inventoryDescription, :inventoryNextPermissions, :inventoryCurrentPermissions, :invType, :creatorID, :inventoryBasePermissions, :inventoryEveryOnePermissions, :inventoryGroupPermissions, :SalePrice, :SaleType, :creationDate, :groupID, :groupOwned, :flags)"; string itemName = item.Name; if (item.Name.Length > 64) { itemName = item.Name.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters"); } string itemDesc = item.Description; if (item.Description.Length > 128) { itemDesc = item.Description.Substring(0, 128); m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters"); } using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) { command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); command.Parameters.Add(database.CreateParameter("invType", item.InvType)); command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); command.Parameters.Add(database.CreateParameter("SalePrice", item.SalePrice)); command.Parameters.Add(database.CreateParameter("SaleType", item.SaleType)); command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); command.Parameters.Add(database.CreateParameter("flags", item.Flags)); conn.Open(); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error inserting item :" + e.Message); } } sql = @"UPDATE inventoryfolders SET version = version + 1 WHERE ""folderID"" = @folderID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) { command.Parameters.Add(database.CreateParameter("folderID", item.Folder.ToString())); conn.Open(); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB] Error updating inventory folder for new item :" + e.Message); } } } /// <summary> /// Updates the specified inventory item /// </summary> /// <param name="item">Inventory item to update</param> public void updateInventoryItem(InventoryItemBase item) { string sql = @"UPDATE inventoryitems SET ""assetID"" = :assetID, ""assetType"" = :assetType, ""parentFolderID"" = :parentFolderID, ""avatarID"" = :avatarID, ""inventoryName"" = :inventoryName, ""inventoryDescription"" = :inventoryDescription, ""inventoryNextPermissions"" = :inventoryNextPermissions, ""inventoryCurrentPermissions"" = :inventoryCurrentPermissions, ""invType"" = :invType, ""creatorID"" = :creatorID, ""inventoryBasePermissions"" = :inventoryBasePermissions, ""inventoryEveryOnePermissions"" = :inventoryEveryOnePermissions, ""inventoryGroupPermissions"" = :inventoryGroupPermissions, ""salePrice"" = :SalePrice, ""saleType"" = :SaleType, ""creationDate"" = :creationDate, ""groupID"" = :groupID, ""groupOwned"" = :groupOwned, flags = :flags WHERE ""inventoryID"" = :inventoryID"; string itemName = item.Name; if (item.Name.Length > 64) { itemName = item.Name.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters on update"); } string itemDesc = item.Description; if (item.Description.Length > 128) { itemDesc = item.Description.Substring(0, 128); m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters on update"); } using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) { command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); command.Parameters.Add(database.CreateParameter("invType", item.InvType)); command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); command.Parameters.Add(database.CreateParameter("SalePrice", item.SalePrice)); command.Parameters.Add(database.CreateParameter("SaleType", item.SaleType)); command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); command.Parameters.Add(database.CreateParameter("flags", item.Flags)); conn.Open(); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error updating item :" + e.Message); } } } // See IInventoryDataPlugin /// <summary> /// Delete an item in inventory database /// </summary> /// <param name="itemID">the item UUID</param> public void deleteInventoryItem(UUID itemID) { string sql = @"DELETE FROM inventoryitems WHERE ""inventoryID""=:inventoryID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID)); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error deleting item :" + e.Message); } } } public InventoryItemBase queryInventoryItem(UUID itemID) { return getInventoryItem(itemID); } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return getInventoryFolder(folderID); } /// <summary> /// Returns all activated gesture-items in the inventory of the specified avatar. /// </summary> /// <param name="avatarID">The <see cref="UUID"/> of the avatar</param> /// <returns> /// The list of gestures (<see cref="InventoryItemBase"/>s) /// </returns> public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) { string sql = @"SELECT * FROM inventoryitems WHERE ""avatarID"" = :uuid AND ""assetType"" = :assetType and flags = 1"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("uuid", avatarID)); cmd.Parameters.Add(database.CreateParameter("assetType", (int)AssetType.Gesture)); conn.Open(); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { List<InventoryItemBase> gestureList = new List<InventoryItemBase>(); while (reader.Read()) { gestureList.Add(readInventoryItem(reader)); } return gestureList; } } } #endregion #region Private methods /// <summary> /// Delete an item in inventory database /// </summary> /// <param name="folderID">the item ID</param> /// <param name="connection">connection to the database</param> private void DeleteItemsInFolder(UUID folderID, NpgsqlConnection connection) { using (NpgsqlCommand command = new NpgsqlCommand(@"DELETE FROM inventoryitems WHERE ""folderID""=:folderID", connection)) { command.Parameters.Add(database.CreateParameter("folderID", folderID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB] Error deleting item :" + e.Message); } } } /// <summary> /// Gets the folder hierarchy in a loop. /// </summary> /// <param name="parentID">parent ID.</param> /// <param name="command">SQL command/connection to database</param> /// <returns></returns> private static List<InventoryFolderBase> getFolderHierarchy(UUID parentID, NpgsqlCommand command) { command.Parameters["parentID"].Value = parentID.Guid; //.ToString(); List<InventoryFolderBase> folders = getInventoryFolders(command); if (folders.Count > 0) { List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>(); foreach (InventoryFolderBase folderBase in folders) { tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command)); } if (tempFolders.Count > 0) { folders.AddRange(tempFolders); } } return folders; } /// <summary> /// Gets the inventory folders. /// </summary> /// <param name="parentID">parentID, use UUID.Zero to get root</param> /// <param name="user">user id, use UUID.Zero, if you want all folders from a parentID.</param> /// <returns></returns> private List<InventoryFolderBase> getInventoryFolders(UUID parentID, UUID user) { string sql = @"SELECT * FROM inventoryfolders WHERE ""parentFolderID"" = :parentID AND ""agentID"" = :uuid"; using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand command = new NpgsqlCommand(sql, conn)) { if (user == UUID.Zero) { command.Parameters.Add(database.CreateParameter("uuid", "%")); } else { command.Parameters.Add(database.CreateParameter("uuid", user)); } command.Parameters.Add(database.CreateParameter("parentID", parentID)); conn.Open(); return getInventoryFolders(command); } } /// <summary> /// Gets the inventory folders. /// </summary> /// <param name="command">SQLcommand.</param> /// <returns></returns> private static List<InventoryFolderBase> getInventoryFolders(NpgsqlCommand command) { using (NpgsqlDataReader reader = command.ExecuteReader()) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) { items.Add(readInventoryFolder(reader)); } return items; } } /// <summary> /// Reads a list of inventory folders returned by a query. /// </summary> /// <param name="reader">A PGSQL Data Reader</param> /// <returns>A List containing inventory folders</returns> protected static InventoryFolderBase readInventoryFolder(NpgsqlDataReader reader) { try { InventoryFolderBase folder = new InventoryFolderBase(); folder.Owner = DBGuid.FromDB(reader["agentID"]); folder.ParentID = DBGuid.FromDB(reader["parentFolderID"]); folder.ID = DBGuid.FromDB(reader["folderID"]); folder.Name = (string)reader["folderName"]; folder.Type = (short)reader["type"]; folder.Version = Convert.ToUInt16(reader["version"]); return folder; } catch (Exception e) { m_log.Error("[INVENTORY DB] Error reading inventory folder :" + e.Message); } return null; } /// <summary> /// Reads a one item from an SQL result /// </summary> /// <param name="reader">The SQL Result</param> /// <returns>the item read</returns> private static InventoryItemBase readInventoryItem(IDataRecord reader) { try { InventoryItemBase item = new InventoryItemBase(); item.ID = DBGuid.FromDB(reader["inventoryID"]); item.AssetID = DBGuid.FromDB(reader["assetID"]); item.AssetType = Convert.ToInt32(reader["assetType"].ToString()); item.Folder = DBGuid.FromDB(reader["parentFolderID"]); item.Owner = DBGuid.FromDB(reader["avatarID"]); item.Name = reader["inventoryName"].ToString(); item.Description = reader["inventoryDescription"].ToString(); item.NextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"]); item.CurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"]); item.InvType = Convert.ToInt32(reader["invType"].ToString()); item.CreatorId = reader["creatorID"].ToString(); item.BasePermissions = Convert.ToUInt32(reader["inventoryBasePermissions"]); item.EveryOnePermissions = Convert.ToUInt32(reader["inventoryEveryOnePermissions"]); item.GroupPermissions = Convert.ToUInt32(reader["inventoryGroupPermissions"]); item.SalePrice = Convert.ToInt32(reader["salePrice"]); item.SaleType = Convert.ToByte(reader["saleType"]); item.CreationDate = Convert.ToInt32(reader["creationDate"]); item.GroupID = DBGuid.FromDB(reader["groupID"]); item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); item.Flags = Convert.ToUInt32(reader["flags"]); return item; } catch (NpgsqlException e) { m_log.Error("[INVENTORY DB]: Error reading inventory item :" + e.Message); } return null; } /// <summary> /// Delete a folder in inventory databasae /// </summary> /// <param name="folderID">the folder UUID</param> /// <param name="connection">connection to database</param> private void DeleteOneFolder(UUID folderID, NpgsqlConnection connection) { try { using (NpgsqlCommand command = new NpgsqlCommand(@"DELETE FROM inventoryfolders WHERE ""folderID""=:folderID and type=-1", connection)) { command.Parameters.Add(database.CreateParameter("folderID", folderID)); command.ExecuteNonQuery(); } } catch (NpgsqlException e) { m_log.Error("[INVENTORY DB]: Error deleting folder :" + e.Message); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="PropertyDescriptorCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")] /* This class has the HostProtectionAttribute. The purpose of this attribute is to enforce host-specific programming model guidelines, not security behavior. Suppress FxCop message - BUT REVISIT IF ADDING NEW SECURITY ATTRIBUTES. */ [assembly: SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope="type", Target="System.ComponentModel.PropertyDescriptorCollection")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.get_IsFixedSize():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IEnumerable.GetEnumerator():System.Collections.IEnumerator")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.get_IsFixedSize():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.ICollection.get_SyncRoot():System.Object")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Remove(System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.ICollection.get_IsSynchronized():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.get_IsReadOnly():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.get_Keys():System.Collections.ICollection")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.get_IsReadOnly():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.Clear():System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.IndexOf(System.Object):System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Contains(System.Object):System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.RemoveAt(System.Int32):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.GetEnumerator():System.Collections.IEnumerator")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Clear():System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.get_Values():System.Collections.ICollection")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.Contains(System.Object):System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.GetEnumerator():System.Collections.IDictionaryEnumerator")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.Remove(System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.get_Item(System.Int32):System.Object")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.Add(System.Object):System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.CopyTo(System.Array,System.Int32):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.get_Item(System.Object):System.Object")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.Insert(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.System.Collections.ICollection.get_Count():System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection..ctor(System.ComponentModel.PropertyDescriptor[])")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.get_Count():System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.get_Item(System.String):System.ComponentModel.PropertyDescriptor")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection..ctor(System.ComponentModel.PropertyDescriptor[],System.Boolean)")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.GetEnumerator():System.Collections.IEnumerator")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.Find(System.String,System.Boolean):System.ComponentModel.PropertyDescriptor")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.PropertyDescriptorCollection.Sort(System.String[]):System.ComponentModel.PropertyDescriptorCollection")] namespace System.ComponentModel { using Microsoft.Win32; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; /// <devdoc> /// <para> /// Represents a collection of properties. /// </para> /// </devdoc> [System.Security.Permissions.HostProtection(Synchronization = true)] public class PropertyDescriptorCollection : ICollection, IList, IDictionary { /// <devdoc> /// An empty PropertyDescriptorCollection that can used instead of creating a new one with no items. /// </devdoc> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields")] // ReadOnly fields - already shipped. public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null, true); private IDictionary cachedFoundProperties; private bool cachedIgnoreCase; private PropertyDescriptor[] properties; private int propCount = 0; private string[] namedSort; private IComparer comparer; private bool propsOwned = true; private bool needSort = false; private bool readOnly = false; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptorCollection'/> /// class. /// </para> /// </devdoc> public PropertyDescriptorCollection(PropertyDescriptor[] properties) { this.properties = properties; if (properties == null) { this.properties = new PropertyDescriptor[0]; this.propCount = 0; } else { this.propCount = properties.Length; } this.propsOwned = true; } /// <devdoc> /// Initializes a new instance of a property descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </devdoc> public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOnly) : this(properties) { this.readOnly = readOnly; } private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer) { this.propsOwned = false; if (namedSort != null) { this.namedSort = (string[])namedSort.Clone(); } this.comparer = comparer; this.properties = properties; this.propCount = propCount; this.needSort = true; } /// <devdoc> /// <para> /// Gets the number /// of property descriptors in the /// collection. /// </para> /// </devdoc> public int Count { get { return propCount; } } /// <devdoc> /// <para>Gets the property with the specified index /// number.</para> /// </devdoc> public virtual PropertyDescriptor this[int index] { get { if (index >= propCount) { throw new IndexOutOfRangeException(); } EnsurePropsOwned(); return properties[index]; } } /// <devdoc> /// <para>Gets the property with the specified name.</para> /// </devdoc> public virtual PropertyDescriptor this[string name] { get { return Find(name, false); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(PropertyDescriptor value) { if (readOnly) { throw new NotSupportedException(); } EnsureSize(propCount + 1); properties[propCount++] = value; return propCount - 1; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Clear() { if (readOnly) { throw new NotSupportedException(); } propCount = 0; cachedFoundProperties = null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(PropertyDescriptor value) { return IndexOf(value) >= 0; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(Array array, int index) { EnsurePropsOwned(); Array.Copy(properties, 0, array, index, Count); } private void EnsurePropsOwned() { if (!propsOwned) { propsOwned = true; if (properties != null) { PropertyDescriptor[] newProps = new PropertyDescriptor[Count]; Array.Copy(properties, 0, newProps, 0, Count); this.properties = newProps; } } if (needSort) { needSort = false; InternalSort(this.namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= properties.Length) { return; } if (properties == null || properties.Length == 0) { propCount = 0; properties = new PropertyDescriptor[sizeNeeded]; return; } EnsurePropsOwned(); int newSize = Math.Max(sizeNeeded, properties.Length * 2); PropertyDescriptor[] newProps = new PropertyDescriptor[newSize]; Array.Copy(properties, 0, newProps, 0, propCount); properties = newProps; } /// <devdoc> /// <para>Gets the description of the property with the specified /// name.</para> /// </devdoc> public virtual PropertyDescriptor Find(string name, bool ignoreCase) { lock(this) { PropertyDescriptor p = null; if (cachedFoundProperties == null || cachedIgnoreCase != ignoreCase) { cachedIgnoreCase = ignoreCase; cachedFoundProperties = new HybridDictionary(ignoreCase); } // first try to find it in the cache // object cached = cachedFoundProperties[name]; if (cached != null) { return (PropertyDescriptor) cached; } // Now start walking from where we last left off, filling // the cache as we go. // for(int i = 0; i < propCount; i++) { if (ignoreCase) { if (String.Equals(properties[i].Name, name, StringComparison.OrdinalIgnoreCase)) { cachedFoundProperties[name] = properties[i]; p = properties[i]; break; } } else { if (properties[i].Name.Equals(name)) { cachedFoundProperties[name] = properties[i]; p = properties[i]; break; } } } return p; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int IndexOf(PropertyDescriptor value) { return Array.IndexOf(properties, value, 0, propCount); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Insert(int index, PropertyDescriptor value) { if (readOnly) { throw new NotSupportedException(); } EnsureSize(propCount + 1); if (index < propCount) { Array.Copy(properties, index, properties, index + 1, propCount - index); } properties[index] = value; propCount++; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(PropertyDescriptor value) { if (readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void RemoveAt(int index) { if (readOnly) { throw new NotSupportedException(); } if (index < propCount - 1) { Array.Copy(properties, index + 1, properties, index, propCount - index - 1); } properties[propCount - 1] = null; propCount--; } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </para> /// </devdoc> public virtual PropertyDescriptorCollection Sort() { return new PropertyDescriptorCollection(this.properties, this.propCount, this.namedSort, this.comparer); } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> public virtual PropertyDescriptorCollection Sort(string[] names) { return new PropertyDescriptorCollection(this.properties, this.propCount, names, this.comparer); } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer) { return new PropertyDescriptorCollection(this.properties, this.propCount, names, comparer); } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection, using the specified IComparer to compare, /// the PropertyDescriptors contained in the collection. /// </para> /// </devdoc> public virtual PropertyDescriptorCollection Sort(IComparer comparer) { return new PropertyDescriptorCollection(this.properties, this.propCount, this.namedSort, comparer); } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> protected void InternalSort(string[] names) { if (properties == null || properties.Length == 0) { return; } this.InternalSort(this.comparer); if (names != null && names.Length > 0) { ArrayList propArrayList = new ArrayList(properties); int foundCount = 0; int propCount = properties.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < propCount; j++) { PropertyDescriptor currentProp = (PropertyDescriptor)propArrayList[j]; // Found a matching property. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentProp != null && currentProp.Name.Equals(names[i])) { properties[foundCount++] = currentProp; propArrayList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < propCount; i++) { if (propArrayList[i] != null) { properties[foundCount++] = (PropertyDescriptor)propArrayList[i]; } } Debug.Assert(foundCount == propCount, "We did not completely fill our property array"); } } /// <devdoc> /// <para> /// Sorts the members of this PropertyDescriptorCollection using the specified IComparer. /// </para> /// </devdoc> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(properties, sorter); } } /// <devdoc> /// <para> /// Gets an enumerator for this <see cref='System.ComponentModel.PropertyDescriptorCollection'/>. /// </para> /// </devdoc> public virtual IEnumerator GetEnumerator() { EnsurePropsOwned(); // we can only return an enumerator on the props we actually have... if (properties.Length != this.propCount) { PropertyDescriptor[] enumProps = new PropertyDescriptor[propCount]; Array.Copy(properties, 0, enumProps, 0, propCount); return enumProps.GetEnumerator(); } return properties.GetEnumerator(); } /// <internalonly/> int ICollection.Count { get { return Count; } } /// <internalonly/> bool ICollection.IsSynchronized { get { return false; } } /// <internalonly/> object ICollection.SyncRoot { get { return null; } } /// <internalonly/> void IDictionary.Add(object key, object value) { PropertyDescriptor newProp = value as PropertyDescriptor; if (newProp == null) { throw new ArgumentException("value"); } Add(newProp); } /// <internalonly/> void IDictionary.Clear() { Clear(); } /// <internalonly/> bool IDictionary.Contains(object key) { if (key is string) { return this[(string)key] != null; } return false; } /// <internalonly/> IDictionaryEnumerator IDictionary.GetEnumerator() { return new PropertyDescriptorEnumerator(this); } /// <internalonly/> bool IDictionary.IsFixedSize { get { return readOnly; } } /// <internalonly/> bool IDictionary.IsReadOnly { get { return readOnly; } } /// <internalonly/> object IDictionary.this[object key] { get { if (key is string) { return this[(string)key]; } return null; } set { if (readOnly) { throw new NotSupportedException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException("value"); } int index = -1; if (key is int) { index = (int)key; if (index < 0 || index >= propCount) { throw new IndexOutOfRangeException(); } } else if (key is string) { for (int i = 0; i < propCount; i++) { if (properties[i].Name.Equals((string)key)) { index = i; break; } } } else { throw new ArgumentException("key"); } if (index == -1) { Add((PropertyDescriptor)value); } else { EnsurePropsOwned(); properties[index] = (PropertyDescriptor)value; if (cachedFoundProperties != null && key is string) { cachedFoundProperties[key] = value; } } } } /// <internalonly/> ICollection IDictionary.Keys { get { string[] keys = new string[propCount]; for (int i = 0; i < propCount ;i++) { keys[i] = properties[i].Name; } return keys; } } /// <internalonly/> ICollection IDictionary.Values { get { // we can only return an enumerator on the props we actually have... // if (properties.Length != this.propCount) { PropertyDescriptor[] newProps = new PropertyDescriptor[propCount]; Array.Copy(properties, 0, newProps, 0, propCount); return newProps; } else { return (ICollection)properties.Clone(); } } } /// <internalonly/> void IDictionary.Remove(object key) { if (key is string) { PropertyDescriptor pd = this[(string)key]; if (pd != null) { ((IList)this).Remove(pd); } } } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <internalonly/> int IList.Add(object value) { return Add((PropertyDescriptor)value); } /// <internalonly/> void IList.Clear() { Clear(); } /// <internalonly/> bool IList.Contains(object value) { return Contains((PropertyDescriptor)value); } /// <internalonly/> int IList.IndexOf(object value) { return IndexOf((PropertyDescriptor)value); } /// <internalonly/> void IList.Insert(int index, object value) { Insert(index, (PropertyDescriptor)value); } /// <internalonly/> bool IList.IsReadOnly { get { return readOnly; } } /// <internalonly/> bool IList.IsFixedSize { get { return readOnly; } } /// <internalonly/> void IList.Remove(object value) { Remove((PropertyDescriptor)value); } /// <internalonly/> void IList.RemoveAt(int index) { RemoveAt(index); } /// <internalonly/> object IList.this[int index] { get { return this[index]; } set { if (readOnly) { throw new NotSupportedException(); } if (index >= propCount) { throw new IndexOutOfRangeException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException("value"); } EnsurePropsOwned(); properties[index] = (PropertyDescriptor)value; } } private class PropertyDescriptorEnumerator : IDictionaryEnumerator { private PropertyDescriptorCollection owner; private int index = -1; public PropertyDescriptorEnumerator(PropertyDescriptorCollection owner) { this.owner = owner; } public object Current { get{ return Entry; } } public DictionaryEntry Entry { get { PropertyDescriptor curProp = owner[index]; return new DictionaryEntry(curProp.Name, curProp); } } public object Key { get { return owner[index].Name; } } public object Value { get { return owner[index].Name; } } public bool MoveNext() { if (index < (owner.Count - 1)) { index++; return true; } return false; } public void Reset() { index = -1; } } } }
// 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.Runtime.CompilerServices; class ApplicationException : Exception { public ApplicationException(string message) : base(message) { } } namespace Test { public abstract class Base { public abstract string AbstractFinal(); public abstract string AbstractOverrideFinal(); public abstract string AbstractOverrideOverride(); public abstract string AbstractOverrideNil(); public virtual string VirtualFinal() { return "Base.VirtualFinal"; } public virtual string VirtualNilFinal() { return "Base.VirtualNilFinal"; } public virtual string VirtualOverrideFinal() { return "Base.VirtualOverrideFinal"; } public virtual string VirtualNilOverride() { return "Base.VirtualNilOverride"; } public virtual string VirtualNilNil() { return "Base.VirtualNilNil"; } public virtual string VirtualOverrideOverride() { return "Base.VirtualOverrideOverride"; } public virtual string VirtualOverrideNil() { return "Base.VirtualOverrideNil"; } } public class Child : Base { public sealed override string AbstractFinal() { return "Child.AbstractFinal"; } public string CallAbstractFinal() { return AbstractFinal(); } public override string AbstractOverrideFinal() { return "Child.AbstractOverrideFinal"; } public override string AbstractOverrideOverride() { return "Child.AbstractOverrideOverride"; } public override string AbstractOverrideNil() { return "Child.AbstractOverrideNil"; } public string CallAbstractOverrideNil() { return AbstractOverrideNil(); } public sealed override string VirtualFinal() { return "Child.VirtualFinal"; } public string CallVirtualFinal() { return VirtualFinal(); } public override string VirtualOverrideFinal() { return "Child.VirtualOverrideFinal"; } public override string VirtualOverrideOverride() { return "Child.VirtualOverrideOverride"; } public override string VirtualOverrideNil() { return "Child.VirtualOverrideNil"; } public string CallVirtualOverrideNil() { return VirtualOverrideNil(); } } public class GrandChild : Child { public sealed override string AbstractOverrideFinal() { return "GrandChild.AbstractOverrideFinal"; } public string CallAbstractOverrideFinal() { return AbstractOverrideFinal(); } public override string AbstractOverrideOverride() { return "GrandChild.AbstractOverrideOverride"; } public string CallAbstractOverrideOverride() { return AbstractOverrideOverride(); } public sealed override string VirtualNilFinal() { return "GrandChild.VirtualNilFinal"; } public string CallVirtualNilFinal() { return VirtualNilFinal(); } public sealed override string VirtualOverrideFinal() { return "GrandChild.VirtualOverrideFinal"; } public string CallVirtualOverrideFinal() { return VirtualOverrideFinal(); } public override string VirtualOverrideOverride() { return "GrandChild.VirtualOverrideOverride"; } public string CallVirtualOverrideOverride() { return VirtualOverrideOverride(); } public override string VirtualNilOverride() { return "GrandChild.VirtualNilOverride"; } public string CallVirtualNilOverride() { return VirtualNilOverride(); } public void TestGrandChild() { Console.WriteLine("Call from inside GrandChild"); Assert.AreEqual("Child.AbstractFinal", CallAbstractFinal()); Assert.AreEqual("GrandChild.AbstractOverrideFinal", CallAbstractOverrideFinal()); Assert.AreEqual("GrandChild.AbstractOverrideOverride", CallAbstractOverrideOverride()); Assert.AreEqual("Child.AbstractOverrideNil", CallAbstractOverrideNil()); Assert.AreEqual("Child.VirtualFinal", CallVirtualFinal()); Assert.AreEqual("GrandChild.VirtualOverrideFinal", CallVirtualOverrideFinal()); Assert.AreEqual("GrandChild.VirtualOverrideOverride", CallVirtualOverrideOverride()); Assert.AreEqual("Child.VirtualOverrideNil", CallVirtualOverrideNil()); } } public static class Program { public static void CallFromInsideGrandChild() { GrandChild child = new GrandChild(); child.TestGrandChild(); } public static int Main(string[] args) { try { CallFromInsideGrandChild(); Console.WriteLine("Test SUCCESS"); return 100; } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("Test FAILED"); return 101; } } } public static class Assert { public static void AreEqual(string left, string right) { if (String.IsNullOrEmpty(left)) throw new ArgumentNullException("left"); if (string.IsNullOrEmpty(right)) throw new ArgumentNullException("right"); if (left != right) { string message = String.Format("[[{0}]] != [[{1}]]", left, right); throw new ApplicationException(message); } } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface ISalesTerritoryHistoryOriginalData : ISchemaBaseOriginalData { System.DateTime StartDate { get; } System.DateTime? EndDate { get; } string rowguid { get; } } public partial class SalesTerritoryHistory : OGM<SalesTerritoryHistory, SalesTerritoryHistory.SalesTerritoryHistoryData, System.String>, ISchemaBase, INeo4jBase, ISalesTerritoryHistoryOriginalData { #region Initialize static SalesTerritoryHistory() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, SalesTerritoryHistory> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.SalesTerritoryHistoryAlias, IWhereQuery> query) { q.SalesTerritoryHistoryAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.SalesTerritoryHistory.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"SalesTerritoryHistory => StartDate : {this.StartDate}, EndDate : {this.EndDate?.ToString() ?? "null"}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new SalesTerritoryHistoryData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.StartDate == null) throw new PersistenceException(string.Format("Cannot save SalesTerritoryHistory with key '{0}' because the StartDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save SalesTerritoryHistory with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save SalesTerritoryHistory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class SalesTerritoryHistoryData : Data<System.String> { public SalesTerritoryHistoryData() { } public SalesTerritoryHistoryData(SalesTerritoryHistoryData data) { StartDate = data.StartDate; EndDate = data.EndDate; rowguid = data.rowguid; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "SalesTerritoryHistory"; } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("StartDate", Conversion<System.DateTime, long>.Convert(StartDate)); dictionary.Add("EndDate", Conversion<System.DateTime?, long?>.Convert(EndDate)); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("StartDate", out value)) StartDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("EndDate", out value)) EndDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface ISalesTerritoryHistory public System.DateTime StartDate { get; set; } public System.DateTime? EndDate { get; set; } public string rowguid { get; set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface ISalesTerritoryHistory public System.DateTime StartDate { get { LazyGet(); return InnerData.StartDate; } set { if (LazySet(Members.StartDate, InnerData.StartDate, value)) InnerData.StartDate = value; } } public System.DateTime? EndDate { get { LazyGet(); return InnerData.EndDate; } set { if (LazySet(Members.EndDate, InnerData.EndDate, value)) InnerData.EndDate = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static SalesTerritoryHistoryMembers members = null; public static SalesTerritoryHistoryMembers Members { get { if (members == null) { lock (typeof(SalesTerritoryHistory)) { if (members == null) members = new SalesTerritoryHistoryMembers(); } } return members; } } public class SalesTerritoryHistoryMembers { internal SalesTerritoryHistoryMembers() { } #region Members for interface ISalesTerritoryHistory public Property StartDate { get; } = Datastore.AdventureWorks.Model.Entities["SalesTerritoryHistory"].Properties["StartDate"]; public Property EndDate { get; } = Datastore.AdventureWorks.Model.Entities["SalesTerritoryHistory"].Properties["EndDate"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["SalesTerritoryHistory"].Properties["rowguid"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static SalesTerritoryHistoryFullTextMembers fullTextMembers = null; public static SalesTerritoryHistoryFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(SalesTerritoryHistory)) { if (fullTextMembers == null) fullTextMembers = new SalesTerritoryHistoryFullTextMembers(); } } return fullTextMembers; } } public class SalesTerritoryHistoryFullTextMembers { internal SalesTerritoryHistoryFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(SalesTerritoryHistory)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["SalesTerritoryHistory"]; } } return entity; } private static SalesTerritoryHistoryEvents events = null; public static SalesTerritoryHistoryEvents Events { get { if (events == null) { lock (typeof(SalesTerritoryHistory)) { if (events == null) events = new SalesTerritoryHistoryEvents(); } } return events; } } public class SalesTerritoryHistoryEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<SalesTerritoryHistory, EntityEventArgs> onNew; public event EventHandler<SalesTerritoryHistory, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<SalesTerritoryHistory, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<SalesTerritoryHistory, EntityEventArgs> onDelete; public event EventHandler<SalesTerritoryHistory, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<SalesTerritoryHistory, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<SalesTerritoryHistory, EntityEventArgs> onSave; public event EventHandler<SalesTerritoryHistory, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<SalesTerritoryHistory, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnStartDate private static bool onStartDateIsRegistered = false; private static EventHandler<SalesTerritoryHistory, PropertyEventArgs> onStartDate; public static event EventHandler<SalesTerritoryHistory, PropertyEventArgs> OnStartDate { add { lock (typeof(OnPropertyChange)) { if (!onStartDateIsRegistered) { Members.StartDate.Events.OnChange -= onStartDateProxy; Members.StartDate.Events.OnChange += onStartDateProxy; onStartDateIsRegistered = true; } onStartDate += value; } } remove { lock (typeof(OnPropertyChange)) { onStartDate -= value; if (onStartDate == null && onStartDateIsRegistered) { Members.StartDate.Events.OnChange -= onStartDateProxy; onStartDateIsRegistered = false; } } } } private static void onStartDateProxy(object sender, PropertyEventArgs args) { EventHandler<SalesTerritoryHistory, PropertyEventArgs> handler = onStartDate; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnEndDate private static bool onEndDateIsRegistered = false; private static EventHandler<SalesTerritoryHistory, PropertyEventArgs> onEndDate; public static event EventHandler<SalesTerritoryHistory, PropertyEventArgs> OnEndDate { add { lock (typeof(OnPropertyChange)) { if (!onEndDateIsRegistered) { Members.EndDate.Events.OnChange -= onEndDateProxy; Members.EndDate.Events.OnChange += onEndDateProxy; onEndDateIsRegistered = true; } onEndDate += value; } } remove { lock (typeof(OnPropertyChange)) { onEndDate -= value; if (onEndDate == null && onEndDateIsRegistered) { Members.EndDate.Events.OnChange -= onEndDateProxy; onEndDateIsRegistered = false; } } } } private static void onEndDateProxy(object sender, PropertyEventArgs args) { EventHandler<SalesTerritoryHistory, PropertyEventArgs> handler = onEndDate; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<SalesTerritoryHistory, PropertyEventArgs> onrowguid; public static event EventHandler<SalesTerritoryHistory, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<SalesTerritoryHistory, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<SalesTerritoryHistory, PropertyEventArgs> onModifiedDate; public static event EventHandler<SalesTerritoryHistory, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<SalesTerritoryHistory, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<SalesTerritoryHistory, PropertyEventArgs> onUid; public static event EventHandler<SalesTerritoryHistory, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<SalesTerritoryHistory, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((SalesTerritoryHistory)sender, args); } #endregion } #endregion } #endregion #region ISalesTerritoryHistoryOriginalData public ISalesTerritoryHistoryOriginalData OriginalVersion { get { return this; } } #region Members for interface ISalesTerritoryHistory System.DateTime ISalesTerritoryHistoryOriginalData.StartDate { get { return OriginalData.StartDate; } } System.DateTime? ISalesTerritoryHistoryOriginalData.EndDate { get { return OriginalData.EndDate; } } string ISalesTerritoryHistoryOriginalData.rowguid { get { return OriginalData.rowguid; } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
// ---------------------------------------------------------------------------- // KingTomato Scripts // ---------------------------------------------------------------------------- $Script::Description = "Handles GUI events for NewOpts pages."; function King::GUI::Init(%gui) { if ($GUI::Building) { echo("GUI::Init -> Builder mode enabled, exiting"); if (!$GUI::Screen) { setScript($GUI::Dialog); guiTools(); $GUI::Screen = true; } return; } // General options if (%gui == General) { } // Settings else if (%gui == Settings) { if ($pref::shadowDetailMask) Control::setValue(KTSettings::Shadows, true); else Control::setValue(KTSettings::Shadows, false); } // Acronyms else if (%gui == Acronyms) { %combo = "KTAcronyms::AcronymList"; %acronym = "KTAcronyms::Acronym"; %meaning = "KTAcronyms::Meaning"; // Load Acronyms List FGCombo::Clear(%combo); for (%a = 1; (%acro = $Acronym::List::[%a]) != ""; %a++) { %means = $Acronym::List[%acro]; FGCombo::addEntry(%combo, %acro @ " - " @ %means, %a); if (%a == 1) FGCombo::setSelected(%combo, %a); } King::GUI::Combo(%gui, %combo); } // Friends List else if (%gui == Friends) { %combo = "KTFriends::FriendsList"; %name = "KTFriends::Name"; // Load friends FGCombo::Clear(%combo); for (%f = 1; (%friend = $KingPref::Friends[%f]) != ""; %f++) { FGCombo::addEntry(%combo, %friend, %f); if (%f == 1) FGCombo::setSelected(%combo, 1); } Control::setText(%name, ""); } // HUDs else if (%gui == HUDs) { %combo = "KTHuds::HudList"; %x = "KTHuds::PositionX"; %y = "KTHuds::PositionY"; %width = "KTHuds::SizeWidth"; %huds = 0; // Load list of _my_ huds FGCombo::Clear(%combo); for (%h = 0; %h < $HUD::numHUDs; %h++) { %hud = $HUD::Name[%h]; // a hud associated with my pack if (String::findSubStr(%hud, "kt_") == 0) { %name = String::getSubStr(%hud, 3, 99); FGCombo::addEntry(%combo, %name @ " Hud", %h); if (%huds++ == 1) FGCombo::setSelected(%combo, %h); } } King::GUI::Combo(%gui, %combo); } } function King::GUI::Button(%gui, %button) { if ($GUI::Building) { echo("GUI::Button -> Builder mode enabled, exiting"); return; } // General options if (%gui == General) { } // Acronyms else if (%gui == Acronyms) { %combo = "KTAcronyms::AcronymList"; %help = "KTAcronyms::HelpText"; %update = false; Control::setText(%help,""); // Add/Update Button if (%button == Update) { if ($GUI::Acronym::Text == "") Control::setText(%help, "Missing Field: Acronym"); else if ($GUI::Acronym::Meaning == "") Control::setText(%help, "Missing Field: Meaning"); else { Acronym::Add($GUI::Acronym::Text, $GUI::Acronym::Meaning); %update = true; } $GUI::Acronym::LastClick = -1; } // Delete Button else if (%button == Delete) { %sel = FGCombo::getSelected(%combo); if (%sel != -1) { if ($GUI::Acronym::LastClick == %sel) { %acro = $Acronym::List::[%sel]; Acronym::Remove(%acro); %update = true; $GUI::Acronym::LastClick = -1; } else { Control::setText(%help, "Delete this acronym? (click again to confirm)"); $GUI::Acronym::LastClick = %sel; } } else Control::setText(%help, "There is no entry to delete."); } if (%update) King::GUI::Init(Acronyms); } // Friends List else if (%gui == Friends) { %combo = "KTFriends::FriendsList"; %help = "KTFriends::HelpText"; %name = "KTFriends::Name"; %update = false; Control::setValue(%help,""); // Add button if (%button == Add) { if ($GUI::Friends::Name != "") { %found = false; for (%f = 1; (%friend = $KingPref::Friends[%f]) != ""; %f++) if (%friend == $GUI::Friends::Name) { %friend = true; break; } if (!%found) { $KingPref::Friends[%f] = $GUI::Friends::Name; Control::setText(%name, ""); %update = true; } else Control::setValue(%help, "<f1>That person is already in your friend list."); } else Control::setValue(%help, "<f1>Fill in the name field."); $GUI::Friends::LastClick = -1; } // delete button else if (%button == Delete) { %sel = FGCombo::getSelected(%combo); if (%sel != -1) { if ($GUI::Friends::LastClick == %sel) { for (%n = %sel; $KingPref::Friends[%n] != ""; %n++) $KingPref::Friends[%n] = $KingPref::Friends[(%n+1)]; %update = true; $GUI::Friends::LastClick = -1; } else { Control::setValue(%help, "<f1>Delete this acronym?\n(click again to confirm)"); $GUI::Friends::LastClick = %sel; } } else Control::setValue(%help, "<f1>There is no entry to delete."); } if (%update) King::GUI::Init(Friends); } // HUDs else if (%gui == HUDs) { %combo = "KTHuds::HudList"; %x = "KTHuds::PositionX"; %y = "KTHuds::PositionY"; %w = "KTHuds::SizeWidth"; // Make Changes if (%button == Apply) { %sel = FGCombo::getSelected(%combo); if (%sel != -1) { %hud = $HUD::Name[%sel]; %name = String::GetSubStr(%hud, 3, 99); $King::HUD[%name, X] = $GUI::HUDs::PosX; $King::HUD[%name, Y] = $GUI::HUDs::PosY; $King::HUD[%name, W] = $GUI::HUDs::Width; $King::HUD[%name, On] = $GUI::HUDs::HUDEnabled; %newPos = sprintf("%1 %2 %3 %4", $King::HUD[%name, X], $King::HUD[%name, Y], $King::HUD[%name, W], HUD::Height(%hud)); HUD::Move(%hud, %newPos); HUD::Display(%hud, $King::HUD[%name, On]); } } // Revert hud settings back to default else if (%button == Undo) { King::HUI::Combo(%gui, %combo); } } } function King::GUI::Combo(%gui, %combo) { if ($GUI::Building) { echo("GUI::Close -> Builder mode enabled, exiting"); return; } // General options if (%gui == General) { } // Acronyms else if (%gui == Acronyms) { %acronym = "KTAcronyms::Acronym"; %meaning = "KTAcronyms::Meaning"; %sel = FGCombo::getSelected(%combo); if (%sel != -1) { %acro = $Acronym::List::[%sel]; %means = $Acronym::List[%acro]; } $GUI::Acronym::Text = %acro; $GUI::Acronym::Meaning = %means; Control::setText(%acronym, %acro); Control::setText(%meaning, %means); } // Friends List else if (%gui == Friends) { } // HUDs else if (%gui == HUDs) { %e = "KTHuds::HUDEnabled"; %x = "KTHuds::PositionX"; %y = "KTHuds::PositionY"; %w = "KTHuds::SizeWidth"; %sel = FGCombo::getSelected(%combo); if (%sel != -1) { %hud = $HUD::Name[%sel]; %name = String::GetSubStr(%hud, 3, 99); %enabled = $King::HUD[%name, On]; %left = $King::HUD[%name, X]; %top = $King::HUD[%name, Y]; %width = $King::HUD[%name, W]; } else %enabled = false; Control::SetVisible(KTHuds::SizeText, (%width != "")); Control::SetVisible(KTHuds::SizeWidthText, (%width != "")); Control::SetVisible(KTHuds::SizeWidth, (%width != "")); $GUI::HUDs::PosX = %left; $GUI::HUDs::PosY = %top; $GUI::HUDs::Width = %width; $GUI::HUDs::HUDEnabled = %enabled; Control::setValue(%x, %left); Control::setValue(%y, %top); Control::setValue(%w, %width); Control::setValue(%e, %enabled); } } function King::GUI::Close(%gui) { if ($GUI::Building) { echo("GUI::Close -> Builder mode enabled, exiting"); return; } // General options if (%gui == General) { if ($KingPref::Logging) $Console::LogMode = 1; else $Console::LogMode = 0; } // Settings else if (%gui == Settings) { if (Control::getValue(KTSettings::Shadows)) { $pref::shadowDetailMask = "1"; $pref::shadowDetailScale = "1.000000"; } else { $pref::shadowDetailMask = "0"; $pref::shadowDetailScale = "0.000000"; } } // Acronyms else if (%gui == Acronyms) { } // Friends List else if (%gui == Friends) { } // HUDs else if (%gui == HUDs) { } }