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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Use these APIs to manage Azure CDN resources through the Azure Resource /// Manager. You must make sure that requests made to these resources are /// secure. /// </summary> public partial class CdnManagementClient : ServiceClient<CdnManagementClient>, ICdnManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Azure Subscription ID. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Version of the API to be used with the client request. Current version is /// 2016-10-02. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IProfilesOperations. /// </summary> public virtual IProfilesOperations Profiles { get; private set; } /// <summary> /// Gets the IEndpointsOperations. /// </summary> public virtual IEndpointsOperations Endpoints { get; private set; } /// <summary> /// Gets the IOriginsOperations. /// </summary> public virtual IOriginsOperations Origins { get; private set; } /// <summary> /// Gets the ICustomDomainsOperations. /// </summary> public virtual ICustomDomainsOperations CustomDomains { get; private set; } /// <summary> /// Gets the IEdgeNodesOperations. /// </summary> public virtual IEdgeNodesOperations EdgeNodes { get; private set; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CdnManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CdnManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CdnManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CdnManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Profiles = new ProfilesOperations(this); Endpoints = new EndpointsOperations(this); Origins = new OriginsOperations(this); CustomDomains = new CustomDomainsOperations(this); EdgeNodes = new EdgeNodesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-10-02"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Check the availability of a resource name. This is needed for resources /// where name is globally unique, such as a CDN endpoint. /// </summary> /// <param name='name'> /// The resource name to validate. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CheckNameAvailabilityOutput>> CheckNameAvailabilityWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } CheckNameAvailabilityInput checkNameAvailabilityInput = new CheckNameAvailabilityInput(); if (name != null) { checkNameAvailabilityInput.Name = name; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("checkNameAvailabilityInput", checkNameAvailabilityInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/checkNameAvailability").ToString(); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(checkNameAvailabilityInput != null) { _requestContent = SafeJsonConvert.SerializeObject(checkNameAvailabilityInput, 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 (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CheckNameAvailabilityOutput>(); _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<CheckNameAvailabilityOutput>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Check the quota and actual usage of the CDN profiles under the given /// subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceUsage>>> ListResourceUsageWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListResourceUsage", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceUsage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ResourceUsage>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the available CDN REST API operations. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Operation>>> ListOperationsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListOperations", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/operations").ToString(); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new 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 (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Operation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Check the quota and actual usage of the CDN profiles under the given /// 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="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceUsage>>> ListResourceUsageNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListResourceUsageNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceUsage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ResourceUsage>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the available CDN REST API operations. /// </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="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Operation>>> ListOperationsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListOperationsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Operation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.Threading; using System.Runtime.Serialization; namespace Microsoft.SPOT.Debugger { public class PortBooter { public delegate void ProgressEventHandler(SRecordFile.Block bl,int offset,bool fLast); public class Report { public enum State { Banner, EntryPoint, ACK, NACK, CRC, Noise, } public State type; public uint address; public string line; } private Engine m_eng; private event ProgressEventHandler m_eventProgress; private ArrayList m_reports = new ArrayList(); private AutoResetEvent m_ready = new AutoResetEvent(false); private byte[] m_buffer = new byte[1024]; private int m_pos = 0; private byte m_lastEOL = 0; private Regex m_re_Banner1 = new Regex("PortBooter v[0-9]+\\.[0-9]+", RegexOptions.None); private Regex m_re_Banner2 = new Regex("Waiting .* for hex upload", RegexOptions.IgnoreCase); private Regex m_re_EntryPoint = new Regex("X start ([0-9a-fA-F]*)", RegexOptions.IgnoreCase); private Regex m_re_ACK = new Regex("X ack ([0-9a-fA-F]*)", RegexOptions.IgnoreCase); private Regex m_re_NACK = new Regex("X nack ([0-9a-fA-F]*)", RegexOptions.IgnoreCase); private Regex m_re_CRC = new Regex("X crc ([0-9a-fA-F]*)", RegexOptions.IgnoreCase); public PortBooter(Engine eng) { m_eng = eng; } public void Dispose() { Stop(); } #if PortBooter_RAWDUMP Stream m_stream; #endif public void Start() { #if PortBooter_RAWDUMP m_stream = new FileStream( @"RawDump.bin", FileMode.Create ); #endif m_eng.WaitForPort(); m_eng.ConfigureXonXoff(true); m_eng.OnNoise += new NoiseEventHandler(this.Process); } public void Stop() { m_eng.OnNoise -= new NoiseEventHandler(this.Process); m_eng.ConfigureXonXoff(false); #if PortBooter_RAWDUMP if(m_stream != null) { m_stream.Flush(); m_stream.Close(); } #endif } public event ProgressEventHandler OnProgress { add { m_eventProgress += value; } remove { m_eventProgress -= value; } } private void Process(byte[] buf, int offset, int count) { #if PortBooter_RAWDUMP if(m_stream != null) { m_stream.Write( buf, offset, count ); m_stream.Flush(); } #endif while(count-- > 0) { byte c = buf[offset++]; m_buffer[m_pos] = c; if(c == '\n' || c == '\r') { if(m_pos == 0) { if(m_lastEOL == '\r' && c == '\n') { m_lastEOL = c; continue; } } m_lastEOL = c; string line = Encoding.UTF8.GetString(m_buffer, 0, m_pos); Report r = null; if(m_re_Banner1.IsMatch(line) || m_re_Banner2.IsMatch(line)) { r = new Report(); r.type = Report.State.Banner; } else if(m_re_EntryPoint.IsMatch(line)) { GroupCollection group = m_re_EntryPoint.Match(line).Groups; r = new Report(); r.type = Report.State.EntryPoint; r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber); } else if(m_re_ACK.IsMatch(line)) { GroupCollection group = m_re_ACK.Match(line).Groups; r = new Report(); r.type = Report.State.ACK; r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber); } else if(m_re_NACK.IsMatch(line)) { GroupCollection group = m_re_NACK.Match(line).Groups; r = new Report(); r.type = Report.State.NACK; r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber); } else if(m_re_CRC.IsMatch(line)) { GroupCollection group = m_re_CRC.Match(line).Groups; r = new Report(); r.type = Report.State.CRC; r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber); } else { r = new Report(); r.type = Report.State.Noise; r.line = line; } if(r != null) { lock(m_reports) { m_reports.Add(r); m_ready.Set(); } } m_pos = 0; } else if(++m_pos == m_buffer.Length) { m_pos = 0; } } } public bool WaitBanner(int tries, int timeout) { while(tries > 0) { Report r = GetReport(timeout); if(r == null) { m_eng.InjectMessage("Synching...\r\n"); } else if(r.type == Report.State.Noise) { m_eng.InjectMessage("{0}", r.line); } else if(r.type == Report.State.Banner) { for(int i = 0; i < 10; i++) { SendString("ZENFLASH\r\n"); Thread.Sleep(20); } return true; } } return false; } public bool Program(ArrayList blocks) { ProgressEventHandler eventProgress = m_eventProgress; const int maxpipeline = 4; const int pipelineSize = 128; int[] outstanding = new int[maxpipeline]; for(int i = 0; i < maxpipeline; i++) { outstanding[i] = -1; } foreach(SRecordFile.Block bl in blocks) { byte[] buf = bl.data.ToArray(); uint address = bl.address; int offset = 0; int count = buf.Length; int pipeline = maxpipeline; while(offset < count) { int pending = 0; for(int i = 0; i < pipeline; i++) { if(outstanding[i] == -1) { int pos = offset + i * pipelineSize; int len = System.Math.Min(count - pos, pipelineSize); if(len <= 0) break; WriteMemory((uint)(address + pos), buf, pos, len); outstanding[i] = i; } pending++; } if(pending == 0) break; Report r = GetReport(5000); if(r == null) { for(int i = 0; i < pipeline; i++) { outstanding[i] = -1; } } else if(r.type == Report.State.Noise) { m_eng.InjectMessage("{0}", r.line); } else if(r.type == Report.State.CRC) { int restart = 0; for(int i = 0; i < pipeline; i++) { if(r.address == address + offset + i * pipelineSize) { restart = i; break; } } int pos = outstanding[restart]; for(int i = restart; i < pipeline; i++) { outstanding[i] = -1; } // // Throttle back pipelining in case of errors. // if(pipeline > pos + 1 && pipeline > 1) { pipeline--; } } else if(r.address == address + offset) { if(r.type == Report.State.ACK) { offset += pipelineSize; for(int i = 1; i < pipeline; i++) { outstanding[i - 1] = outstanding[i]; } outstanding[pipeline - 1] = -1; if(eventProgress != null) eventProgress(bl, System.Math.Min(count, offset), false); } else if(r.type == Report.State.NACK) { } } } if(eventProgress != null) eventProgress(bl, count, true); } return true; } public Report GetReport(int timeout) { while(true) { lock(m_reports) { if(m_reports.Count > 0) { Report r = (Report)m_reports[0]; m_reports.RemoveAt(0); return r; } } if(timeout <= 0) return null; DateTime start = DateTime.Now; m_ready.WaitOne(timeout, false); TimeSpan diff = DateTime.Now - start; timeout -= (int)diff.TotalMilliseconds; } } public void SendString(string s) { SendBuffer(Encoding.UTF8.GetBytes(s)); } public void Execute(uint address) { WriteMemory(address, null, 0, 0); } public void WriteMemory(uint address, byte[] data, int offset, int count) { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream, Encoding.Unicode); uint crc = 0; crc -= address; crc -= (ushort)count; for(int i = 0; i < count; i++) { crc -= data[offset + i]; } writer.Write((byte)'X'); writer.Write((uint)address); writer.Write((ushort)count); writer.Write((uint)crc); if(count > 0) { writer.Write(data, offset, count); } writer.Flush(); SendBuffer(stream.ToArray()); } void SendBuffer(byte[] buf) { m_eng.SendRawBuffer(buf); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetSettings1 { public partial class IndicesGetSettings1YamlTests { public class IndicesGetSettings110BasicYamlBase : YamlTestsBase { public IndicesGetSettings110BasicYamlBase() : base() { //do indices.create _body = new { settings= new { number_of_shards= "5", number_of_replicas= "1" } }; this.Do(()=> _client.IndicesCreate("test_1", _body)); //do indices.create _body = new { settings= new { number_of_shards= "3", number_of_replicas= "0" } }; this.Do(()=> _client.IndicesCreate("test_2", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSettings2Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetSettings2Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_1.settings.index.number_of_replicas: this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //match _response.test_2.settings.index.number_of_replicas: this.IsMatch(_response.test_2.settings.index.number_of_replicas, 0); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettings3Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettings3Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_1.settings.index.number_of_replicas: this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettingsAll4Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettingsAll4Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1", "_all")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_1.settings.index.number_of_replicas: this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettings5Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettings5Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1", "*")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_1.settings.index.number_of_replicas: this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettingsName6Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettingsName6Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_shards")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettingsNameName7Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettingsNameName7Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_shards,index.number_of_replicas")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_1.settings.index.number_of_replicas: this.IsMatch(_response.test_1.settings.index.number_of_replicas, 1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettingsName8Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettingsName8Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1", "index.number_of_s*")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSettingsName9Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetSettingsName9Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll("index.number_of_shards")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2.settings.index.number_of_replicas; this.IsFalse(_response.test_2.settings.index.number_of_replicas); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllSettingsName10Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetAllSettingsName10Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("_all", "index.number_of_shards")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2.settings.index.number_of_replicas; this.IsFalse(_response.test_2.settings.index.number_of_replicas); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSettingsName11Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetSettingsName11Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("*", "index.number_of_shards")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2.settings.index.number_of_replicas; this.IsFalse(_response.test_2.settings.index.number_of_replicas); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexIndexSettingsName12Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexIndexSettingsName12Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_1,test_2", "index.number_of_shards")); //match _response.test_1.settings.index.number_of_shards: this.IsMatch(_response.test_1.settings.index.number_of_shards, 5); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //is_false _response.test_1.settings.index.number_of_replicas; this.IsFalse(_response.test_1.settings.index.number_of_replicas); //is_false _response.test_2.settings.index.number_of_replicas; this.IsFalse(_response.test_2.settings.index.number_of_replicas); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexSettingsName13Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetIndexSettingsName13Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("*2", "index.number_of_shards")); //match _response.test_2.settings.index.number_of_shards: this.IsMatch(_response.test_2.settings.index.number_of_shards, 3); //is_false _response.test_1; this.IsFalse(_response.test_1); //is_false _response.test_2.settings.index.number_of_replicas; this.IsFalse(_response.test_2.settings.index.number_of_replicas); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSettingsWithLocalFlag14Tests : IndicesGetSettings110BasicYamlBase { [Test] public void GetSettingsWithLocalFlag14Test() { //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll(nv=>nv .AddQueryString("local", @"true") )); //is_true _response.test_1; this.IsTrue(_response.test_1); //is_true _response.test_2; this.IsTrue(_response.test_2); } } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using IdentityServervNextDemo.EntityFrameworkCore; namespace IdentityServervNextDemo.Migrations { [DbContext(typeof(IdentityServervNextDemoDbContext))] [Migration("20170424115119_Initial_Migrations")] partial class Initial_Migrations { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.1") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<int?>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("IdentityServervNextDemo.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("IdentityServervNextDemo.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Roles.Role", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Users.User", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServervNextDemo.MultiTenancy.Tenant", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
// 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.IO.PortsTests; using System.Linq; using System.Text; using System.Threading; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Ports.Tests { public class Read_byte_int_int_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random bytes to receive for parity testing private const int numRndBytesPairty = 8; //The number of characters to read at a time for parity testing private const int numBytesReadPairty = 2; //The number of random bytes to receive for BytesToRead testing private const int numRndBytesToRead = 16; //When we test Read and do not care about actually reading anything we must still //create an byte array to pass into the method the following is the size of the //byte array used in this situation private const int defaultByteArraySize = 1; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(); Thread t = new Thread(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); } catch (TimeoutException) { } //Wait for the thread to finish while (t.IsAlive) Thread.Sleep(50); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(); byte[] xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); if (com2.IsOpen) com2.Close(); } } [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(); VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1), Encoding.UTF32); } [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(); VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndBytesPairty]; byte[] expectedBytes = new byte[numRndBytesPairty]; byte[] actualBytes = new byte[numRndBytesPairty + 1]; int waitTime; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } // Create a parity error on the last byte bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); // Set the last expected byte to be the ParityReplace Byte expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); waitTime = 0; while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) { Thread.Sleep(50); waitTime += 50; } com1.Read(actualBytes, 0, actualBytes.Length); // Compare the chars that were written with the ones we expected to read Assert.Equal(expectedBytes, actualBytes.Take(expectedBytes.Length).ToArray()); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); // Clear the parity error on the last byte expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2); } } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_1_Buffer_Size() { VerifyBytesToRead(1, Encoding.Unicode); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_Equal_Buffer_Size() { VerifyBytesToRead(numRndBytesToRead, new UTF8Encoding()); } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; // Warm up read method Assert.Throws<TimeoutException>(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numRndBytesPairty]; byte[] expectedBytes = new byte[numRndBytesPairty]; byte expectedByte; // Generate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } if (-1 == parityReplace) { // If parityReplace is -1 and we should just use the default value expectedByte = com1.ParityReplace; } else if ('\0' == parityReplace) { // If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedByte = bytesToWrite[parityErrorIndex]; } else { // Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedByte = (byte)parityReplace; } // Create an parity error by setting the highest order bit to true bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); expectedBytes[parityErrorIndex] = expectedByte; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Encoding = encoding; com1.Open(); com2.Open(); VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty); } } private void VerifyBytesToRead(int numBytesRead) { VerifyBytesToRead(numBytesRead, new ASCIIEncoding()); } private void VerifyBytesToRead(int numBytesRead, Encoding encoding) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numRndBytesToRead]; // Generate random characters for (int i = 0; i < bytesToWrite.Length; i++) { bytesToWrite[i] = (byte)rndGen.Next(0, 256); } Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); com1.Encoding = encoding; com1.Open(); com2.Open(); VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) { byte[] rcvBuffer = new byte[rcvBufferSize]; byte[] buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; bytesToRead = com1.BytesToRead; while (true) { int bytesRead; try { bytesRead = com1.Read(rcvBuffer, 0, rcvBufferSize); } catch (TimeoutException) { break; } //While their are more characters to be read if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; } // Compare the bytes that were written with the ones we expected to read Assert.Equal(expectedBytes, buffer); } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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 Microsoft.PackageManagement.Providers.Internal.Bootstrap { using System; using System.Collections.Generic; using System.Linq; using PackageManagement.Internal.Packaging; using PackageManagement.Internal.Utility.Extensions; internal class Feed : Swid { [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Feed(BootstrapRequest request, Swidtag swidtag) : base(request, swidtag) { } internal Feed(BootstrapRequest request, IEnumerable<Link> mirrors) : base(request, mirrors) { } internal Feed(BootstrapRequest request, IEnumerable<Uri> mirrors) : base(request, mirrors) { } /// <summary> /// Follows the feed to find all the *declared latest* versions of packgaes /// </summary> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query() { if (!IsValid) { return Enumerable.Empty<Package>(); } // first get all the packages that are marked as the latest version. var packages = Packages.Select(packageGroup => new Package(_request, packageGroup.Where(link => link.Attributes[Iso19770_2.Discovery.Latest].IsTrue()))); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query()); // We do not follow to other feeds to find more, because declared latest packages should be in this feed (or a supplemental). return packages.Concat(morePackages); } /// <summary> /// Follows the feed to find all versions of package matching 'name' /// </summary> /// <param name="name">the name or partial name of a package to find</param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name) { if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)).Where(package => package.IsValid && package.Name.EqualsIgnoreCase(name)); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name)); // let's search child feeds that declare that the name of the package in the feed matches the given name var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name]))).SelectMany(feed => new Feed(_request, feed).Query(name)); // and search child feeds that the name would be in their range. var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } /// <summary> /// Follows the feed to find the specific version of a package matching 'name' /// </summary> /// <param name="name"></param> /// <param name="version"></param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name, string version) { if (string.IsNullOrEmpty(version)) { return Query(name); } if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name and version var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)) .Where(package => package.IsValid && package.Name.EqualsIgnoreCase(name) && SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, version) == 0); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name, version)); // let's search child feeds that declare that the name of the package in the feed matches the given name // and the version is either in the specified range of the link, or there is no specified version. var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => { if (name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name])) { var minVer = link.Attributes[Iso19770_2.Discovery.MinimumVersion]; if (!string.IsNullOrEmpty(minVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, minVer, version) > 0) { // the minimum version in the feed is greater than the specified version. return false; } } var maxVer = link.Attributes[Iso19770_2.Discovery.MaximumVersion]; if (!string.IsNullOrEmpty(maxVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, version, maxVer) > 0) { // the given version is greater than the maximum version in the feed. return false; } } return true; } return false; })).SelectMany(feed => new Feed(_request, feed).Query(name, version)); // and search child feeds that the name would be in their range. // (version matches have to wait till we Query() that feed, since name ranges and version ranges shouldn't be on the same link.) var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name, version)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } /// <summary> /// Follows the feed to find the all versions of a package matching 'name', in the given range /// </summary> /// <param name="name"></param> /// <param name="minimumVersion"></param> /// <param name="maximumVersion"></param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name, string minimumVersion, string maximumVersion) { if (string.IsNullOrEmpty(minimumVersion) && string.IsNullOrEmpty(maximumVersion)) { return Query(name); } if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name and version var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)).Where(package => { if (package.IsValid && package.Name.EqualsIgnoreCase(name)) { if (!string.IsNullOrWhiteSpace(minimumVersion)) { if (SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, minimumVersion) < 0) { // a minimum version was specified, but the package version is less than the specified minimumversion. return false; } } if (!string.IsNullOrWhiteSpace(maximumVersion)) { if (SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, maximumVersion) > 0) { // a maximum version was specified, but the package version is more than the specified maximumversion. return false; } } // the version is in the range asked for. return true; } // not a valid package, or incorrect name. return false; }); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name, minimumVersion, maximumVersion)); // let's search child feeds that declare that the name of the package in the feed matches the given name // and the version is either in the specified range of the link, or there is no specified version. var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => { if (name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name])) { // first, ensure that the requested miniumum version is lower than the maximum version found in the feed. var maxVer = link.Attributes[Iso19770_2.Discovery.MaximumVersion]; if (!string.IsNullOrEmpty(maxVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, minimumVersion, maxVer) <= 0) { // the minimum version is greater than the maximum version in the feed. return false; } } // and then ensure that the requested maximum version is greater than the miniumum version found in the feed. var minVer = link.Attributes[Iso19770_2.Discovery.MinimumVersion]; if (!string.IsNullOrEmpty(minVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, maximumVersion, minVer) >= 0) { // the maximum version less than the minimum version in the feed. return false; } } return true; } return false; })).SelectMany(feed => new Feed(_request, feed).Query(name, minimumVersion, maximumVersion)); // and search child feeds that the name would be in their range. // (version matches have to wait till we Query() that feed, since name ranges and version ranges shouldn't be on the same link.) var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name, minimumVersion, maximumVersion)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using OrchardCore.Admin; using OrchardCore.AdminMenu.Services; using OrchardCore.AdminMenu.ViewModels; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Navigation; using OrchardCore.Security.Permissions; namespace OrchardCore.AdminMenu.Controllers { [Admin] public class NodeController : Controller { private readonly IAuthorizationService _authorizationService; private readonly IDisplayManager<MenuItem> _displayManager; private readonly IEnumerable<IAdminNodeProviderFactory> _factories; private readonly IAdminMenuService _adminMenuService; private readonly INotifier _notifier; private readonly IHtmlLocalizer H; private readonly IUpdateModelAccessor _updateModelAccessor; public NodeController( IAuthorizationService authorizationService, IEnumerable<IPermissionProvider> permissionProviders, IDisplayManager<MenuItem> displayManager, IEnumerable<IAdminNodeProviderFactory> factories, IAdminMenuService adminMenuService, IHtmlLocalizer<NodeController> htmlLocalizer, INotifier notifier, IUpdateModelAccessor updateModelAccessor) { _displayManager = displayManager; _factories = factories; _adminMenuService = adminMenuService; _authorizationService = authorizationService; _notifier = notifier; _updateModelAccessor = updateModelAccessor; H = htmlLocalizer; } public async Task<IActionResult> List(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.GetAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id); if (adminMenu == null) { return NotFound(); } return View(await BuildDisplayViewModel(adminMenu)); } private async Task<AdminNodeListViewModel> BuildDisplayViewModel(Models.AdminMenu tree) { var thumbnails = new Dictionary<string, dynamic>(); foreach (var factory in _factories) { var treeNode = factory.Create(); dynamic thumbnail = await _displayManager.BuildDisplayAsync(treeNode, _updateModelAccessor.ModelUpdater, "TreeThumbnail"); thumbnail.TreeNode = treeNode; thumbnails.Add(factory.Name, thumbnail); } var model = new AdminNodeListViewModel { AdminMenu = tree, Thumbnails = thumbnails, }; return model; } public async Task<IActionResult> Create(string id, string type) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.GetAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id); if (adminMenu == null) { return NotFound(); } var treeNode = _factories.FirstOrDefault(x => x.Name == type)?.Create(); if (treeNode == null) { return NotFound(); } var model = new AdminNodeEditViewModel { AdminMenuId = id, AdminNode = treeNode, AdminNodeId = treeNode.UniqueId, AdminNodeType = type, Editor = await _displayManager.BuildEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: true) }; return View(model); } [HttpPost] public async Task<IActionResult> Create(AdminNodeEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.AdminMenuId); if (adminMenu == null) { return NotFound(); } var treeNode = _factories.FirstOrDefault(x => x.Name == model.AdminNodeType)?.Create(); if (treeNode == null) { return NotFound(); } dynamic editor = await _displayManager.UpdateEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: true); editor.TreeNode = treeNode; if (ModelState.IsValid) { treeNode.UniqueId = model.AdminNodeId; adminMenu.MenuItems.Add(treeNode); await _adminMenuService.SaveAsync(adminMenu); await _notifier.SuccessAsync(H["Admin node added successfully."]); return RedirectToAction(nameof(List), new { id = model.AdminMenuId }); } model.Editor = editor; // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(string id, string treeNodeId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.GetAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id); if (adminMenu == null) { return NotFound(); } var treeNode = adminMenu.GetMenuItemById(treeNodeId); if (treeNode == null) { return NotFound(); } var model = new AdminNodeEditViewModel { AdminMenuId = id, AdminNode = treeNode, AdminNodeId = treeNode.UniqueId, AdminNodeType = treeNode.GetType().Name, Priority = treeNode.Priority, Position = treeNode.Position, Editor = await _displayManager.BuildEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: false) }; model.Editor.TreeNode = treeNode; return View(model); } [HttpPost] public async Task<IActionResult> Edit(AdminNodeEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.AdminMenuId); if (adminMenu == null) { return NotFound(); } var treeNode = adminMenu.GetMenuItemById(model.AdminNodeId); if (treeNode == null) { return NotFound(); } var editor = await _displayManager.UpdateEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: false); if (ModelState.IsValid) { treeNode.Priority = model.Priority; treeNode.Position = model.Position; await _adminMenuService.SaveAsync(adminMenu); await _notifier.SuccessAsync(H["Admin node updated successfully."]); return RedirectToAction(nameof(List), new { id = model.AdminMenuId }); } await _notifier.ErrorAsync(H["The admin node has validation errors."]); model.Editor = editor; // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Delete(string id, string treeNodeId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id); if (adminMenu == null) { return NotFound(); } var treeNode = adminMenu.GetMenuItemById(treeNodeId); if (treeNode == null) { return NotFound(); } if (adminMenu.RemoveMenuItem(treeNode) == false) { return new StatusCodeResult(500); } await _adminMenuService.SaveAsync(adminMenu); await _notifier.SuccessAsync(H["Admin node deleted successfully."]); return RedirectToAction(nameof(List), new { id }); } [HttpPost] public async Task<IActionResult> Toggle(string id, string treeNodeId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id); if (adminMenu == null) { return NotFound(); } var treeNode = adminMenu.GetMenuItemById(treeNodeId); if (treeNode == null) { return NotFound(); } treeNode.Enabled = !treeNode.Enabled; await _adminMenuService.SaveAsync(adminMenu); await _notifier.SuccessAsync(H["Admin node toggled successfully."]); return RedirectToAction(nameof(List), new { id = id }); } [HttpPost] public async Task<IActionResult> MoveNode(string treeId, string nodeToMoveId, string destinationNodeId, int position) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu)) { return Forbid(); } var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync(); var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, treeId); if ((adminMenu == null) || (adminMenu.MenuItems == null)) { return NotFound(); } var nodeToMove = adminMenu.GetMenuItemById(nodeToMoveId); if (nodeToMove == null) { return NotFound(); } var destinationNode = adminMenu.GetMenuItemById(destinationNodeId); // don't check for null. When null the item will be moved to the root. if (adminMenu.RemoveMenuItem(nodeToMove) == false) { return StatusCode(500); } if (adminMenu.InsertMenuItemAt(nodeToMove, destinationNode, position) == false) { return StatusCode(500); } await _adminMenuService.SaveAsync(adminMenu); return Ok(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; namespace BulletSharp { public class BulletWorldImporter : WorldImporter { public BulletWorldImporter(DynamicsWorld world) : base(world) { } public BulletWorldImporter() : base(null) { } public bool ConvertAllObjects(BulletFile file) { _shapeMap.Clear(); _bodyMap.Clear(); foreach (byte[] bvhData in file.Bvhs) { OptimizedBvh bvh = CreateOptimizedBvh(); if ((file.Flags & FileFlags.DoublePrecision) != 0) { throw new NotImplementedException(); } else { // QuantizedBvhData is parsed in C++, so we need to actually fix pointers GCHandle bvhDataHandle = GCHandle.Alloc(bvhData, GCHandleType.Pinned); IntPtr bvhDataPinnedPtr = bvhDataHandle.AddrOfPinnedObject(); IntPtr contiguousNodesHandlePtr = IntPtr.Zero; IntPtr quantizedContiguousNodesHandlePtr = IntPtr.Zero; IntPtr subTreeInfoHandlePtr = IntPtr.Zero; using (MemoryStream stream = new MemoryStream(bvhData)) { using (BulletReader reader = new BulletReader(stream)) { long contiguousNodesPtr = reader.ReadPtr(QuantizedBvhFloatData.Offset("ContiguousNodesPtr")); long quantizedContiguousNodesPtr = reader.ReadPtr(QuantizedBvhFloatData.Offset("QuantizedContiguousNodesPtr")); long subTreeInfoPtr = reader.ReadPtr(QuantizedBvhFloatData.Offset("SubTreeInfoPtr")); using (BulletWriter writer = new BulletWriter(stream)) { if (contiguousNodesPtr != 0) { GCHandle contiguousNodesHandle = GCHandle.Alloc(file.LibPointers[contiguousNodesPtr], GCHandleType.Pinned); contiguousNodesHandlePtr = GCHandle.ToIntPtr(contiguousNodesHandle); stream.Position = QuantizedBvhFloatData.Offset("ContiguousNodesPtr"); writer.Write(contiguousNodesHandle.AddrOfPinnedObject()); } if (quantizedContiguousNodesPtr != 0) { GCHandle quantizedContiguousNodesHandle = GCHandle.Alloc(file.LibPointers[quantizedContiguousNodesPtr], GCHandleType.Pinned); quantizedContiguousNodesHandlePtr = GCHandle.ToIntPtr(quantizedContiguousNodesHandle); stream.Position = QuantizedBvhFloatData.Offset("QuantizedContiguousNodesPtr"); writer.Write(quantizedContiguousNodesHandle.AddrOfPinnedObject()); } if (subTreeInfoPtr != 0) { GCHandle subTreeInfoHandle = GCHandle.Alloc(file.LibPointers[subTreeInfoPtr], GCHandleType.Pinned); subTreeInfoHandlePtr = GCHandle.ToIntPtr(subTreeInfoHandle); stream.Position = QuantizedBvhFloatData.Offset("SubTreeInfoPtr"); writer.Write(subTreeInfoHandle.AddrOfPinnedObject()); } } } } bvh.DeSerializeFloat(bvhDataPinnedPtr); bvhDataHandle.Free(); if (contiguousNodesHandlePtr != IntPtr.Zero) { GCHandle.FromIntPtr(contiguousNodesHandlePtr).Free(); } if (quantizedContiguousNodesHandlePtr != IntPtr.Zero) { GCHandle.FromIntPtr(quantizedContiguousNodesHandlePtr).Free(); } if (subTreeInfoHandlePtr != IntPtr.Zero) { GCHandle.FromIntPtr(subTreeInfoHandlePtr).Free(); } } foreach (KeyValuePair<long, byte[]> lib in file.LibPointers) { if (lib.Value == bvhData) { _bvhMap.Add(lib.Key, bvh); break; } } } foreach (byte[] shapeData in file.CollisionShapes) { CollisionShape shape = ConvertCollisionShape(shapeData, file.LibPointers); if (shape != null) { foreach (KeyValuePair<long, byte[]> lib in file.LibPointers) { if (lib.Value == shapeData) { _shapeMap.Add(lib.Key, shape); break; } } using (MemoryStream stream = new MemoryStream(shapeData, false)) { using (BulletReader reader = new BulletReader(stream)) { long namePtr = reader.ReadPtr(CollisionShapeFloatData.Offset("Name")); if (namePtr != 0) { byte[] nameData = file.LibPointers[namePtr]; int length = Array.IndexOf(nameData, (byte)0); string name = System.Text.Encoding.ASCII.GetString(nameData, 0, length); _objectNameMap.Add(shape, name); _nameShapeMap.Add(name, shape); } } } } } foreach (byte[] solverInfoData in file.DynamicsWorldInfo) { if ((file.Flags & FileFlags.DoublePrecision) != 0) { //throw new NotImplementedException(); } else { //throw new NotImplementedException(); } } foreach (byte[] bodyData in file.RigidBodies) { if ((file.Flags & FileFlags.DoublePrecision) != 0) { throw new NotImplementedException(); } else { ConvertRigidBodyFloat(bodyData, file.LibPointers); } } foreach (byte[] colObjData in file.CollisionObjects) { if ((file.Flags & FileFlags.DoublePrecision) != 0) { throw new NotImplementedException(); } else { using (MemoryStream colObjStream = new MemoryStream(colObjData, false)) { using (BulletReader colObjReader = new BulletReader(colObjStream)) { long shapePtr = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("CollisionShape")); CollisionShape shape = _shapeMap[shapePtr]; Math.Matrix startTransform = colObjReader.ReadMatrix(CollisionObjectFloatData.Offset("WorldTransform")); long namePtr = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("Name")); string name = null; if (namePtr != 0) { byte[] nameData = file.FindLibPointer(namePtr); int length = Array.IndexOf(nameData, (byte)0); name = System.Text.Encoding.ASCII.GetString(nameData, 0, length); } CollisionObject colObj = CreateCollisionObject(ref startTransform, shape, name); _bodyMap.Add(colObjData, colObj); } } } } foreach (byte[] constraintData in file.Constraints) { MemoryStream stream = new MemoryStream(constraintData, false); using (BulletReader reader = new BulletReader(stream)) { long collisionObjectAPtr = reader.ReadPtr(TypedConstraintFloatData.Offset("RigidBodyA")); long collisionObjectBPtr = reader.ReadPtr(TypedConstraintFloatData.Offset("RigidBodyB")); RigidBody a = null, b = null; if (collisionObjectAPtr != 0) { if (!file.LibPointers.ContainsKey(collisionObjectAPtr)) { a = TypedConstraint.GetFixedBody(); } else { byte[] coData = file.LibPointers[collisionObjectAPtr]; a = RigidBody.Upcast(_bodyMap[coData]); if (a == null) { a = TypedConstraint.GetFixedBody(); } } } if (collisionObjectBPtr != 0) { if (!file.LibPointers.ContainsKey(collisionObjectBPtr)) { b = TypedConstraint.GetFixedBody(); } else { byte[] coData = file.LibPointers[collisionObjectBPtr]; b = RigidBody.Upcast(_bodyMap[coData]); if (b == null) { b = TypedConstraint.GetFixedBody(); } } } if (a == null && b == null) { stream.Dispose(); continue; } if ((file.Flags & FileFlags.DoublePrecision) != 0) { throw new NotImplementedException(); } else { ConvertConstraintFloat(a, b, constraintData, file.Version, file.LibPointers); } } stream.Dispose(); } return true; } public bool LoadFile(string fileName, string preSwapFilenameOut) { BulletFile bulletFile = new BulletFile(fileName); bool result = LoadFileFromMemory(bulletFile); //now you could save the file in 'native' format using //bulletFile.WriteFile("native.bullet"); if (result) { if (preSwapFilenameOut != null) { bulletFile.PreSwap(); //bulletFile.WriteFile(preSwapFilenameOut); } } return result; } public bool LoadFile(string fileName) { return LoadFile(fileName, null); } public bool LoadFileFromMemory(byte[] memoryBuffer, int len) { BulletFile bulletFile = new BulletFile(memoryBuffer, len); return LoadFileFromMemory(bulletFile); } public bool LoadFileFromMemory(BulletFile bulletFile) { if ((bulletFile.Flags & FileFlags.OK) != FileFlags.OK) { return false; } bulletFile.Parse(_verboseMode); if ((_verboseMode & FileVerboseMode.DumpChunks) == FileVerboseMode.DumpChunks) { //bulletFile.DumpChunks(bulletFile->FileDna); } return ConvertAllObjects(bulletFile); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Diagnostics.Contracts; namespace Microsoft.Glee.Optimization { public enum Relation { LessOrEqual, Equal, GreaterOrEqual } public enum Status { Unknown, Infeasible, Unbounded, Optimal, Feasible, //this status is assigned after successfull stage one FloatingPointError } /// <summary> /// Solves the general linear program but always looking for the minimum /// </summary> [ContractClass(typeof(LinearProgramInterfaceContracts))] public interface LinearProgramInterface { /// <summary> /// When looking for the Quadratical Program minimum both variables of some variable pairs cannot appear in the basis together /// </summary> int[] ForbiddenPairs { set; get; } double Epsilon { get; /*set;*/ } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] double[] FeasibleSolution(); /// <summary> /// returns an optimal solution: that is a solution where cx is minimal /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] double[] MinimalSolution(); /// <summary> /// Call this method only in case when the program is infeasible. /// The linear program will be transformed to the form Ax=b. /// The corresponding quadratic program is /// minimize||Ax-b||, x>=0 /// where ||.|| is the Euclidean norm. /// The solution always exists. /// Null is returned however if the matrix is too big /// </summary> /// <returns>approximation to solution</returns> double[] LeastSquareSolution(); ///<summary> /// set the cost function /// </summary> /// <param name="costs">the objective vector</param> void InitCosts(double[] costsParam); /// <summary> /// If one just happens to know the i-th variable value it can be set /// </summary> /// <param name="i"></param> /// <param name="val"></param> void SetVariable(int i, double val); /// <summary> /// adds a constraint: the coeffiecents should not be very close to zero or too huge. /// If it is the case, as one can scale for example the whole programm to zero, /// then such coefficient will be treated az zeros. We are talking here about the numbers /// with absolute values less than 1.0E-8 /// </summary> /// <param name="coeff">the constraint coefficents</param> /// <param name="relation">could be 'less or equal', equal or 'greater or equal'</param> /// <param name="rightSide">right side of the constraint</param> void AddConstraint(double[] coeff, Relation relation, double rightSide); /// <summary> /// Solves the linear program, minimizing, by going through stages one and two /// </summary> void Minimize(); /// <summary> /// calculate the cost of the solution /// </summary> double GetMinimalValue(); Status Status { get; set; } /// <summary> /// Add a constraint from below on the variable /// </summary> /// <param name="var"></param> /// <param name="l"></param> void LimitVariableFromBelow(int var, double l); /// <summary> /// Add a constraint from above on the variable /// </summary> /// <param name="var"></param> /// <param name="l"></param> void LimitVariableFromAbove(int var, double l); double EpsilonForArtificials{get;set;} double EpsilonForReducedCosts { get;set;} } [ContractClassFor(typeof(LinearProgramInterface))] abstract class LinearProgramInterfaceContracts : LinearProgramInterface { #region LinearProgramInterface Members int[] LinearProgramInterface.ForbiddenPairs { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } double LinearProgramInterface.Epsilon { get { throw new NotImplementedException(); } } double[] LinearProgramInterface.FeasibleSolution() { throw new NotImplementedException(); } double[] LinearProgramInterface.MinimalSolution() { throw new NotImplementedException(); } double[] LinearProgramInterface.LeastSquareSolution() { Contract.Requires(((LinearProgramInterface)this).Status == Status.Infeasible); return default(double[]); } void LinearProgramInterface.InitCosts(double[] costsParam) { throw new NotImplementedException(); } void LinearProgramInterface.SetVariable(int i, double val) { throw new NotImplementedException(); } void LinearProgramInterface.AddConstraint(double[] coeff, Relation relation, double rightSide) { throw new NotImplementedException(); } void LinearProgramInterface.Minimize() { throw new NotImplementedException(); } double LinearProgramInterface.GetMinimalValue() { throw new NotImplementedException(); } Status LinearProgramInterface.Status { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } void LinearProgramInterface.LimitVariableFromBelow(int var, double l) { throw new NotImplementedException(); } void LinearProgramInterface.LimitVariableFromAbove(int var, double l) { throw new NotImplementedException(); } double LinearProgramInterface.EpsilonForArtificials { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } double LinearProgramInterface.EpsilonForReducedCosts { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.Cryptography; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; using Neo.VM; using Neo.VM.Types; using Neo.Wallets; using System.Linq; using System.Security.Cryptography; namespace Neo.SmartContract.Framework.UnitTests.Services.Neo { [TestClass] public class CryptoTest { private KeyPair _key = null; private TestEngine _engine; [TestInitialize] public void Init() { _engine = new TestEngine(TriggerType.Application, new Transaction() { Attributes = new TransactionAttribute[0], Script = new byte[0], Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, Witnesses = new Witness[0], NetworkFee = 1, Nonce = 2, SystemFee = 3, ValidUntilBlock = 4, Version = 5 }); _engine.AddEntryScript("./TestClasses/Contract_Crypto.cs"); _key = GenerateKey(32); } public static KeyPair GenerateKey(int privateKeyLength) { byte[] privateKey = new byte[privateKeyLength]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(privateKey); } return new KeyPair(privateKey); } [TestMethod] public void Test_SHA256() { _engine.Reset(); var result = _engine.ExecuteTestCaseStandard("SHA256", "asd"); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(VM.Types.ByteString)); Assert.AreEqual("688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6", item.GetSpan().ToArray().ToHexString()); } [TestMethod] public void Test_RIPEMD160() { _engine.Reset(); var str = System.Text.Encoding.Default.GetBytes("hello world"); var result = _engine.ExecuteTestCaseStandard("RIPEMD160", str); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(VM.Types.ByteString)); Assert.AreEqual("98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f", item.GetSpan().ToArray().ToHexString()); } [TestMethod] public void Test_HASH160() { _engine.Reset(); var str = System.Text.Encoding.Default.GetBytes("hello world"); var result = _engine.ExecuteTestCaseStandard("hash160", str); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(VM.Types.ByteString)); Assert.AreEqual("d7d5ee7824ff93f94c3055af9382c86c68b5ca92", item.GetSpan().ToArray().ToHexString()); } [TestMethod] public void Test_HASH256() { _engine.Reset(); var str = System.Text.Encoding.Default.GetBytes("hello world"); var result = _engine.ExecuteTestCaseStandard("hash256", str); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(VM.Types.ByteString)); Assert.AreEqual("bc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423", item.GetSpan().ToArray().ToHexString()); } [TestMethod] public void Test_VerifySignature() { byte[] signature = Crypto.Sign(_engine.ScriptContainer.GetHashData(), _key.PrivateKey, _key.PublicKey.EncodePoint(false).Skip(1).ToArray()); // False _engine.Reset(); var result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignature", new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)), new VM.Types.ByteString(new byte[64])); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsFalse(item.GetBoolean()); // True _engine.Reset(); result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignature", new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)), new VM.Types.ByteString(signature)); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsTrue(item.GetBoolean()); } [TestMethod] public void Test_VerifySignatures() { byte[] signature = Crypto.Sign(_engine.ScriptContainer.GetHashData(), _key.PrivateKey, _key.PublicKey.EncodePoint(false).Skip(1).ToArray()); // False _engine.Reset(); var result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignatures", new Array(new StackItem[] { new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)) }), new Array(new StackItem[] { new VM.Types.ByteString(new byte[64]) })); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsFalse(item.GetBoolean()); // True _engine.Reset(); result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignatures", new Array(new StackItem[] { new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)) }), new Array(new StackItem[] { new VM.Types.ByteString(signature) })); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsTrue(item.GetBoolean()); } [TestMethod] public void Test_VerifySignaturesWithMessage() { byte[] signature = Crypto.Sign(_engine.ScriptContainer.GetHashData(), _key.PrivateKey, _key.PublicKey.EncodePoint(false).Skip(1).ToArray()); // False _engine.Reset(); var result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignaturesWithMessage", new VM.Types.ByteString(new byte[0]), new Array(new StackItem[] { new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)) }), new Array(new StackItem[] { new VM.Types.ByteString(new byte[64]) })); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsFalse(item.GetBoolean()); // True _engine.Reset(); result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignaturesWithMessage", new VM.Types.ByteString(_engine.ScriptContainer.GetHashData()), new Array(new StackItem[] { new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)) }), new Array(new StackItem[] { new VM.Types.ByteString(signature) })); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsTrue(item.GetBoolean()); } [TestMethod] public void Test_VerifySignatureWithMessage() { byte[] signature = Crypto.Sign(_engine.ScriptContainer.GetHashData(), _key.PrivateKey, _key.PublicKey.EncodePoint(false).Skip(1).ToArray()); // False _engine.Reset(); var result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignatureWithMessage", new VM.Types.ByteString(new byte[0]), new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)), new VM.Types.ByteString(signature)); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); var item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsFalse(item.GetBoolean()); // True _engine.Reset(); result = _engine.ExecuteTestCaseStandard("secp256r1VerifySignatureWithMessage", new VM.Types.ByteString(_engine.ScriptContainer.GetHashData()), new VM.Types.ByteString(_key.PublicKey.EncodePoint(true)), new VM.Types.ByteString(signature)); Assert.AreEqual(VMState.HALT, _engine.State); Assert.AreEqual(1, result.Count); item = result.Pop(); Assert.IsInstanceOfType(item, typeof(Boolean)); Assert.IsTrue(item.GetBoolean()); } } }
// // TrackEditorDialog.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Gtk; using Hyena.Gui; using Hyena.Widgets; using Banshee.Base; using Banshee.Kernel; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration.Schema; using Banshee.Widgets; using Banshee.Gui.Dialogs; using Banshee.Collection.Gui; using Hyena.Data; using Selection=Hyena.Collections.Selection; namespace Banshee.Gui.TrackEditor { public class TrackEditorDialog : BansheeDialog { public delegate void EditorTrackOperationClosure (EditorTrackInfo track); private VBox main_vbox; private Frame header_image_frame; private Image header_image; private Label header_title_label; private Label header_artist_label; private Label header_album_label; private Label edit_notif_label; private object tooltip_host; private DateTime dialog_launch_datetime = DateTime.Now; private Notebook notebook; public Notebook Notebook { get { return notebook; } } private Button nav_backward_button; private Button nav_forward_button; private PulsingButton sync_all_button; private EditorMode mode; internal EditorMode Mode { get { return mode; } } private bool readonly_tabs = false; private List<ITrackEditorPage> pages = new List<ITrackEditorPage> (); public event EventHandler Navigated; private TrackEditorDialog (TrackListModel model, Selection selection, EditorMode mode) : this (model, selection, mode, false) { } private TrackEditorDialog (TrackListModel model, Selection selection, EditorMode mode, bool readonlyTabs) : base ( mode == EditorMode.Edit ? Catalog.GetString ("Track Editor") : Catalog.GetString ("Track Properties")) { readonly_tabs = readonlyTabs; this.mode = mode; LoadTrackModel (model, selection); if (mode == EditorMode.Edit || readonly_tabs) { WidthRequest = 525; if (mode == EditorMode.Edit) { AddStockButton (Stock.Cancel, ResponseType.Cancel); AddStockButton (Stock.Save, ResponseType.Ok); } } else { SetSizeRequest (400, 500); } if (mode == EditorMode.View) { AddStockButton (Stock.Close, ResponseType.Close, true); } tooltip_host = TooltipSetter.CreateHost (); AddNavigationButtons (); main_vbox = new VBox (); main_vbox.Spacing = 12; main_vbox.BorderWidth = 0; main_vbox.Show (); VBox.PackStart (main_vbox, true, true, 0); BuildHeader (); BuildNotebook (); BuildFooter (); LoadModifiers (); LoadTrackToEditor (); HideSingleTab (); } #region UI Building private void AddNavigationButtons () { if (TrackCount <= 1) { return; } nav_backward_button = new Button (Stock.GoBack); nav_backward_button.UseStock = true; nav_backward_button.Clicked += delegate { NavigateBackward (); }; nav_backward_button.Show (); TooltipSetter.Set (tooltip_host, nav_backward_button, Catalog.GetString ("Show the previous track")); nav_forward_button = new Button (Stock.GoForward); nav_forward_button.UseStock = true; nav_forward_button.Clicked += delegate { NavigateForward (); }; nav_forward_button.Show (); TooltipSetter.Set (tooltip_host, nav_forward_button, Catalog.GetString ("Show the next track")); ActionArea.PackStart (nav_backward_button, false, false, 0); ActionArea.PackStart (nav_forward_button, false, false, 0); ActionArea.SetChildSecondary (nav_backward_button, true); ActionArea.SetChildSecondary (nav_forward_button, true); } private void BuildHeader () { Table header = new Table (3, 3, false); header.ColumnSpacing = 5; header_image_frame = new Frame (); header_image = new Image (); header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.Add ( CoverArtEditor.For (header_image, (x, y) => true, () => CurrentTrack, () => LoadCoverArt (CurrentTrack) ) ); header.Attach (header_image_frame, 0, 1, 0, 3, AttachOptions.Fill, AttachOptions.Expand, 0, 0); AddHeaderRow (header, 0, Catalog.GetString ("Title:"), out header_title_label); AddHeaderRow (header, 1, Catalog.GetString ("Artist:"), out header_artist_label); AddHeaderRow (header, 2, Catalog.GetString ("Album:"), out header_album_label); header.ShowAll (); main_vbox.PackStart (header, false, false, 0); } private TrackInfo CurrentTrack { get { return TrackCount == 0 ? null : GetTrack (CurrentTrackIndex); } } private void AddHeaderRow (Table header, uint row, string title, out Label label) { Label title_label = new Label (); title_label.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (title)); title_label.Xalign = 0.0f; header.Attach (title_label, 1, 2, row, row + 1, AttachOptions.Fill, AttachOptions.Expand, 0, 0); label = new Label (); label.Xalign = 0.0f; label.Ellipsize = Pango.EllipsizeMode.End; header.Attach (label, 2, 3, row, row + 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Expand, 0, 0); } private void BuildNotebook () { notebook = new Notebook (); notebook.Show (); Gtk.Widget page_to_focus = null; foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/NotebookPage")) { try { ITrackEditorPage page = (ITrackEditorPage)node.CreateInstance (); bool show = false; if (mode == EditorMode.Edit && (page.PageType != PageType.ViewOnly)) { show = true; } else if (mode == EditorMode.View) { if (readonly_tabs) { show = page.PageType != PageType.EditOnly; } else { show = page.PageType == PageType.View || page.PageType == PageType.ViewOnly; } } if (show) { if (page is StatisticsPage && mode == EditorMode.View) { page_to_focus = (StatisticsPage)page; } pages.Add (page); page.Initialize (this); page.Widget.Show (); } } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize NotebookPage extension node. Ensure it implements ITrackEditorPage.", e); } } pages.Sort (delegate (ITrackEditorPage a, ITrackEditorPage b) { return a.Order.CompareTo (b.Order); }); foreach (ITrackEditorPage page in pages) { Container container = page.Widget as Container; if (container == null) { VBox box = new VBox (); box.PackStart (page.Widget, true, true, 0); container = box; } container.BorderWidth = 12; notebook.AppendPage (container, page.TabWidget == null ? new Label (page.Title) : page.TabWidget); } main_vbox.PackStart (notebook, true, true, 0); if (page_to_focus != null) { notebook.CurrentPage = notebook.PageNum (page_to_focus); } } private void BuildFooter () { if (mode == EditorMode.View || TrackCount < 2) { return; } HBox button_box = new HBox (); button_box.Spacing = 6; if (TrackCount > 1) { sync_all_button = new PulsingButton (); sync_all_button.FocusInEvent += delegate { ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StartPulsing (); }); }; sync_all_button.FocusOutEvent += delegate { if (sync_all_button.State == StateType.Prelight) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StopPulsing (); }); }; sync_all_button.StateChanged += delegate { if (sync_all_button.HasFocus) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { if (sync_all_button.State == StateType.Prelight) { button.StartPulsing (); } else { button.StopPulsing (); } }); }; sync_all_button.Clicked += delegate { InvokeFieldSync (); }; Alignment alignment = new Alignment (0.5f, 0.5f, 0.0f, 0.0f); HBox box = new HBox (); box.Spacing = 2; box.PackStart (new Image (Stock.Copy, IconSize.Button), false, false, 0); box.PackStart (new Label (Catalog.GetString ("Sync all field _values")), false, false, 0); alignment.Add (box); sync_all_button.Add (alignment); TooltipSetter.Set (tooltip_host, sync_all_button, Catalog.GetString ( "Apply the values of all common fields set for this track to all of the tracks selected in this editor")); button_box.PackStart (sync_all_button, false, false, 0); foreach (Widget child in ActionArea.Children) { child.SizeAllocated += OnActionAreaChildSizeAllocated; } edit_notif_label = new Label (); edit_notif_label.Xalign = 1.0f; button_box.PackEnd (edit_notif_label, false, false, 0); } main_vbox.PackStart (button_box, false, false, 0); button_box.ShowAll (); } private void LoadModifiers () { foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/Modifier")) { try { ITrackEditorModifier mod = (ITrackEditorModifier)node.CreateInstance (); mod.Modify (this); } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize TrackEditor/Modifier extension node. Ensure it implements ITrackEditorModifier.", e); } } } public void ForeachWidget<T> (WidgetAction<T> action) where T : class { for (int i = 0; i < notebook.NPages; i++) { GtkUtilities.ForeachWidget (notebook.GetNthPage (i) as Container, action); } } private void InvokeFieldSync () { for (int i = 0; i < notebook.NPages; i++) { var field_page = notebook.GetNthPage (i) as FieldPage; if (field_page != null) { foreach (var slot in field_page.FieldSlots) { if (slot.Sync != null && (slot.SyncButton == null || slot.SyncButton.Sensitive)) { slot.Sync (); } } } } } private int action_area_children_allocated = 0; private void OnActionAreaChildSizeAllocated (object o, SizeAllocatedArgs args) { Widget [] children = ActionArea.Children; if (++action_area_children_allocated != children.Length) { return; } sync_all_button.WidthRequest = Math.Max (sync_all_button.Allocation.Width, (children[1].Allocation.X + children[1].Allocation.Width) - children[0].Allocation.X - 1); } #endregion #region Track Model/Changes API private CachedList<DatabaseTrackInfo> db_selection; private List<TrackInfo> memory_selection; private Dictionary<TrackInfo, EditorTrackInfo> edit_map = new Dictionary<TrackInfo, EditorTrackInfo> (); private int current_track_index; protected void LoadTrackModel (TrackListModel model, Selection selection) { DatabaseTrackListModel db_model = model as DatabaseTrackListModel; if (db_model != null) { db_selection = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (db_model, selection); } else { memory_selection = new List<TrackInfo> (); var items = new ModelSelection<TrackInfo> (model, selection); foreach (TrackInfo track in items) { memory_selection.Add (track); } } } public void LoadTrackToEditor () { TrackInfo current_track = null; EditorTrackInfo editor_track = LoadTrack (current_track_index, out current_track); if (editor_track == null) { return; } // Update the Header header_title_label.Text = current_track.DisplayTrackTitle; header_artist_label.Text = current_track.DisplayArtistName; header_album_label.Text = current_track.DisplayAlbumTitle; if (edit_notif_label != null) { edit_notif_label.Markup = String.Format (Catalog.GetString ("<i>Editing {0} of {1} items</i>"), CurrentTrackIndex + 1, TrackCount); } LoadCoverArt (current_track); // Disconnect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.DisconnectUndo (); }); foreach (ITrackEditorPage page in pages) { page.LoadTrack (editor_track); } // Connect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.ConnectUndo (editor_track); }); // Update Navigation if (TrackCount > 0 && nav_backward_button != null && nav_forward_button != null) { nav_backward_button.Sensitive = CanGoBackward; nav_forward_button.Sensitive = CanGoForward; } // If there was a widget focused already (eg the Title entry), GrabFocus on it, // which causes its text to be selected, ready for editing. Widget child = FocusChild; while (child != null) { Container container = child as Container; if (container != null) { child = container.FocusChild; } else if (child != null) { child.GrabFocus (); child = null; } } } private void HideSingleTab () { int visible_pages = 0; foreach (ITrackEditorPage page in pages) { if (page.Widget.Visible) { visible_pages++; } } if (visible_pages == 1) { notebook.ShowTabs = false; notebook.ShowBorder = false; var container = notebook.CurrentPageWidget as Container; if (container != null) { container.BorderWidth = 0; } } } private void LoadCoverArt (TrackInfo current_track) { if (current_track == null) return; var artwork = ServiceManager.Get<ArtworkManager> (); var cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64); header_image.Clear (); header_image.Pixbuf = cover_art; if (cover_art == null) { header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.ShadowType = ShadowType.None; } else { header_image_frame.ShadowType = ShadowType.In; } header_image.QueueDraw (); } public void ForeachNonCurrentTrack (EditorTrackOperationClosure closure) { for (int i = 0; i < TrackCount; i++) { if (i == current_track_index) { continue; } EditorTrackInfo track = LoadTrack (i); if (track != null) { closure (track); } } } public EditorTrackInfo LoadTrack (int index) { return LoadTrack (index, true); } public EditorTrackInfo LoadTrack (int index, bool alwaysLoad) { TrackInfo source_track; return LoadTrack (index, alwaysLoad, out source_track); } private EditorTrackInfo LoadTrack (int index, out TrackInfo sourceTrack) { return LoadTrack (index, true, out sourceTrack); } private EditorTrackInfo LoadTrack (int index, bool alwaysLoad, out TrackInfo sourceTrack) { sourceTrack = GetTrack (index); EditorTrackInfo editor_track = null; if (sourceTrack == null) { // Something bad happened here return null; } if (!edit_map.TryGetValue (sourceTrack, out editor_track) && alwaysLoad) { editor_track = new EditorTrackInfo (sourceTrack); editor_track.EditorIndex = index; editor_track.EditorCount = TrackCount; edit_map.Add (sourceTrack, editor_track); } return editor_track; } private TrackInfo GetTrack (int index) { return db_selection != null ? db_selection[index] : memory_selection[index]; } protected virtual void OnNavigated () { EventHandler handler = Navigated; if (handler != null) { handler (this, EventArgs.Empty); } } public void NavigateForward () { if (current_track_index < TrackCount - 1) { current_track_index++; LoadTrackToEditor (); OnNavigated (); } } public void NavigateBackward () { if (current_track_index > 0) { current_track_index--; LoadTrackToEditor (); OnNavigated (); } } public int TrackCount { get { return db_selection != null ? db_selection.Count : memory_selection.Count; } } public int CurrentTrackIndex { get { return current_track_index; } } public bool CanGoBackward { get { return current_track_index > 0; } } public bool CanGoForward { get { return current_track_index >= 0 && current_track_index < TrackCount - 1; } } #endregion #region Saving public void Save () { List<int> primary_sources = new List<int> (); // TODO: wrap in db transaction try { DatabaseTrackInfo.NotifySaved = false; for (int i = 0; i < TrackCount; i++) { // Save any tracks that were actually loaded into the editor EditorTrackInfo track = LoadTrack (i, false); if (track == null || track.SourceTrack == null) { continue; } SaveTrack (track); if (track.SourceTrack is DatabaseTrackInfo) { // If the source track is from the database, save its parent for notification later int id = (track.SourceTrack as DatabaseTrackInfo).PrimarySourceId; if (!primary_sources.Contains (id)) { primary_sources.Add (id); } } } // Finally, notify the affected primary sources foreach (int id in primary_sources) { PrimarySource psrc = PrimarySource.GetById (id); if (psrc != null) { psrc.NotifyTracksChanged (); } } } finally { DatabaseTrackInfo.NotifySaved = true; } } private void SaveTrack (EditorTrackInfo track) { TrackInfo.ExportableMerge (track, track.SourceTrack); track.SourceTrack.Update (); if (track.SourceTrack.TrackEqual (ServiceManager.PlayerEngine.CurrentTrack)) { TrackInfo.ExportableMerge (track, ServiceManager.PlayerEngine.CurrentTrack); ServiceManager.PlayerEngine.TrackInfoUpdated (); } } #endregion #region Static Helpers public static void RunEdit (TrackListModel model, Selection selection) { Run (model, selection, EditorMode.Edit); } public static void RunView (TrackListModel model, Selection selection, bool readonlyTabs) { Run (model, selection, EditorMode.View, readonlyTabs); } public static void Run (TrackListModel model, Selection selection, EditorMode mode) { Run (new TrackEditorDialog (model, selection, mode)); } private static void Run (TrackListModel model, Selection selection, EditorMode mode, bool readonlyTabs) { Run (new TrackEditorDialog (model, selection, mode, readonlyTabs)); } private static void Run (TrackEditorDialog track_editor) { track_editor.Response += delegate (object o, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { track_editor.Save (); } else { int changed_count = 0; for (int i = 0; i < track_editor.TrackCount; i++) { EditorTrackInfo track = track_editor.LoadTrack (i, false); if (track != null) { track.GenerateDiff (); if (track.DiffCount > 0) { changed_count++; } } } if (changed_count == 0) { track_editor.Destroy (); return; } HigMessageDialog message_dialog = new HigMessageDialog ( track_editor, DialogFlags.Modal, MessageType.Warning, ButtonsType.None, String.Format (Catalog.GetPluralString ( "Save the changes made to the open track?", "Save the changes made to {0} of {1} open tracks?", track_editor.TrackCount), changed_count, track_editor.TrackCount), String.Empty ); UpdateCancelMessage (track_editor, message_dialog); uint timeout = 0; timeout = GLib.Timeout.Add (1000, delegate { bool result = UpdateCancelMessage (track_editor, message_dialog); if (!result) { timeout = 0; } return result; }); message_dialog.AddButton (Catalog.GetString ("Close _without Saving"), ResponseType.Close, false); message_dialog.AddButton (Stock.Cancel, ResponseType.Cancel, false); message_dialog.AddButton (Stock.Save, ResponseType.Ok, true); try { switch ((ResponseType)message_dialog.Run ()) { case ResponseType.Ok: track_editor.Save (); break; case ResponseType.Close: break; case ResponseType.Cancel: case ResponseType.DeleteEvent: return; } } finally { if (timeout > 0) { GLib.Source.Remove (timeout); } message_dialog.Destroy (); } } track_editor.Destroy (); }; //track_editor.Run (); track_editor.Show (); } private static bool UpdateCancelMessage (TrackEditorDialog trackEditor, HigMessageDialog messageDialog) { if (messageDialog == null) { return false; } messageDialog.MessageLabel.Text = String.Format (Catalog.GetString ( "If you don't save, changes from the last {0} will be permanently lost."), Banshee.Sources.DurationStatusFormatters.ApproximateVerboseFormatter ( DateTime.Now - trackEditor.dialog_launch_datetime ) ); return messageDialog.IsMapped; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// This is the default XPath/XQuery data model cache implementation. It will be used whenever /// the user does not supply his own XPathNavigator implementation. /// </summary> internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo { private XPathNode[] _pageCurrent; private XPathNode[] _pageParent; private int _idxCurrent; private int _idxParent; private string _atomizedLocalName; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed /// text node, then the parent is a virtualized parent (may be different than .Parent on the current node). /// </summary> public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) { Debug.Assert(pageCurrent != null && idxCurrent != 0); Debug.Assert((pageParent == null) == (idxParent == 0)); _pageCurrent = pageCurrent; _pageParent = pageParent; _idxCurrent = idxCurrent; _idxParent = idxParent; } /// <summary> /// Copy constructor. /// </summary> public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent) { _atomizedLocalName = nav._atomizedLocalName; } //----------------------------------------------- // XPathItem //----------------------------------------------- /// <summary> /// Get the string value of the current node, computed using data model dm:string-value rules. /// If the node has a typed value, return the string representation of the value. If the node /// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise, /// concatenate all text node descendants of the current node. /// </summary> public override string Value { get { string value; XPathNode[] page, pageEnd; int idx, idxEnd; // Try to get the pre-computed string value of the node value = _pageCurrent[_idxCurrent].Value; if (value != null) return value; #if DEBUG switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: Debug.Fail("ReadStringValue() should have taken care of these node types."); break; case XPathNodeType.Text: Debug.Assert(_idxParent != 0 && _pageParent[_idxParent].HasCollapsedText, "ReadStringValue() should have taken care of anything but collapsed text."); break; } #endif // If current node is collapsed text, then parent element has a simple text value if (_idxParent != 0) { Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text); return _pageParent[_idxParent].Value; } // Must be node with complex content, so concatenate the string values of all text descendants string s = string.Empty; StringBuilder bldr = null; // Get all text nodes which follow the current node in document order, but which are still descendants page = pageEnd = _pageCurrent; idx = idxEnd = _idxCurrent; if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) { pageEnd = null; idxEnd = 0; } while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) { Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText); if (s.Length == 0) { s = page[idx].Value; } else { if (bldr == null) { bldr = new StringBuilder(); bldr.Append(s); } bldr.Append(page[idx].Value); } } return (bldr != null) ? bldr.ToString() : s; } } //----------------------------------------------- // XPathNavigator //----------------------------------------------- /// <summary> /// Create a copy of this navigator, positioned to the same node in the tree. /// </summary> public override XPathNavigator Clone() { return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent); } /// <summary> /// Get the XPath node type of the current node. /// </summary> public override XPathNodeType NodeType { get { return _pageCurrent[_idxCurrent].NodeType; } } /// <summary> /// Get the local name portion of the current node's name. /// </summary> public override string LocalName { get { return _pageCurrent[_idxCurrent].LocalName; } } /// <summary> /// Get the namespace portion of the current node's name. /// </summary> public override string NamespaceURI { get { return _pageCurrent[_idxCurrent].NamespaceUri; } } /// <summary> /// Get the name of the current node. /// </summary> public override string Name { get { return _pageCurrent[_idxCurrent].Name; } } /// <summary> /// Get the prefix portion of the current node's name. /// </summary> public override string Prefix { get { return _pageCurrent[_idxCurrent].Prefix; } } /// <summary> /// Get the base URI of the current node. /// </summary> public override string BaseURI { get { XPathNode[] page; int idx; if (_idxParent != 0) { // Get BaseUri of parent for attribute, namespace, and collapsed text nodes page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } do { switch (page[idx].NodeType) { case XPathNodeType.Element: case XPathNodeType.Root: case XPathNodeType.ProcessingInstruction: // BaseUri is always stored with Elements, Roots, and PIs return page[idx].BaseUri; } // Get BaseUri of parent idx = page[idx].GetParent(out page); } while (idx != 0); return string.Empty; } } /// <summary> /// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form. /// </summary> public override bool IsEmptyElement { get { return _pageCurrent[_idxCurrent].AllowShortcutTag; } } /// <summary> /// Return the xml name table which was used to atomize all prefixes, local-names, and /// namespace uris in the document. /// </summary> public override XmlNameTable NameTable { get { return _pageCurrent[_idxCurrent].Document.NameTable; } } /// <summary> /// Position the navigator on the first attribute of the current node and return true. If no attributes /// can be found, return false. /// </summary> public override bool MoveToFirstAttribute() { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found, /// return false. /// </summary> public override bool MoveToNextAttribute() { return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// True if the current node has one or more attributes. /// </summary> public override bool HasAttributes { get { return _pageCurrent[_idxCurrent].HasAttribute; } } /// <summary> /// Position the navigator on the attribute with the specified name and return true. If no matching /// attribute can be found, return false. Don't assume the name parts are atomized with respect /// to this document. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// Position the navigator on the namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { XPathNode[] page; int idx; if (namespaceScope == XPathNamespaceScope.Local) { // Get local namespaces only idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page); } else { // Get all in-scope namespaces idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page); } while (idx != 0) { // Don't include the xmlns:xml namespace node if scope is ExcludeXml if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) { _pageParent = _pageCurrent; _idxParent = _idxCurrent; _pageCurrent = page; _idxCurrent = idx; return true; } // Skip past xmlns:xml idx = page[idx].GetSibling(out page); } return false; } /// <summary> /// Position the navigator on the next namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XPathNode[] page = _pageCurrent, pageParent; int idx = _idxCurrent, idxParent; // If current node is not a namespace node, return false if (page[idx].NodeType != XPathNodeType.Namespace) return false; while (true) { // Get next namespace sibling idx = page[idx].GetSibling(out page); // If there are no more nodes, return false if (idx == 0) return false; switch (scope) { case XPathNamespaceScope.Local: // Once parent changes, there are no longer any local namespaces idxParent = page[idx].GetParent(out pageParent); if (idxParent != _idxParent || (object)pageParent != (object)_pageParent) return false; break; case XPathNamespaceScope.ExcludeXml: // If node is xmlns:xml, then skip it if (page[idx].IsXmlNamespaceNode) continue; break; } // Found a matching next namespace node, so return it break; } _pageCurrent = page; _idxCurrent = idx; return true; } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the next content node. Return false if there are no more content nodes. /// </summary> public override bool MoveToNext() { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the previous (sibling) content node. Return false if there are no previous content nodes. /// </summary> public override bool MoveToPrevious() { // If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do // not have previous siblings. if (_idxParent != 0) return false; return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Move to the first content-typed child of the current node. Return false if the current /// node has no content children. /// </summary> public override bool MoveToFirstChild() { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position the navigator on the parent of the current node. If the current node has no parent, /// return false. /// </summary> public override bool MoveToParent() { if (_idxParent != 0) { // 1. For attribute nodes, element parent is always stored in order to make node-order // comparison simpler. // 2. For namespace nodes, parent is always stored in navigator in order to virtualize // XPath 1.0 namespaces. // 3. For collapsed text nodes, element parent is always stored in navigator. Debug.Assert(_pageParent != null); _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position this navigator to the same position as the "other" navigator. If the "other" navigator /// is not of the same type as this navigator, then return false. /// </summary> public override bool MoveTo(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { _pageCurrent = that._pageCurrent; _idxCurrent = that._idxCurrent; _pageParent = that._pageParent; _idxParent = that._idxParent; return true; } return false; } /// <summary> /// Position to the navigator to the element whose id is equal to the specified "id" string. /// </summary> public override bool MoveToId(string id) { XPathNode[] page; int idx; idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page); if (idx != 0) { // Move to ID element and clear parent state Debug.Assert(page[idx].NodeType == XPathNodeType.Element); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; return true; } return false; } /// <summary> /// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false /// if not, or if the "other" navigator is not the same type as this navigator. /// </summary> public override bool IsSamePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent && _idxParent == that._idxParent && _pageParent == that._pageParent; } return false; } /// <summary> /// Returns true if the current node has children. /// </summary> public override bool HasChildren { get { return _pageCurrent[_idxCurrent].HasContentChild; } } /// <summary> /// Position the navigator on the root node of the current document. /// </summary> public override void MoveToRoot() { if (_idxParent != 0) { // Clear parent state _pageParent = null; _idxParent = 0; } _idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent); } /// <summary> /// Move to the first element child of the current node with the specified name. Return false /// if the current node has no matching element children. /// </summary> public override bool MoveToChild(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first element sibling of the current node with the specified name. Return false /// if the current node has no matching element siblings. /// </summary> public override bool MoveToNext(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first content child of the current node with the specified type. Return false /// if the current node has no matching children. /// </summary> public override bool MoveToChild(XPathNodeType type) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node if (type != XPathNodeType.Text && type != XPathNodeType.All) return false; // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the first content sibling of the current node with the specified type. Return false /// if the current node has no matching siblings. /// </summary> public override bool MoveToNext(XPathNodeType type) { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the next element that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// Return false if the current node has no matching following elements. /// </summary> public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNode[] pageEnd; int idxEnd; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Get node on which scan ends (null if rest of document should be scanned) idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType /// Return false if the current node has no matching following nodes. /// </summary> public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathDocumentNavigator endTiny = end as XPathDocumentNavigator; XPathNode[] page, pageEnd; int idx, idxEnd; // If searching for text, make sure to handle collapsed text nodes correctly if (type == XPathNodeType.Text || type == XPathNodeType.All) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end" if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent) { // "end" is positioned to a virtual attribute, namespace, or text node return false; } _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } if (type == XPathNodeType.Text) { // Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, true, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } // If ending node is a virtual node, and current node is its parent, then we're done if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd) return false; // Get all virtual (collapsed) and physical text nodes which follow the current node if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) return false; if (page[idx].NodeType == XPathNodeType.Element) { // Virtualize collapsed text nodes Debug.Assert(page[idx].HasCollapsedText); _idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent); _pageParent = page; _idxParent = idx; } else { // Physical text node Debug.Assert(page[idx].IsText); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; } return true; } } // Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType. /// </summary> public override XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathDocumentKindChildIterator(this, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified QName. /// </summary> public override XPathNodeIterator SelectChildren(string name, string namespaceURI) { // If local name is wildcard, then call XPathNavigator.SelectChildren if (name == null || name.Length == 0) return base.SelectChildren(name, namespaceURI); return new XPathDocumentElementChildIterator(this, name, namespaceURI); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// XPathNodeType. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDocumentKindDescendantIterator(this, type, matchSelf); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// QName. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { // If local name is wildcard, then call XPathNavigator.SelectDescendants if (name == null || name.Length == 0) return base.SelectDescendants(name, namespaceURI, matchSelf); return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf); } /// <summary> /// Returns: /// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the /// navigator's are not positioned on nodes in the same document. /// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node /// in document order. /// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node /// in document order. /// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator. /// </summary> public override XmlNodeOrder ComparePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document; XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document; if ((object)thisDoc == (object)thatDoc) { int locThis = GetPrimaryLocation(); int locThat = that.GetPrimaryLocation(); if (locThis == locThat) { locThis = GetSecondaryLocation(); locThat = that.GetSecondaryLocation(); if (locThis == locThat) return XmlNodeOrder.Same; } return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After; } } return XmlNodeOrder.Unknown; } /// <summary> /// Return true if the "other" navigator's current node is a descendant of this navigator's current node. /// </summary> public override bool IsDescendant(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathNode[] pageThat; int idxThat; // If that current node's parent is virtualized, then start with the virtual parent if (that._idxParent != 0) { pageThat = that._pageParent; idxThat = that._idxParent; } else { idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat); } while (idxThat != 0) { if (idxThat == _idxCurrent && pageThat == _pageCurrent) return true; idxThat = pageThat[idxThat].GetParent(out pageThat); } } return false; } /// <summary> /// Construct a primary location for this navigator. The location is an integer that can be /// easily compared with other locations in the same document in order to determine the relative /// document order of two nodes. If two locations compare equal, then secondary locations should /// be compared. /// </summary> private int GetPrimaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so primary location should be derived from current node return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); } // Yes, so primary location should be derived from parent node return XPathNodeHelper.GetLocation(_pageParent, _idxParent); } /// <summary> /// Construct a secondary location for this navigator. This location should only be used if /// primary locations previously compared equal. /// </summary> private int GetSecondaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so secondary location is int.MinValue (always first) return int.MinValue; } // Yes, so secondary location should be derived from current node // This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: // Namespace nodes come first (make location negative, but greater than int.MinValue) return int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); case XPathNodeType.Attribute: // Attribute nodes come next (location is always positive) return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); default: // Collapsed text nodes are always last return int.MaxValue; } } /// <summary> /// Create a unique id for the current node. This is used by the generate-id() function. /// </summary> internal override string UniqueId { get { // 32-bit integer is split into 5-bit groups, the maximum number of groups is 7 char[] buf = new char[1 + 7 + 1 + 7]; int idx = 0; int loc; // Ensure distinguishing attributes, namespaces and child nodes buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType]; // If the current node is virtualized, code its parent if (_idxParent != 0) { loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); buf[idx++] = '0'; } // Code the node itself loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); return new string(buf, 0, idx); } } public override object UnderlyingObject { get { // Since we don't have any underlying PUBLIC object // the best one we can return is a clone of the navigator. // Note that it should be a clone as the user might Move the returned navigator // around and thus cause unexpected behavior of the caller of this class (For example the validator) return this.Clone(); } } //----------------------------------------------- // IXmlLineInfo //----------------------------------------------- /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> public bool HasLineInfo() { return _pageCurrent[_idxCurrent].Document.HasLineInfo; } /// <summary> /// Return the source line number of the current node. /// </summary> public int LineNumber { get { // If the current node is a collapsed text node, then return parent element's line number if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].LineNumber; return _pageCurrent[_idxCurrent].LineNumber; } } /// <summary> /// Return the source line position of the current node. /// </summary> public int LinePosition { get { // If the current node is a collapsed text node, then get position from parent element if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].CollapsedLinePosition; return _pageCurrent[_idxCurrent].LinePosition; } } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Get hashcode based on current position of the navigator. /// </summary> public int GetPositionHashCode() { return _idxCurrent ^ _idxParent; } /// <summary> /// Return true if navigator is positioned to an element having the specified name. /// </summary> public bool IsElementMatch(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Cannot be an element if parent is stored if (_idxParent != 0) return false; return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI); } /// <summary> /// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignificantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & XPathNavigatorEx.GetKindMask(typ)) != 0); } /// <summary> /// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it /// is positioned to a non-virtual node. If "end" is positioned to a virtual node: /// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent /// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1. /// </summary> private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) { // If ending navigator is positioned to a node in another document, then return null if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document) { // If the ending navigator is not positioned on a virtual node, then return its current node if (end._idxParent == 0) { pageEnd = end._pageCurrent; return end._idxCurrent; } // If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the // next physical node instead, as the results will be the same. pageEnd = end._pageParent; return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1; } // No following, so set pageEnd to null and return an index of 0 pageEnd = null; return 0; } } }
using System; using NUnit.Framework; using NFluent; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class FieldValueDiscarded { [Test] public void DiscardFirst() { var res = FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedFirst>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.CustomerID == null).Length); } [Test] public void DiscardSecond() { var res = FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedSecond>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.CompanyName == null).Length); } [Test] public void DiscardMiddle() { var res = FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedMiddle>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.Address == null).Length); } [Test] public void DiscardLast() { var res = FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedLast>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.Country == null).Length); } [DelimitedRecord("\t")] public class CustomersTabDiscardedFirst { [FieldValueDiscarded] public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedSecond { public string CustomerID; [FieldValueDiscarded] public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedMiddle { public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; [FieldValueDiscarded] public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedLast { public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; [FieldValueDiscarded] public string Country; } [Test] public void DiscardedBad() { Assert.Throws<BadUsageException>(() => FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersDiscardBad>()); } [Test] public void OrdersAllDiscarded() { var res = FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersAllDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate == new DateTime(2000, 1, 2) && x.Freight == 0).Length).IsEqualTo(res.Length); } [Test] public void OrdersLastNotDiscarded() { var res = FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersLastNotDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate == new DateTime(2000, 1, 2) && x.Freight != 0).Length).IsEqualTo(res.Length); } [Test] public void OrdersLastTwoNotDiscarded() { var res = FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersLastTwoNotDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate != new DateTime(2000, 1, 2) && x.Freight != 0).Length).IsEqualTo(res.Length); } [DelimitedRecord("|")] public class OrdersDiscardBad { [FieldValueDiscarded] public int OrderID; public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; public decimal Freight; } [DelimitedRecord("|")] public class OrdersAllDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] [FieldValueDiscarded] [FieldNullValue(typeof (DateTime), "2000-01-02")] public DateTime OrderDate; [FieldValueDiscarded] [FieldNullValue(typeof (decimal), "0")] public decimal Freight; } [DelimitedRecord("|")] public class OrdersLastNotDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] [FieldValueDiscarded] [FieldNullValue(typeof (DateTime), "2000-01-02")] public DateTime OrderDate; public decimal Freight; } [DelimitedRecord("|")] public class OrdersLastTwoNotDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; public decimal Freight; } } }
#region License // Copyright (c) 2006-2007, ClearCanvas 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: // // * 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 ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion namespace AIMTemplateService.View.WinForms { partial class WebBrowserComponentControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WebBrowserComponentControl)); this._browser = new System.Windows.Forms.WebBrowser(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this._statusBar = new System.Windows.Forms.StatusStrip(); this._browserProgress = new System.Windows.Forms.ToolStripProgressBar(); this._browserStatus = new System.Windows.Forms.ToolStripStatusLabel(); this._toolbar = new System.Windows.Forms.ToolStrip(); this._back = new System.Windows.Forms.ToolStripButton(); this._forward = new System.Windows.Forms.ToolStripButton(); this._stop = new System.Windows.Forms.ToolStripButton(); this._refresh = new System.Windows.Forms.ToolStripButton(); this._address = new System.Windows.Forms.ToolStripComboBox(); this._go = new System.Windows.Forms.ToolStripButton(); this._progressLogo = new System.Windows.Forms.ToolStripLabel(); this._shortcutToolbar = new System.Windows.Forms.ToolStrip(); this.toolStripContainer1.BottomToolStripPanel.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this._statusBar.SuspendLayout(); this._toolbar.SuspendLayout(); this.SuspendLayout(); // // _browser // this._browser.Dock = System.Windows.Forms.DockStyle.Fill; this._browser.Location = new System.Drawing.Point(0, 0); this._browser.MinimumSize = new System.Drawing.Size(20, 20); this._browser.Name = "_browser"; this._browser.Size = new System.Drawing.Size(584, 440); this._browser.TabIndex = 0; // // toolStripContainer1 // // // toolStripContainer1.BottomToolStripPanel // this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this._statusBar); // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this._browser); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(584, 440); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(584, 526); this.toolStripContainer1.TabIndex = 1; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this._toolbar); this.toolStripContainer1.TopToolStripPanel.Controls.Add(this._shortcutToolbar); // // _statusBar // this._statusBar.Dock = System.Windows.Forms.DockStyle.None; this._statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._browserProgress, this._browserStatus}); this._statusBar.Location = new System.Drawing.Point(0, 0); this._statusBar.Name = "_statusBar"; this._statusBar.Size = new System.Drawing.Size(584, 22); this._statusBar.TabIndex = 1; this._statusBar.Text = "statusStrip1"; // // _browserProgress // this._browserProgress.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this._browserProgress.Name = "_browserProgress"; this._browserProgress.Size = new System.Drawing.Size(100, 16); // // _browserStatus // this._browserStatus.Name = "_browserStatus"; this._browserStatus.Size = new System.Drawing.Size(0, 17); // // _toolbar // this._toolbar.Dock = System.Windows.Forms.DockStyle.None; this._toolbar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._toolbar.ImageScalingSize = new System.Drawing.Size(32, 32); this._toolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._back, this._forward, this._stop, this._refresh, this._address, this._go, this._progressLogo}); this._toolbar.Location = new System.Drawing.Point(0, 0); this._toolbar.Name = "_toolbar"; this._toolbar.Size = new System.Drawing.Size(584, 39); this._toolbar.Stretch = true; this._toolbar.TabIndex = 0; // // _back // this._back.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._back.Image = ((System.Drawing.Image)(resources.GetObject("_back.Image"))); this._back.ImageTransparentColor = System.Drawing.Color.Magenta; this._back.Name = "_back"; this._back.Size = new System.Drawing.Size(36, 36); this._back.Text = "Back"; // // _forward // this._forward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._forward.Image = ((System.Drawing.Image)(resources.GetObject("_forward.Image"))); this._forward.ImageTransparentColor = System.Drawing.Color.Magenta; this._forward.Name = "_forward"; this._forward.Size = new System.Drawing.Size(36, 36); this._forward.Text = "Forward"; // // _stop // this._stop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._stop.Image = ((System.Drawing.Image)(resources.GetObject("_stop.Image"))); this._stop.ImageTransparentColor = System.Drawing.Color.Magenta; this._stop.Name = "_stop"; this._stop.Size = new System.Drawing.Size(36, 36); this._stop.Text = "toolStripButton1"; this._stop.ToolTipText = "Stop"; // // _refresh // this._refresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._refresh.Image = ((System.Drawing.Image)(resources.GetObject("_refresh.Image"))); this._refresh.ImageTransparentColor = System.Drawing.Color.Magenta; this._refresh.Name = "_refresh"; this._refresh.Size = new System.Drawing.Size(36, 36); this._refresh.Text = "toolStripButton1"; this._refresh.ToolTipText = "Refresh"; // // _address // this._address.Name = "_address"; this._address.Size = new System.Drawing.Size(350, 39); this._address.ToolTipText = "Address"; // // _go // this._go.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._go.Image = ((System.Drawing.Image)(resources.GetObject("_go.Image"))); this._go.ImageTransparentColor = System.Drawing.Color.Magenta; this._go.Name = "_go"; this._go.Size = new System.Drawing.Size(36, 36); this._go.Text = "toolStripButton1"; this._go.ToolTipText = "Go"; // // _progressLogo // this._progressLogo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this._progressLogo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._progressLogo.Name = "_progressLogo"; this._progressLogo.Size = new System.Drawing.Size(0, 36); // // _shortcutToolbar // this._shortcutToolbar.Dock = System.Windows.Forms.DockStyle.None; this._shortcutToolbar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._shortcutToolbar.Location = new System.Drawing.Point(0, 39); this._shortcutToolbar.Name = "_shortcutToolbar"; this._shortcutToolbar.Size = new System.Drawing.Size(584, 25); this._shortcutToolbar.Stretch = true; this._shortcutToolbar.TabIndex = 1; // // WebBrowserComponentControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.toolStripContainer1); this.Name = "WebBrowserComponentControl"; this.Size = new System.Drawing.Size(584, 526); this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false); this.toolStripContainer1.BottomToolStripPanel.PerformLayout(); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this._statusBar.ResumeLayout(false); this._statusBar.PerformLayout(); this._toolbar.ResumeLayout(false); this._toolbar.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser _browser; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ToolStrip _toolbar; private System.Windows.Forms.ToolStripButton _back; private System.Windows.Forms.ToolStripButton _forward; private System.Windows.Forms.ToolStripButton _stop; private System.Windows.Forms.ToolStripButton _refresh; private System.Windows.Forms.ToolStripComboBox _address; private System.Windows.Forms.ToolStripButton _go; private System.Windows.Forms.ToolStripLabel _progressLogo; private System.Windows.Forms.StatusStrip _statusBar; private System.Windows.Forms.ToolStripStatusLabel _browserStatus; private System.Windows.Forms.ToolStripProgressBar _browserProgress; private System.Windows.Forms.ToolStrip _shortcutToolbar; } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TakeOrSkipWhileQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Parallel { /// <summary> /// Take- and SkipWhile work similarly. Execution is broken into two phases: Search /// and Yield. /// /// During the Search phase, many partitions at once search for the first occurrence /// of a false element. As they search, any time a partition finds a false element /// whose index is lesser than the current lowest-known false element, the new index /// will be published, so other partitions can stop the search. The search stops /// as soon as (1) a partition exhausts its input, (2) the predicate yields false for /// one of the partition's elements, or (3) its input index passes the current lowest- /// known index (sufficient since a given partition's indices are always strictly /// incrementing -- asserted below). Elements are buffered during this process. /// /// Partitions use a barrier after Search and before moving on to Yield. Once all /// have passed the barrier, Yielding begins. At this point, the lowest-known false /// index will be accurate for the entire set, since all partitions have finished /// scanning. This is where TakeWhile and SkipWhile differ. TakeWhile will start at /// the beginning of its buffer and yield all elements whose indices are less than /// the lowest-known false index. SkipWhile, on the other hand, will skip any such /// elements in the buffer, yielding those whose index is greater than or equal to /// the lowest-known false index, and then finish yielding any remaining elements in /// its data source (since it may have stopped prematurely due to (3) above). /// </summary> /// <typeparam name="TResult"></typeparam> internal sealed class TakeOrSkipWhileQueryOperator<TResult> : UnaryQueryOperator<TResult, TResult> { // Predicate function used to decide when to stop yielding elements. One pair is used for // index-based evaluation (i.e. it is passed the index as well as the element's value). private readonly Func<TResult, bool>? _predicate; private readonly Func<TResult, int, bool>? _indexedPredicate; private readonly bool _take; // Whether to take (true) or skip (false). private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool _limitsParallelism = false; // The precomputed value of LimitsParallelism //--------------------------------------------------------------------------------------- // Initializes a new take-while operator. // // Arguments: // child - the child data source to enumerate // predicate - the predicate function (if expression tree isn't provided) // indexedPredicate - the index-based predicate function (if expression tree isn't provided) // take - whether this is a TakeWhile (true) or SkipWhile (false) // // Notes: // Only one kind of predicate can be specified, an index-based one or not. If an // expression tree is provided, the delegate cannot also be provided. // internal TakeOrSkipWhileQueryOperator(IEnumerable<TResult> child, Func<TResult, bool>? predicate, Func<TResult, int, bool>? indexedPredicate, bool take) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); Debug.Assert(predicate != null || indexedPredicate != null, "need a predicate function"); _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; InitOrderIndexState(); } /// <summary> /// Determines the order index state for the output operator /// </summary> private void InitOrderIndexState() { // SkipWhile/TakeWhile needs an increasing index. However, if the predicate expression depends on the index, // the index needs to be correct, not just increasing. OrdinalIndexState requiredIndexState = OrdinalIndexState.Increasing; OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (_indexedPredicate != null) { requiredIndexState = OrdinalIndexState.Correct; _limitsParallelism = childIndexState == OrdinalIndexState.Increasing; } OrdinalIndexState indexState = ExchangeUtilities.Worse(childIndexState, OrdinalIndexState.Correct); if (indexState.IsWorseThan(requiredIndexState)) { _prematureMerge = true; } if (!_take) { // If the index was correct, now it is only increasing. indexState = indexState.Worse(OrdinalIndexState.Increasing); } SetOrdinalIndexState(indexState); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, bool preferStriping, QuerySettings settings) { if (_prematureMerge) { ListQueryResults<TResult> results = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); PartitionedStream<TResult, int> listInputStream = results.GetPartitionedStream(); WrapHelper<int>(listInputStream, recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>(PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Create shared data. OperatorState<TKey> operatorState = new OperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); Debug.Assert(_indexedPredicate == null || typeof(TKey) == typeof(int)); Func<TResult, TKey, bool>? convertedIndexedPredicate = (Func<TResult, TKey, bool>?)(object?)_indexedPredicate; PartitionedStream<TResult, TKey> partitionedStream = new PartitionedStream<TResult, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { partitionedStream[i] = new TakeOrSkipWhileQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, convertedIndexedPredicate, _take, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer); } recipient.Receive(partitionedStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TResult> Open(QuerySettings settings, bool preferStriping) { QueryResults<TResult> childQueryResults = Child.Open(settings, true); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TResult> AsSequentialQuery(CancellationToken token) { if (_take) { if (_indexedPredicate != null) { return Child.AsSequentialQuery(token).TakeWhile(_indexedPredicate); } Debug.Assert(_predicate != null); return Child.AsSequentialQuery(token).TakeWhile(_predicate); } if (_indexedPredicate != null) { IEnumerable<TResult> wrappedIndexedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedIndexedChild.SkipWhile(_indexedPredicate); } Debug.Assert(_predicate != null); IEnumerable<TResult> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.SkipWhile(_predicate); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the take- or skip-while. // private class TakeOrSkipWhileQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TResult, TKey> { private readonly QueryOperatorEnumerator<TResult, TKey> _source; // The data source to enumerate. private readonly Func<TResult, bool>? _predicate; // The actual predicate function. private readonly Func<TResult, TKey, bool>? _indexedPredicate; // The actual index-based predicate function. private readonly bool _take; // Whether to execute a take- (true) or skip-while (false). private readonly IComparer<TKey> _keyComparer; // Comparer for the order keys. // These fields are all shared among partitions. private readonly OperatorState<TKey> _operatorState; // The lowest false found by any partition. private readonly CountdownEvent _sharedBarrier; // To separate the search/yield phases. private readonly CancellationToken _cancellationToken; // Token used to cancel this operator. private List<Pair<TResult, TKey>>? _buffer; // Our buffer. private Shared<int>? _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing] private int _updatesSeen; // How many updates has this enumerator observed? (Each other enumerator will contribute one update.) private TKey _currentLowKey = default!; // The lowest key rejected by one of the other enumerators. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal TakeOrSkipWhileQueryOperatorEnumerator( QueryOperatorEnumerator<TResult, TKey> source, Func<TResult, bool>? predicate, Func<TResult, TKey, bool>? indexedPredicate, bool take, OperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancelToken, IComparer<TKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(predicate != null || indexedPredicate != null); Debug.Assert(operatorState != null); Debug.Assert(sharedBarrier != null); Debug.Assert(keyComparer != null); _source = source; _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancelToken; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TResult currentElement, ref TKey currentKey) { // If the buffer has not been created, we will generate it lazily on demand. if (_buffer == null) { // Create a buffer, but don't publish it yet (in case of exception). List<Pair<TResult, TKey>> buffer = new List<Pair<TResult, TKey>>(); // Enter the search phase. In this phase, we scan the input until one of three // things happens: (1) all input has been exhausted, (2) the predicate yields // false for one of our elements, or (3) we move past the current lowest index // found by other partitions for a false element. As we go, we have to remember // the elements by placing them into the buffer. try { TResult current = default(TResult)!; TKey key = default(TKey)!; int i = 0; //counter to help with cancellation while (_source.MoveNext(ref current!, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Add the current element to our buffer. buffer.Add(new Pair<TResult, TKey>(current, key)); // See if another partition has found a false value before this element. If so, // we should stop scanning the input now and reach the barrier ASAP. if (_updatesSeen != _operatorState._updatesDone) { lock (_operatorState) { _currentLowKey = _operatorState._currentLowKey; _updatesSeen = _operatorState._updatesDone; } } if (_updatesSeen > 0 && _keyComparer.Compare(key, _currentLowKey) > 0) { break; } // Evaluate the predicate, either indexed or not based on info passed to the ctor. bool predicateResult; if (_predicate != null) { predicateResult = _predicate(current); } else { Debug.Assert(_indexedPredicate != null); predicateResult = _indexedPredicate(current, key); } if (!predicateResult) { // Signal that we've found a false element, racing with other partitions to // set the shared index value. lock (_operatorState) { if (_operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, key) > 0) { _currentLowKey = _operatorState._currentLowKey = key; _updatesSeen = ++_operatorState._updatesDone; } } break; } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } // Before exiting the search phase, we will synchronize with others. This is a barrier. _sharedBarrier.Wait(_cancellationToken); // Publish the buffer and set the index to just before the 1st element. _buffer = buffer; _bufferIndex = new Shared<int>(-1); } Debug.Assert(_bufferIndex != null); // Now either enter (or continue) the yielding phase. As soon as we reach this, we know the // current shared "low false" value is the absolute lowest with a false. if (_take) { // In the case of a take-while, we will yield each element from our buffer for which // the element is lesser than the lowest false index found. if (_bufferIndex.Value >= _buffer.Count - 1) { return false; } // Increment the index, and remember the values. ++_bufferIndex.Value; currentElement = _buffer[_bufferIndex.Value].First; currentKey = _buffer[_bufferIndex.Value].Second; return _operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, currentKey) > 0; } else { // If no false was found, the output is empty. if (_operatorState._updatesDone == 0) { return false; } // In the case of a skip-while, we must skip over elements whose index is lesser than the // lowest index found. Once we've exhausted the buffer, we must go back and continue // enumerating the data source until it is empty. if (_bufferIndex.Value < _buffer.Count - 1) { for (_bufferIndex.Value++; _bufferIndex.Value < _buffer.Count; _bufferIndex.Value++) { // If the current buffered element's index is greater than or equal to the smallest // false index found, we will yield it as a result. if (_keyComparer.Compare(_buffer[_bufferIndex.Value].Second, _operatorState._currentLowKey) >= 0) { currentElement = _buffer[_bufferIndex.Value].First; currentKey = _buffer[_bufferIndex.Value].Second; return true; } } } // Lastly, so long as our input still has elements, they will be yieldable. if (_source.MoveNext(ref currentElement!, ref currentKey)) { Debug.Assert(_keyComparer.Compare(currentKey, _operatorState._currentLowKey) > 0, "expected remaining element indices to be greater than smallest"); return true; } } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } private class OperatorState<TKey> { internal volatile int _updatesDone = 0; internal TKey _currentLowKey = default!; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore; using NetGore.IO; namespace DemoGame { /// <summary> /// Represents the integral value of an Alliance's index. /// </summary> [Serializable] [TypeConverter(typeof(AllianceIDTypeConverter))] public struct AllianceID : IComparable<AllianceID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int> { /// <summary> /// Represents the largest possible value of AllianceID. This field is constant. /// </summary> public const int MaxValue = byte.MaxValue; /// <summary> /// Represents the smallest possible value of AllianceID. This field is constant. /// </summary> public const int MinValue = byte.MinValue; /// <summary> /// The underlying value. This contains the actual value of the struct instance. /// </summary> readonly byte _value; /// <summary> /// Initializes a new instance of the <see cref="AllianceID"/> struct. /// </summary> /// <param name="value">Value to assign to the new AllianceID.</param> /// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception> public AllianceID(int value) { if (value < MinValue || value > MaxValue) throw new ArgumentOutOfRangeException("value"); _value = (byte)value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="other">Another object to compare to.</param> /// <returns> /// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public bool Equals(AllianceID other) { return other._value == _value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns> /// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public override bool Equals(object obj) { return obj is AllianceID && this == (AllianceID)obj; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { return _value.GetHashCode(); } /// <summary> /// Gets the raw internal value of this AllianceID. /// </summary> /// <returns>The raw internal value.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public byte GetRawValue() { return _value; } /// <summary> /// Reads an AllianceID from an IValueReader. /// </summary> /// <param name="reader">IValueReader to read from.</param> /// <param name="name">Unique name of the value to read.</param> /// <returns>The AllianceID read from the IValueReader.</returns> public static AllianceID Read(IValueReader reader, string name) { var value = reader.ReadByte(name); return new AllianceID(value); } /// <summary> /// Reads an AllianceID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="i">The index of the field to find.</param> /// <returns>The AllianceID read from the <see cref="IDataRecord"/>.</returns> public static AllianceID Read(IDataRecord reader, int i) { var value = reader.GetValue(i); if (value is byte) return new AllianceID((byte)value); var convertedValue = Convert.ToByte(value); return new AllianceID(convertedValue); } /// <summary> /// Reads an AllianceID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="name">The name of the field to find.</param> /// <returns>The AllianceID read from the <see cref="IDataRecord"/>.</returns> public static AllianceID Read(IDataRecord reader, string name) { return Read(reader, reader.GetOrdinal(name)); } /// <summary> /// Reads an AllianceID from an BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <returns>The AllianceID read from the BitStream.</returns> public static AllianceID Read(BitStream bitStream) { var value = bitStream.ReadByte(); return new AllianceID(value); } /// <summary> /// Converts the numeric value of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance, consisting of a sequence /// of digits ranging from 0 to 9, without leading zeroes.</returns> public override string ToString() { return _value.ToString(); } /// <summary> /// Writes the AllianceID to an IValueWriter. /// </summary> /// <param name="writer">IValueWriter to write to.</param> /// <param name="name">Unique name of the AllianceID that will be used to distinguish it /// from other values when reading.</param> public void Write(IValueWriter writer, string name) { writer.Write(name, _value); } /// <summary> /// Writes the AllianceID to an IValueWriter. /// </summary> /// <param name="bitStream">BitStream to write to.</param> public void Write(BitStream bitStream) { bitStream.Write(_value); } #region IComparable<AllianceID> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(AllianceID other) { return _value.CompareTo(other._value); } #endregion #region IComparable<int> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(int other) { return _value.CompareTo(other); } #endregion #region IConvertible Members /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for this instance. /// </summary> /// <returns> /// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface. /// </returns> public TypeCode GetTypeCode() { return _value.GetTypeCode(); } /// <summary> /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation /// that supplies culture-specific formatting information.</param> /// <returns> /// A Boolean value equivalent to the value of this instance. /// </returns> bool IConvertible.ToBoolean(IFormatProvider provider) { return ((IConvertible)_value).ToBoolean(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit unsigned integer equivalent to the value of this instance. /// </returns> byte IConvertible.ToByte(IFormatProvider provider) { return ((IConvertible)_value).ToByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A Unicode character equivalent to the value of this instance. /// </returns> char IConvertible.ToChar(IFormatProvider provider) { return ((IConvertible)_value).ToChar(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance. /// </returns> DateTime IConvertible.ToDateTime(IFormatProvider provider) { return ((IConvertible)_value).ToDateTime(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance. /// </returns> decimal IConvertible.ToDecimal(IFormatProvider provider) { return ((IConvertible)_value).ToDecimal(provider); } /// <summary> /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A double-precision floating-point number equivalent to the value of this instance. /// </returns> double IConvertible.ToDouble(IFormatProvider provider) { return ((IConvertible)_value).ToDouble(provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit signed integer equivalent to the value of this instance. /// </returns> short IConvertible.ToInt16(IFormatProvider provider) { return ((IConvertible)_value).ToInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit signed integer equivalent to the value of this instance. /// </returns> int IConvertible.ToInt32(IFormatProvider provider) { return ((IConvertible)_value).ToInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit signed integer equivalent to the value of this instance. /// </returns> long IConvertible.ToInt64(IFormatProvider provider) { return ((IConvertible)_value).ToInt64(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit signed integer equivalent to the value of this instance. /// </returns> sbyte IConvertible.ToSByte(IFormatProvider provider) { return ((IConvertible)_value).ToSByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A single-precision floating-point number equivalent to the value of this instance. /// </returns> float IConvertible.ToSingle(IFormatProvider provider) { return ((IConvertible)_value).ToSingle(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.String"/> instance equivalent to the value of this instance. /// </returns> public string ToString(IFormatProvider provider) { return ((IConvertible)_value).ToString(provider); } /// <summary> /// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information. /// </summary> /// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance. /// </returns> object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)_value).ToType(conversionType, provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit unsigned integer equivalent to the value of this instance. /// </returns> ushort IConvertible.ToUInt16(IFormatProvider provider) { return ((IConvertible)_value).ToUInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit unsigned integer equivalent to the value of this instance. /// </returns> uint IConvertible.ToUInt32(IFormatProvider provider) { return ((IConvertible)_value).ToUInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit unsigned integer equivalent to the value of this instance. /// </returns> ulong IConvertible.ToUInt64(IFormatProvider provider) { return ((IConvertible)_value).ToUInt64(provider); } #endregion #region IEquatable<int> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(int other) { return _value.Equals(other); } #endregion #region IFormattable Members /// <summary> /// Formats the value of the current instance using the specified format. /// </summary> /// <param name="format">The <see cref="T:System.String"/> specifying the format to use. /// -or- /// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation. /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// </param> /// <returns> /// A <see cref="T:System.String"/> containing the value of the current instance in the specified format. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { return _value.ToString(format, formatProvider); } #endregion /// <summary> /// Implements operator ++. /// </summary> /// <param name="l">The AllianceID to increment.</param> /// <returns>The incremented AllianceID.</returns> public static AllianceID operator ++(AllianceID l) { return new AllianceID(l._value + 1); } /// <summary> /// Implements operator --. /// </summary> /// <param name="l">The AllianceID to decrement.</param> /// <returns>The decremented AllianceID.</returns> public static AllianceID operator --(AllianceID l) { return new AllianceID(l._value - 1); } /// <summary> /// Implements operator +. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side plus the right side.</returns> public static AllianceID operator +(AllianceID left, AllianceID right) { return new AllianceID(left._value + right._value); } /// <summary> /// Implements operator -. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side minus the right side.</returns> public static AllianceID operator -(AllianceID left, AllianceID right) { return new AllianceID(left._value - right._value); } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(AllianceID left, int right) { return left._value == right; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(AllianceID left, int right) { return left._value != right; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(int left, AllianceID right) { return left == right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(int left, AllianceID right) { return left != right._value; } /// <summary> /// Casts a AllianceID to an Int32. /// </summary> /// <param name="AllianceID">AllianceID to cast.</param> /// <returns>The Int32.</returns> public static explicit operator int(AllianceID AllianceID) { return AllianceID._value; } /// <summary> /// Casts an Int32 to a AllianceID. /// </summary> /// <param name="value">Int32 to cast.</param> /// <returns>The AllianceID.</returns> public static explicit operator AllianceID(int value) { return new AllianceID(value); } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(int left, AllianceID right) { return left > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(int left, AllianceID right) { return left < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(AllianceID left, AllianceID right) { return left._value > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(AllianceID left, AllianceID right) { return left._value < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(AllianceID left, int right) { return left._value > right; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(AllianceID left, int right) { return left._value < right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(int left, AllianceID right) { return left >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(int left, AllianceID right) { return left <= right._value; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(AllianceID left, int right) { return left._value >= right; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(AllianceID left, int right) { return left._value <= right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(AllianceID left, AllianceID right) { return left._value >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(AllianceID left, AllianceID right) { return left._value <= right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(AllianceID left, AllianceID right) { return left._value != right._value; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(AllianceID left, AllianceID right) { return left._value == right._value; } } /// <summary> /// Adds extensions to some data I/O objects for performing Read and Write operations for the AllianceID. /// All of the operations are implemented in the AllianceID struct. These extensions are provided /// purely for the convenience of accessing all the I/O operations from the same place. /// </summary> public static class AllianceIDReadWriteExtensions { /// <summary> /// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type AllianceID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <returns>The value at the given <paramref name="key"/> parsed as a AllianceID.</returns> public static AllianceID AsAllianceID<T>(this IDictionary<T, string> dict, T key) { return Parser.Invariant.ParseAllianceID(dict[key]); } /// <summary> /// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type AllianceID. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param> /// <returns>The value at the given <paramref name="key"/> parsed as an int, or the /// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/> /// or the value at the given <paramref name="key"/> could not be parsed.</returns> public static AllianceID AsAllianceID<T>(this IDictionary<T, string> dict, T key, AllianceID defaultValue) { string value; if (!dict.TryGetValue(key, out value)) return defaultValue; AllianceID parsed; if (!Parser.Invariant.TryParse(value, out parsed)) return defaultValue; return parsed; } /// <summary> /// Reads the AllianceID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the AllianceID from.</param> /// <param name="i">The field index to read.</param> /// <returns>The AllianceID read from the <see cref="IDataRecord"/>.</returns> public static AllianceID GetAllianceID(this IDataRecord r, int i) { return AllianceID.Read(r, i); } /// <summary> /// Reads the AllianceID from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the AllianceID from.</param> /// <param name="name">The name of the field to read the value from.</param> /// <returns>The AllianceID read from the <see cref="IDataRecord"/>.</returns> public static AllianceID GetAllianceID(this IDataRecord r, string name) { return AllianceID.Read(r, name); } /// <summary> /// Parses the AllianceID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <returns>The AllianceID parsed from the string.</returns> public static AllianceID ParseAllianceID(this Parser parser, string value) { return new AllianceID(parser.ParseByte(value)); } /// <summary> /// Reads the AllianceID from a BitStream. /// </summary> /// <param name="bitStream">BitStream to read the AllianceID from.</param> /// <returns>The AllianceID read from the BitStream.</returns> public static AllianceID ReadAllianceID(this BitStream bitStream) { return AllianceID.Read(bitStream); } /// <summary> /// Reads the AllianceID from an IValueReader. /// </summary> /// <param name="valueReader">IValueReader to read the AllianceID from.</param> /// <param name="name">The unique name of the value to read.</param> /// <returns>The AllianceID read from the IValueReader.</returns> public static AllianceID ReadAllianceID(this IValueReader valueReader, string name) { return AllianceID.Read(valueReader, name); } /// <summary> /// Tries to parse the AllianceID from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <param name="outValue">If this method returns true, contains the parsed AllianceID.</param> /// <returns>True if the parsing was successfully; otherwise false.</returns> public static bool TryParse(this Parser parser, string value, out AllianceID outValue) { byte tmp; var ret = parser.TryParse(value, out tmp); outValue = new AllianceID(tmp); return ret; } /// <summary> /// Writes a AllianceID to a BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="value">AllianceID to write.</param> public static void Write(this BitStream bitStream, AllianceID value) { value.Write(bitStream); } /// <summary> /// Writes a AllianceID to a IValueWriter. /// </summary> /// <param name="valueWriter">IValueWriter to write to.</param> /// <param name="name">Unique name of the AllianceID that will be used to distinguish it /// from other values when reading.</param> /// <param name="value">AllianceID to write.</param> public static void Write(this IValueWriter valueWriter, string name, AllianceID value) { value.Write(valueWriter, name); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Signum.Utilities; using Signum.Utilities.Reflection; using Signum.Utilities.ExpressionTrees; using Signum.Entities; using Signum.Engine.Maps; using Signum.Entities.Basics; using System.Threading; using System.Threading.Tasks; using System.Text.RegularExpressions; using Signum.Entities.DynamicQuery; namespace Signum.Engine.DynamicQuery { public static class AutocompleteUtils { public static List<Lite<Entity>> FindLiteLike(Implementations implementations, string subString, int count) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike"); try { using (ExecutionMode.UserInterface()) return FindLiteLike(implementations.Types, subString, count); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static async Task<List<Lite<Entity>>> FindLiteLikeAsync(Implementations implementations, string subString, int count, CancellationToken cancellationToken) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike"); try { using (ExecutionMode.UserInterface()) return await FindLiteLikeAsync(implementations.Types, subString, count, cancellationToken); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } private static bool TryParsePrimaryKey(string value, Type type, out PrimaryKey id) { var match = Regex.Match(value, "^id[:]?(.*)", RegexOptions.IgnoreCase); if (match.Success) return PrimaryKey.TryParse(match.Groups[1].ToString(), type, out id); id = default(PrimaryKey); return false; } static List<Lite<Entity>> FindLiteLike(IEnumerable<Type> types, string subString, int count) { if (subString == null) subString = ""; types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null); List<Lite<Entity>> results = new List<Lite<Entity>>(); foreach (var t in types) { if (TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var lite = giLiteById.GetInvoker(t).Invoke(id); if (lite != null) { results.Add(lite); if (results.Count >= count) return results; } } } foreach (var t in types) { if (!TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var parts = subString.SplitParts(); results.AddRange(giLiteContaining.GetInvoker(t)(parts, count - results.Count)); if (results.Count >= count) return results; } } return results; } private static async Task<List<Lite<Entity>>> FindLiteLikeAsync(IEnumerable<Type> types, string subString, int count, CancellationToken cancellationToken) { if (subString == null) subString = ""; types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null); List<Lite<Entity>> results = new List<Lite<Entity>>(); foreach (var t in types) { if (TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var lite = await giLiteByIdAsync.GetInvoker(t).Invoke(id, cancellationToken); if (lite != null) { results.Add(lite); if (results.Count >= count) return results; } } } foreach (var t in types) { if (!TryParsePrimaryKey(subString, t, out PrimaryKey id)) { var parts = subString.SplitParts(); var list = await giLiteContainingAsync.GetInvoker(t)(parts, count - results.Count, cancellationToken); results.AddRange(list); if (results.Count >= count) return results; } } return results; } static GenericInvoker<Func<PrimaryKey, Lite<Entity>>> giLiteById = new GenericInvoker<Func<PrimaryKey, Lite<Entity>>>(id => LiteById<TypeEntity>(id)); static Lite<Entity> LiteById<T>(PrimaryKey id) where T : Entity { return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefault(); } static GenericInvoker<Func<PrimaryKey, CancellationToken, Task<Lite<Entity>>>> giLiteByIdAsync = new GenericInvoker<Func<PrimaryKey, CancellationToken, Task<Lite<Entity>>>>((id, token) => LiteByIdAsync<TypeEntity>(id, token)); static Task<Lite<Entity>> LiteByIdAsync<T>(PrimaryKey id, CancellationToken token) where T : Entity { return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefaultAsync(token).ContinueWith(t => (Lite<Entity>)t.Result); } static GenericInvoker<Func<string[], int, List<Lite<Entity>>>> giLiteContaining = new GenericInvoker<Func<string[], int, List<Lite<Entity>>>>((parts, c) => LiteContaining<TypeEntity>(parts, c)); static List<Lite<Entity>> LiteContaining<T>(string[] parts, int count) where T : Entity { return Database.Query<T>() .Where(a => a.ToString().ContainsAllParts(parts)) .OrderBy(a => a.ToString().Length) .Select(a => a.ToLite()) .Take(count) .AsEnumerable() .Cast<Lite<Entity>>() .ToList(); } static GenericInvoker<Func<string[], int, CancellationToken, Task<List<Lite<Entity>>>>> giLiteContainingAsync = new GenericInvoker<Func<string[], int, CancellationToken, Task<List<Lite<Entity>>>>>((parts, c, token) => LiteContaining<TypeEntity>(parts, c, token)); static async Task<List<Lite<Entity>>> LiteContaining<T>(string[] parts, int count, CancellationToken token) where T : Entity { var list = await Database.Query<T>() .Where(a => a.ToString().ContainsAllParts(parts)) .OrderBy(a => a.ToString().Length) .Select(a => a.ToLite()) .Take(count) .ToListAsync(token); return list.Cast<Lite<Entity>>().ToList(); } public static List<Lite<Entity>> FindAllLite(Implementations implementations) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite"); try { using (ExecutionMode.UserInterface()) return implementations.Types.SelectMany(type => Database.RetrieveAllLite(type)).ToList(); } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static async Task<List<Lite<Entity>>> FindAllLiteAsync(Implementations implementations, CancellationToken token) { if (implementations.IsByAll) throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite"); try { using (ExecutionMode.UserInterface()) { var tasks = implementations.Types.Select(type => Database.RetrieveAllLiteAsync(type, token)).ToList(); var list = await Task.WhenAll(tasks); return list.SelectMany(li => li).ToList(); } } catch (Exception e) { e.Data["implementations"] = implementations.ToString(); throw; } } public static List<T> AutocompleteUntyped<T>(this IQueryable<T> query, Expression<Func<T, Lite<Entity>>> entitySelector, string subString, int count, Type type) { using (ExecutionMode.UserInterface()) { List<T> results = new List<T>(); if (TryParsePrimaryKey(subString, type, out PrimaryKey id)) { T entity = query.SingleOrDefaultEx(r => entitySelector.Evaluate(r).Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = query .Where(r => entitySelector.Evaluate(r).ToString()!.ContainsAllParts(parts)) .OrderBy(r => entitySelector.Evaluate(r).ToString()!.Length) .Take(count - results.Count) .ToList(); results.AddRange(list); return results; } } public static async Task<List<T>> AutocompleteUntypedAsync<T>(this IQueryable<T> query, Expression<Func<T, Lite<Entity>>> entitySelector, string subString, int count, Type type, CancellationToken token) { using (ExecutionMode.UserInterface()) { List<T> results = new List<T>(); if (TryParsePrimaryKey(subString, type, out PrimaryKey id)) { T entity = await query.SingleOrDefaultAsync(r => entitySelector.Evaluate(r).Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = await query.Where(r => entitySelector.Evaluate(r).ToString()!.ContainsAllParts(parts)) .OrderBy(r => entitySelector.Evaluate(r).ToString()!.Length) .Take(count - results.Count) .ToListAsync(); results.AddRange(list); return results; } } public static List<Lite<T>> Autocomplete<T>(this IQueryable<Lite<T>> query, string subString, int count) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T>? entity = query.SingleOrDefaultEx(e => e.Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); results.AddRange(query.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count)); return results; } } public static async Task<List<Lite<T>>> AutocompleteAsync<T>(this IQueryable<Lite<T>> query, string subString, int count, CancellationToken token) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T> entity = await query.SingleOrDefaultAsync(e => e.Id == id, token); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = await query.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count) .ToListAsync(token); results.AddRange(list); return results; } } public static List<Lite<T>> Autocomplete<T>(this IEnumerable<Lite<T>> collection, string subString, int count) where T : Entity { using (ExecutionMode.UserInterface()) { List<Lite<T>> results = new List<Lite<T>>(); if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id)) { Lite<T>? entity = collection.SingleOrDefaultEx(e => e.Id == id); if (entity != null) results.Add(entity); if (results.Count >= count) return results; } var parts = subString.SplitParts(); var list = collection.Where(a => a.ToString()!.ContainsAllParts(parts)) .OrderBy(a => a.ToString()!.Length) .Take(count - results.Count); results.AddRange(list); return results; } } public static string[] SplitParts(this string str) { if (FilterCondition.ToLowerString()) return str.Trim().ToLower().SplitNoEmpty(' '); return str.Trim().SplitNoEmpty(' '); } [AutoExpressionField] public static bool ContainsAllParts(this string str, string[] parts) => As.Expression(() => FilterCondition.ToLowerString() ? str.ToLower().ContainsAll(parts) : str.ContainsAll(parts)); } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine.EventSystems; namespace UnityEngine.UI { [AddComponentMenu("Event/Graphic Raycaster")] [RequireComponent(typeof(Canvas))] public class GraphicRaycaster : BaseRaycaster { protected const int kNoEventMaskSet = -1; public enum BlockingObjects { None = 0, TwoD = 1, ThreeD = 2, All = 3, } public override int sortOrderPriority { get { // We need to return the sorting order here as distance will all be 0 for overlay. if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) return int.MaxValue - canvas.sortingOrder; return base.sortOrderPriority; } } public override int renderOrderPriority { get { // We need to return the sorting order here as distance will all be 0 for overlay. if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) return int.MaxValue - canvas.renderOrder; return base.renderOrderPriority; } } public bool ignoreReversedGraphics = true; public BlockingObjects blockingObjects = BlockingObjects.None; [SerializeField] protected LayerMask m_BlockingMask = kNoEventMaskSet; private Canvas m_Canvas; protected GraphicRaycaster() { } private Canvas canvas { get { if (m_Canvas != null) return m_Canvas; m_Canvas = GetComponent<Canvas>(); return m_Canvas; } } [NonSerialized] private List<Graphic> m_RaycastResults = new List<Graphic>(); public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) { if (canvas == null) return; // Convert to view space Vector2 pos; if (eventCamera == null) pos = new Vector2(eventData.position.x / Screen.width, eventData.position.y / Screen.height); else pos = eventCamera.ScreenToViewportPoint(eventData.position); // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) return; float hitDistance = float.MaxValue; if (canvas.renderMode != RenderMode.ScreenSpaceOverlay && blockingObjects != BlockingObjects.None) { var ray = eventCamera.ScreenPointToRay(eventData.position); float dist = eventCamera.farClipPlane - eventCamera.nearClipPlane; if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All) { var hits = Physics.RaycastAll(ray, dist, m_BlockingMask); if (hits.Length > 0 && hits[0].distance < hitDistance) { hitDistance = hits[0].distance; } } if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All) { var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask); if (hits.Length > 0 && hits[0].fraction * dist < hitDistance) { hitDistance = hits[0].fraction * dist; } } } m_RaycastResults.Clear(); Raycast(canvas, eventCamera, eventData.position, m_RaycastResults); for (var index = 0; index < m_RaycastResults.Count; index++) { var go = m_RaycastResults[index].gameObject; bool appendGraphic = true; if (ignoreReversedGraphics) { if (eventCamera == null) { // If we dont have a camera we know that we should always be facing forward var dir = go.transform.rotation * Vector3.forward; appendGraphic = Vector3.Dot(Vector3.forward, dir) > 0; } else { // If we have a camera compare the direction against the cameras forward. var cameraFoward = eventCamera.transform.rotation * Vector3.forward; var dir = go.transform.rotation * Vector3.forward; appendGraphic = Vector3.Dot(cameraFoward, dir) > 0; } } if (appendGraphic) { float distance = (eventCamera == null || canvas.renderMode == RenderMode.ScreenSpaceOverlay) ? 0 : Vector3.Distance(eventCamera.transform.position, canvas.transform.position); if (distance >= hitDistance) continue; var castResult = new RaycastResult { gameObject = go, module = this, distance = distance, index = resultAppendList.Count, depth = m_RaycastResults[index].depth }; resultAppendList.Add(castResult); } } } public override Camera eventCamera { get { if (canvas.renderMode == RenderMode.ScreenSpaceOverlay || (canvas.renderMode == RenderMode.ScreenSpaceCamera && canvas.worldCamera == null)) return null; return canvas.worldCamera != null ? canvas.worldCamera : Camera.main; } } /// <summary> /// Perform a raycast into the screen and collect all graphics underneath it. /// </summary> [NonSerialized] static readonly List<Graphic> s_SortedGraphics = new List<Graphic>(); private static void Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results) { // Debug.Log("ttt" + pointerPoision + ":::" + camera); // Necessary for the event system var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas); s_SortedGraphics.Clear(); for (int i = 0; i < foundGraphics.Count; ++i) { Graphic graphic = foundGraphics[i]; // -1 means it hasn't been processed by the canvas, which means it isn't actually drawn if (graphic.depth == -1) continue; if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, pointerPosition, eventCamera)) continue; if (graphic.Raycast(pointerPosition, eventCamera)) { s_SortedGraphics.Add(graphic); } } s_SortedGraphics.Sort((g1, g2) => g2.depth.CompareTo(g1.depth)); // StringBuilder cast = new StringBuilder(); for (int i = 0; i < s_SortedGraphics.Count; ++i) results.Add(s_SortedGraphics[i]); // Debug.Log (cast.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace NinjaLab.Azure.Apis.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// *********************************************************************** // Assembly : ACBr.Net.Core // Author : RFTD // Created : 03-21-2014 // // Last Modified By : RFTD // Last Modified On : 01-30-2015 // *********************************************************************** // <copyright file="Log4NetLogger.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Linq.Expressions; namespace ACBr.Net.Core.Logging { /// <summary> /// Classe Log4NetLogger. /// </summary> public class Log4NetLogger : IACBrLogger { /// <summary> /// The i log type /// </summary> private static readonly Type LogType = Type.GetType("log4net.ILog, log4net"); /// <summary> /// The is error enabled delegate /// </summary> private static readonly Func<object, bool> IsErrorEnabledDelegate; /// <summary> /// The is fatal enabled delegate /// </summary> private static readonly Func<object, bool> IsFatalEnabledDelegate; /// <summary> /// The is debug enabled delegate /// </summary> private static readonly Func<object, bool> IsDebugEnabledDelegate; /// <summary> /// The is information enabled delegate /// </summary> private static readonly Func<object, bool> IsInfoEnabledDelegate; /// <summary> /// The is warn enabled delegate /// </summary> private static readonly Func<object, bool> IsWarnEnabledDelegate; /// <summary> /// The error delegate /// </summary> private static readonly Action<object, object> ErrorDelegate; /// <summary> /// The error exception delegate /// </summary> private static readonly Action<object, object, Exception> ErrorExceptionDelegate; /// <summary> /// The error format delegate /// </summary> private static readonly Action<object, string, object[]> ErrorFormatDelegate; /// <summary> /// The fatal delegate /// </summary> private static readonly Action<object, object> FatalDelegate; /// <summary> /// The fatal exception delegate /// </summary> private static readonly Action<object, object, Exception> FatalExceptionDelegate; /// <summary> /// The debug delegate /// </summary> private static readonly Action<object, object> DebugDelegate; /// <summary> /// The debug exception delegate /// </summary> private static readonly Action<object, object, Exception> DebugExceptionDelegate; /// <summary> /// The debug format delegate /// </summary> private static readonly Action<object, string, object[]> DebugFormatDelegate; /// <summary> /// The information delegate /// </summary> private static readonly Action<object, object> InfoDelegate; /// <summary> /// The information exception delegate /// </summary> private static readonly Action<object, object, Exception> InfoExceptionDelegate; /// <summary> /// The information format delegate /// </summary> private static readonly Action<object, string, object[]> InfoFormatDelegate; /// <summary> /// The warn delegate /// </summary> private static readonly Action<object, object> WarnDelegate; /// <summary> /// The warn exception delegate /// </summary> private static readonly Action<object, object, Exception> WarnExceptionDelegate; /// <summary> /// The warn format delegate /// </summary> private static readonly Action<object, string, object[]> WarnFormatDelegate; /// <summary> /// The logger /// </summary> private readonly object Logger; /// <summary> /// Initializes static members of the <see cref="Log4NetLogger"/> class. /// </summary> static Log4NetLogger() { IsErrorEnabledDelegate = GetPropertyGetter("IsErrorEnabled"); IsFatalEnabledDelegate = GetPropertyGetter("IsFatalEnabled"); IsDebugEnabledDelegate = GetPropertyGetter("IsDebugEnabled"); IsInfoEnabledDelegate = GetPropertyGetter("IsInfoEnabled"); IsWarnEnabledDelegate = GetPropertyGetter("IsWarnEnabled"); ErrorDelegate = GetMethodCallForMessage("Error"); ErrorExceptionDelegate = GetMethodCallForMessageException("Error"); ErrorFormatDelegate = GetMethodCallForMessageFormat("ErrorFormat"); FatalDelegate = GetMethodCallForMessage("Fatal"); FatalExceptionDelegate = GetMethodCallForMessageException("Fatal"); DebugDelegate = GetMethodCallForMessage("Debug"); DebugExceptionDelegate = GetMethodCallForMessageException("Debug"); DebugFormatDelegate = GetMethodCallForMessageFormat("DebugFormat"); InfoDelegate = GetMethodCallForMessage("Info"); InfoExceptionDelegate = GetMethodCallForMessageException("Info"); InfoFormatDelegate = GetMethodCallForMessageFormat("InfoFormat"); WarnDelegate = GetMethodCallForMessage("Warn"); WarnExceptionDelegate = GetMethodCallForMessageException("Warn"); WarnFormatDelegate = GetMethodCallForMessageFormat("WarnFormat"); } /// <summary> /// Gets the property getter. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>Func&lt;System.Object, System.Boolean&gt;.</returns> private static Func<object, bool> GetPropertyGetter(string propertyName) { var funcParam = Expression.Parameter(typeof(object), "l"); Expression convertedParam = Expression.Convert(funcParam, LogType); Expression property = Expression.Property(convertedParam, propertyName); return (Func<object, bool>)Expression.Lambda(property, funcParam).Compile(); } /// <summary> /// Gets the method call for message. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns>Action&lt;System.Object, System.Object&gt;.</returns> private static Action<object, object> GetMethodCallForMessage(string methodName) { var loggerParam = Expression.Parameter(typeof(object), "l"); var messageParam = Expression.Parameter(typeof(object), "o"); Expression convertedParam = Expression.Convert(loggerParam, LogType); var methodCall = Expression.Call(convertedParam, LogType.GetMethod(methodName, new[] { typeof(object) }), messageParam); return (Action<object, object>)Expression.Lambda(methodCall, loggerParam, messageParam).Compile(); } /// <summary> /// Gets the method call for message exception. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns>Action&lt;System.Object, System.Object, Exception&gt;.</returns> private static Action<object, object, Exception> GetMethodCallForMessageException(string methodName) { var loggerParam = Expression.Parameter(typeof(object), "l"); var messageParam = Expression.Parameter(typeof(object), "o"); var exceptionParam = Expression.Parameter(typeof(Exception), "e"); Expression convertedParam = Expression.Convert(loggerParam, LogType); var methodCall = Expression.Call(convertedParam, LogType.GetMethod(methodName, new[] { typeof(object), typeof(Exception) }), messageParam, exceptionParam); return (Action<object, object, Exception>)Expression.Lambda(methodCall, loggerParam, messageParam, exceptionParam).Compile(); } /// <summary> /// Gets the method call for message format. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns>Action&lt;System.Object, System.String, System.Object[]&gt;.</returns> private static Action<object, string, object[]> GetMethodCallForMessageFormat(string methodName) { var loggerParam = Expression.Parameter(typeof(object), "l"); var formatParam = Expression.Parameter(typeof(string), "f"); var parametersParam = Expression.Parameter(typeof(object[]), "p"); Expression convertedParam = Expression.Convert(loggerParam, LogType); var methodCall = Expression.Call(convertedParam, LogType.GetMethod(methodName, new[] { typeof(string), typeof(object[]) }), formatParam, parametersParam); return (Action<object, string, object[]>)Expression.Lambda(methodCall, loggerParam, formatParam, parametersParam).Compile(); } /// <summary> /// Initializes a new instance of the <see cref="Log4NetLogger"/> class. /// </summary> /// <param name="logger">The logger.</param> public Log4NetLogger(object logger) { Logger = logger; } /// <summary> /// Gets a value indicating whether this instance is error enabled. /// </summary> /// <value><c>true</c> if this instance is error enabled; otherwise, <c>false</c>.</value> public bool IsErrorEnabled { get { return IsErrorEnabledDelegate(Logger); } } /// <summary> /// Gets a value indicating whether this instance is fatal enabled. /// </summary> /// <value><c>true</c> if this instance is fatal enabled; otherwise, <c>false</c>.</value> public bool IsFatalEnabled { get { return IsFatalEnabledDelegate(Logger); } } /// <summary> /// Gets a value indicating whether this instance is debug enabled. /// </summary> /// <value><c>true</c> if this instance is debug enabled; otherwise, <c>false</c>.</value> public bool IsDebugEnabled { get { return IsDebugEnabledDelegate(Logger); } } /// <summary> /// Gets a value indicating whether this instance is information enabled. /// </summary> /// <value><c>true</c> if this instance is information enabled; otherwise, <c>false</c>.</value> public bool IsInfoEnabled { get { return IsInfoEnabledDelegate(Logger); } } /// <summary> /// Gets a value indicating whether this instance is warn enabled. /// </summary> /// <value><c>true</c> if this instance is warn enabled; otherwise, <c>false</c>.</value> public bool IsWarnEnabled { get { return IsWarnEnabledDelegate(Logger); } } /// <summary> /// Errors the specified message. /// </summary> /// <param name="message">The message.</param> public void Error(object message) { if (IsErrorEnabled) ErrorDelegate(Logger, message); } /// <summary> /// Errors the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Error(object message, Exception exception) { if (IsErrorEnabled) ErrorExceptionDelegate(Logger, message, exception); } /// <summary> /// Errors the format. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) ErrorFormatDelegate(Logger, format, args); } /// <summary> /// Fatals the specified message. /// </summary> /// <param name="message">The message.</param> public void Fatal(object message) { if (IsFatalEnabled) FatalDelegate(Logger, message); } /// <summary> /// Fatals the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Fatal(object message, Exception exception) { if (IsFatalEnabled) FatalExceptionDelegate(Logger, message, exception); } /// <summary> /// Debugs the specified message. /// </summary> /// <param name="message">The message.</param> public void Debug(object message) { if (IsDebugEnabled) DebugDelegate(Logger, message); } /// <summary> /// Debugs the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Debug(object message, Exception exception) { if (IsDebugEnabled) DebugExceptionDelegate(Logger, message, exception); } /// <summary> /// Debugs the format. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public void DebugFormat(string format, params object[] args) { if (IsDebugEnabled) DebugFormatDelegate(Logger, format, args); } /// <summary> /// Informations the specified message. /// </summary> /// <param name="message">The message.</param> public void Info(object message) { if (IsInfoEnabled) InfoDelegate(Logger, message); } /// <summary> /// Informations the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Info(object message, Exception exception) { if (IsInfoEnabled) InfoExceptionDelegate(Logger, message, exception); } /// <summary> /// Informations the format. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public void InfoFormat(string format, params object[] args) { if (IsInfoEnabled) InfoFormatDelegate(Logger, format, args); } /// <summary> /// Warns the specified message. /// </summary> /// <param name="message">The message.</param> public void Warn(object message) { if (IsWarnEnabled) WarnDelegate(Logger, message); } /// <summary> /// Warns the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Warn(object message, Exception exception) { if (IsWarnEnabled) WarnExceptionDelegate(Logger, message, exception); } /// <summary> /// Warns the format. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public void WarnFormat(string format, params object[] args) { if (IsWarnEnabled) WarnFormatDelegate(Logger, format, args); } } }
// 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.Data.Common; using System.Diagnostics; using System.Threading.Tasks; namespace System.Data.SqlClient.SNI { internal class TdsParserStateObjectManaged : TdsParserStateObject { private SNIMarsConnection _marsConnection = null; private SNIHandle _sessionHandle = null; // the SNI handle we're to work on private SNIPacket _sniPacket = null; // Will have to re-vamp this for MARS internal SNIPacket _sniAsyncAttnPacket = null; // Packet to use to send Attn private readonly Dictionary<SNIPacket, SNIPacket> _pendingWritePackets = new Dictionary<SNIPacket, SNIPacket>(); // Stores write packets that have been sent to SNI, but have not yet finished writing (i.e. we are waiting for SNI's callback) private readonly WritePacketCache _writePacketCache = new WritePacketCache(); // Store write packets that are ready to be re-used public TdsParserStateObjectManaged(TdsParser parser) : base(parser) { } internal SspiClientContextStatus sspiClientContextStatus = new SspiClientContextStatus(); internal TdsParserStateObjectManaged(TdsParser parser, TdsParserStateObject physicalConnection, bool async) : base(parser, physicalConnection, async) { } internal SNIHandle Handle => _sessionHandle; internal override uint Status => _sessionHandle != null ? _sessionHandle.Status : TdsEnums.SNI_UNINITIALIZED; internal override object SessionHandle => _sessionHandle; protected override object EmptyReadPacket => null; protected override bool CheckPacket(object packet, TaskCompletionSource<object> source) { SNIPacket p = packet as SNIPacket; return p.IsInvalid || (!p.IsInvalid && source != null); } protected override void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async) { Debug.Assert(physicalConnection is TdsParserStateObjectManaged, "Expected a stateObject of type " + this.GetType()); TdsParserStateObjectManaged managedSNIObject = physicalConnection as TdsParserStateObjectManaged; _sessionHandle = managedSNIObject.CreateMarsSession(this, async); } internal SNIMarsHandle CreateMarsSession(object callbackObject, bool async) { return _marsConnection.CreateMarsSession(callbackObject, async); } protected override uint SNIPacketGetData(object packet, byte[] _inBuff, ref uint dataSize) => SNIProxy.Singleton.PacketGetData(packet as SNIPacket, _inBuff, ref dataSize); internal override void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity) { _sessionHandle = SNIProxy.Singleton.CreateConnectionHandle(this, serverName, ignoreSniOpenTimeout, timerExpire, out instanceName, ref spnBuffer, flushCache, async, parallel, isIntegratedSecurity); if (_sessionHandle == null) { _parser.ProcessSNIError(this); } else if (async) { // Create call backs and allocate to the session handle SNIAsyncCallback ReceiveAsyncCallbackDispatcher = new SNIAsyncCallback(ReadAsyncCallback); SNIAsyncCallback SendAsyncCallbackDispatcher = new SNIAsyncCallback(WriteAsyncCallback); _sessionHandle.SetAsyncCallbacks(ReceiveAsyncCallbackDispatcher, SendAsyncCallbackDispatcher); } } internal void ReadAsyncCallback(SNIPacket packet, uint error) => ReadAsyncCallback(IntPtr.Zero, packet, error); internal void WriteAsyncCallback(SNIPacket packet, uint sniError) => WriteAsyncCallback(IntPtr.Zero, packet, sniError); protected override void RemovePacketFromPendingList(object packet) { // No-Op } internal override void Dispose() { SNIPacket packetHandle = _sniPacket; SNIHandle sessionHandle = _sessionHandle; SNIPacket asyncAttnPacket = _sniAsyncAttnPacket; _sniPacket = null; _sessionHandle = null; _sniAsyncAttnPacket = null; _marsConnection = null; DisposeCounters(); if (null != sessionHandle || null != packetHandle) { packetHandle?.Dispose(); asyncAttnPacket?.Dispose(); if (sessionHandle != null) { sessionHandle.Dispose(); DecrementPendingCallbacks(true); // Will dispose of GC handle. } } DisposePacketCache(); } internal override void DisposePacketCache() { lock (_writePacketLockObject) { _writePacketCache.Dispose(); // Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point } } protected override void FreeGcHandle(int remaining, bool release) { // No - op } internal override bool IsFailedHandle() => _sessionHandle.Status != TdsEnums.SNI_SUCCESS; internal override object ReadSyncOverAsync(int timeoutRemaining, out uint error) { SNIHandle handle = Handle; if (handle == null) { throw ADP.ClosedConnectionError(); } SNIPacket packet = null; error = SNIProxy.Singleton.ReadSyncOverAsync(handle, out packet, timeoutRemaining); return packet; } internal override bool IsPacketEmpty(object packet) { return packet == null; } internal override void ReleasePacket(object syncReadPacket) { ((SNIPacket)syncReadPacket).Dispose(); } internal override uint CheckConnection() { SNIHandle handle = Handle; return handle == null ? TdsEnums.SNI_SUCCESS : SNIProxy.Singleton.CheckConnection(handle); } internal override object ReadAsync(out uint error, ref object handle) { SNIPacket packet; error = SNIProxy.Singleton.ReadAsync((SNIHandle)handle, out packet); return packet; } internal override object CreateAndSetAttentionPacket() { if (_sniAsyncAttnPacket == null) { SNIPacket attnPacket = new SNIPacket(); SetPacketData(attnPacket, SQL.AttentionHeader, TdsEnums.HEADER_LEN); _sniAsyncAttnPacket = attnPacket; } return _sniAsyncAttnPacket; } internal override uint WritePacket(object packet, bool sync) { return SNIProxy.Singleton.WritePacket((SNIHandle)Handle, (SNIPacket)packet, sync); } internal override object AddPacketToPendingList(object packet) { // No-Op return packet; } internal override bool IsValidPacket(object packetPointer) => (SNIPacket)packetPointer != null && !((SNIPacket)packetPointer).IsInvalid; internal override object GetResetWritePacket() { if (_sniPacket != null) { _sniPacket.Reset(); } else { lock (_writePacketLockObject) { _sniPacket = _writePacketCache.Take(Handle); } } return _sniPacket; } internal override void ClearAllWritePackets() { if (_sniPacket != null) { _sniPacket.Dispose(); _sniPacket = null; } lock (_writePacketLockObject) { Debug.Assert(_pendingWritePackets.Count == 0 && _asyncWriteCount == 0, "Should not clear all write packets if there are packets pending"); _writePacketCache.Clear(); } } internal override void SetPacketData(object packet, byte[] buffer, int bytesUsed) => SNIProxy.Singleton.PacketSetData((SNIPacket)packet, buffer, bytesUsed); internal override uint SniGetConnectionId(ref Guid clientConnectionId) => SNIProxy.Singleton.GetConnectionId(Handle, ref clientConnectionId); internal override uint DisabeSsl() => SNIProxy.Singleton.DisableSsl(Handle); internal override uint EnableMars(ref uint info) { _marsConnection = new SNIMarsConnection(Handle); if (_marsConnection.StartReceive() == TdsEnums.SNI_SUCCESS_IO_PENDING) { return TdsEnums.SNI_SUCCESS; } return TdsEnums.SNI_ERROR; } internal override uint EnableSsl(ref uint info)=> SNIProxy.Singleton.EnableSsl(Handle, info); internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) => SNIProxy.Singleton.SetConnectionBufferSize(Handle, unsignedPacketSize); internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer) { SNIProxy.Singleton.GenSspiClientContext(sspiClientContextStatus, receivedBuff, ref sendBuff, _sniSpnBuffer); sendLength = (uint)(sendBuff != null ? sendBuff.Length : 0); return 0; } internal override uint WaitForSSLHandShakeToComplete() => 0; internal sealed class WritePacketCache : IDisposable { private bool _disposed; private Stack<SNIPacket> _packets; public WritePacketCache() { _disposed = false; _packets = new Stack<SNIPacket>(); } public SNIPacket Take(SNIHandle sniHandle) { SNIPacket packet; if (_packets.Count > 0) { // Success - reset the packet packet = _packets.Pop(); packet.Reset(); } else { // Failed to take a packet - create a new one packet = new SNIPacket(); } return packet; } public void Add(SNIPacket packet) { if (!_disposed) { _packets.Push(packet); } else { // If we're disposed, then get rid of any packets added to us packet.Dispose(); } } public void Clear() { while (_packets.Count > 0) { _packets.Pop().Dispose(); } } public void Dispose() { if (!_disposed) { _disposed = true; Clear(); } } } } }
// 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.Diagnostics; using System.Linq; using System.Linq.Expressions; using Microsoft.Its.Domain.Serialization; using Newtonsoft.Json; namespace Microsoft.Its.Domain { /// <summary> /// Defines a class that can be used like a string but with additional constraints to enforce specific semantic usages. /// </summary> /// <typeparam name="T">The type of the implementing class.</typeparam> [DebuggerDisplay("{Value}")] [Serializable] [JsonConverter(typeof(PrimitiveConverter))] public abstract class String<T> where T : String<T> { private readonly string value; private readonly StringComparison stringComparison = StringComparison.OrdinalIgnoreCase; private static readonly Func<string, T> create; /// <summary> /// Initializes the <see cref="String{T}" /> class. /// </summary> static String() { var ctor = typeof (T).GetConstructor(new[] { typeof (string) }); var innerValue = Expression.Parameter(typeof (string)); var expression = Expression.Lambda<Func<string, T>>( Expression.New(ctor, innerValue), innerValue); create = expression.Compile(); } /// <summary> /// Initializes a new instance of the <see cref="String&lt;T&gt;" /> class. /// </summary> protected String() { value = string.Empty; } /// <summary> /// Initializes a new instance of the <see cref="String&lt;T&gt;" /> class. /// </summary> /// <param name="value">The value held by the string instance.</param> /// <param name="stringComparison"> /// The string comparison to be used to determine equality of two instances of the same <see cref="String{T}" />. /// </param> protected String(string value, StringComparison stringComparison = StringComparison.OrdinalIgnoreCase) { if (value == null) { throw new ArgumentNullException("value"); } this.value = value; this.stringComparison = stringComparison; } /// <summary> /// Gets the underlying <see cref="string" /> value of the instance. /// </summary> public string Value { get { return value; } } /// <summary> /// Performs an explicit conversion from <see cref="String{T}" /> to <see cref="System.String" />. /// </summary> /// <param name="from">From.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator string(String<T> from) { return from.Value; } /// <summary> /// Performs an implicit conversion from <see cref="System.String" /> to <see cref="String{T}" />. /// </summary> /// <param name="from">From.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator String<T>(string from) { return create(from); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj"> /// The <see cref="System.Object" /> to compare with this instance. /// </param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return Equals(this, obj); } /// <summary> /// Equalses the specified other. /// </summary> /// <param name="other">The other.</param> /// <returns></returns> public bool Equals(String<T> other) { return Equals(this, other); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return Value.ToLowerInvariant().GetHashCode() ^ typeof (T).GetHashCode(); } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return Value; } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(String<T> left, object right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(String<T> left, object right) { return !Equals(left, right); } /// <summary> /// Equalses the specified left. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns></returns> public static bool Equals(String<T> left, object right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(null, right)) { return false; } if (ReferenceEquals(null, left)) { return false; } if (left.GetType() != right.GetType()) { var s = right as string; if (s != null) { // if right is a true string, compare as string return string.Equals( left.Value, s, left.stringComparison); } // two different semantic string types are never equal return false; } // if they're the same type, compare as string return string.Equals( left.Value, ((String<T>) right).Value, left.stringComparison); } } }
// 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.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.CSharp.Analyzers.CSharpDoNotUseInsecureDtdProcessingInApiDesignAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.VisualBasic.Analyzers.BasicDoNotUseInsecureDtdProcessingInApiDesignAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingInApiDesignAnalyzerTests { private static DiagnosticResult GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(int line, int column, string name) => VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage, name)); private static DiagnosticResult GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(int line, int column, string name) => VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage, name)); [Fact] public async Task XmlTextReaderDerivedTypeNoCtorSetUrlResolverToXmlResolverMethodShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public void method() { XmlResolver = new XmlUrlResolver(); } } }", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(11, 13, "method") ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub method() XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(8, 13, "method") ); } [Fact] public async Task XmlTextReaderDerivedTypeSetUrlResolverToXmlResolverMethodShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { XmlResolver = new XmlUrlResolver(); } } }", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method") ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method") ); } [Fact] public async Task XmlTextReaderDerivedTypeSetDtdProcessingToParseMethodShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Parse; } } }", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method") ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Parse End Sub End Class End Namespace", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method") ); } [Fact] public async Task XmlTextReaderDerivedTypeSetUrlResolverToThisXmlResolverMethodShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { this.XmlResolver = new XmlUrlResolver(); } } }", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method") ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() Me.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method") ); } [Fact] public async Task XmlTextReaderDerivedTypeSetUrlResolverToBaseXmlResolverMethodShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { base.XmlResolver = new XmlUrlResolver(); } } }", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method") ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() MyBase.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method") ); } [Fact] public async Task XmlTextReaderDerivedTypeSetXmlResolverToNullMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { XmlResolver = null; } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeSetDtdProcessingToProhibitMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Prohibit; } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Prohibit End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeSetDtdProcessingToTypoMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Prohibit; } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Prohibit End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeParseAndNullResolverMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Parse; XmlResolver = null; } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Parse XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeIgnoreAndUrlResolverMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Ignore; XmlResolver = new XmlUrlResolver(); } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Ignore XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeParseAndUrlResolverMethodShouldGenerateDiagnostic() { DiagnosticResult diagWith2Locations = GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method") .WithLocation(18, 13); await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method() { DtdProcessing = DtdProcessing.Parse; XmlResolver = new XmlUrlResolver(); } } }", diagWith2Locations ); diagWith2Locations = GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method") .WithLocation(14, 13); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method() DtdProcessing = DtdProcessing.Parse XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", diagWith2Locations ); } [Fact] public async Task XmlTextReaderDerivedTypeSecureResolverInOnePathMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method(bool flag) { DtdProcessing = DtdProcessing.Parse; if (flag) { XmlResolver = null; } else { XmlResolver = new XmlUrlResolver(); // intended false negative, due to the lack of flow analysis } } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method(flag As Boolean) DtdProcessing = DtdProcessing.Parse If flag Then XmlResolver = Nothing Else ' intended false negative, due to the lack of flow analysis XmlResolver = New XmlUrlResolver() End If End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderDerivedTypeSetInsecureSettingsInSeperatePathsMethodShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlTextReader { public TestClass() { this.XmlResolver = null; this.DtdProcessing = DtdProcessing.Prohibit; } public void method(bool flag) { if (flag) { // secure DtdProcessing = DtdProcessing.Ignore; XmlResolver = null; } else { // insecure DtdProcessing = DtdProcessing.Parse; XmlResolver = new XmlUrlResolver(); // intended false negative, due to the lack of flow analysis } } } }" ); await VerifyVisualBasicAnalyzerAsync(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlTextReader Public Sub New() Me.XmlResolver = Nothing Me.DtdProcessing = DtdProcessing.Prohibit End Sub Public Sub method(flag As Boolean) If flag Then ' secure DtdProcessing = DtdProcessing.Ignore XmlResolver = Nothing Else ' insecure DtdProcessing = DtdProcessing.Parse ' intended false negative, due to the lack of flow analysis XmlResolver = New XmlUrlResolver() End If End Sub End Class End Namespace"); } } }
/* Copyright (c) 2014, RMIT Training 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 CounterCompliance nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace CounterReports.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Eagle.ExternalIntegrationWebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Globalization; using System.Linq; using System.Web; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.Web.Studio.Utility; namespace ASC.Feed.Aggregator.Modules.CRM { internal class DealsModule : FeedModule { private const string item = "deal"; protected override string Table { get { return "crm_deal"; } } protected override string LastUpdatedColumn { get { return "create_on"; } } protected override string TenantColumn { get { return "tenant_id"; } } protected override string DbId { get { return Constants.CrmDbId; } } public override string Name { get { return Constants.DealsModule; } } public override string Product { get { return ModulesHelper.CRMProductName; } } public override Guid ProductID { get { return ModulesHelper.CRMProductID; } } public override bool VisibleFor(Feed feed, object data, Guid userId) { return base.VisibleFor(feed, data, userId) && CRMSecurity.CanAccessTo((Deal)data); } public override IEnumerable<Tuple<Feed, object>> GetFeeds(FeedFilter filter) { var query = new SqlQuery("crm_deal d") .Select(DealColumns().Select(d => "d." + d).ToArray()) .Where("d.tenant_id", filter.Tenant) .Where(Exp.Between("d.create_on", filter.Time.From, filter.Time.To)) .LeftOuterJoin("crm_contact c", Exp.EqColumns("c.id", "d.contact_id") & Exp.Eq("c.tenant_id", filter.Tenant) ) .Select(ContactColumns().Select(c => "c." + c).ToArray()); using (var db = DbManager.FromHttpContext(Constants.CrmDbId)) { var deals = db.ExecuteList(query).ConvertAll(ToDeal); return deals.Select(d => new Tuple<Feed, object>(ToFeed(d), d)); } } private static IEnumerable<string> DealColumns() { return new[] { "id", "title", "description", "responsible_id", "create_by", "create_on", "last_modifed_by", "last_modifed_on", "contact_id" // 8 }; } private static IEnumerable<string> ContactColumns() { return new[] { "is_company", // 9 "id", "notes", "first_name", "last_name", "company_name", "company_id", "display_name", "create_by", "create_on", "last_modifed_by", "last_modifed_on" // 20 }; } private static Deal ToDeal(object[] r) { var deal = new Deal { ID = Convert.ToInt32(r[0]), Title = Convert.ToString(r[1]), Description = Convert.ToString(r[2]), ResponsibleID = new Guid(Convert.ToString(r[3])), CreateBy = new Guid(Convert.ToString(r[4])), CreateOn = Convert.ToDateTime(r[5]), LastModifedBy = new Guid(Convert.ToString(r[6])), LastModifedOn = Convert.ToDateTime(r[7]) }; var contactId = Convert.ToInt32(r[8]); if (!string.IsNullOrEmpty(Convert.ToString(r[9]))) { var isCompany = Convert.ToBoolean(r[9]); if (contactId > 0 && isCompany) { deal.Contact = new Company { ID = Convert.ToInt32(r[10]), About = Convert.ToString(r[11]), CompanyName = Convert.ToString(r[14]), CreateBy = new Guid(Convert.ToString(r[17])), CreateOn = Convert.ToDateTime(r[18]), LastModifedBy = new Guid(Convert.ToString(r[19])), LastModifedOn = Convert.ToDateTime(r[20]) }; } else { deal.Contact = new Person { ID = Convert.ToInt32(r[10]), About = Convert.ToString(r[11]), FirstName = Convert.ToString(r[12]), LastName = Convert.ToString(r[13]), CompanyID = Convert.ToInt32(r[15]), JobTitle = Convert.ToString(r[16]), CreateBy = new Guid(Convert.ToString(r[17])), CreateOn = Convert.ToDateTime(r[18]), LastModifedBy = new Guid(Convert.ToString(r[19])), LastModifedOn = Convert.ToDateTime(r[20]) }; } } return deal; } private Feed ToFeed(Deal deal) { var itemId = "/Products/CRM/Deals.aspx?id=" + deal.ID + "#profile"; return new Feed(deal.CreateBy, deal.CreateOn) { Item = item, ItemId = deal.ID.ToString(CultureInfo.InvariantCulture), ItemUrl = CommonLinkUtility.ToAbsolute(itemId), Product = Product, Module = Name, Title = deal.Title, Description = Helper.GetHtmlDescription(HttpUtility.HtmlEncode(deal.Description)), AdditionalInfo = deal.Contact.GetTitle(), Keywords = string.Format("{0} {1}", deal.Title, deal.Description), HasPreview = false, CanComment = false, GroupId = GetGroupId(item, deal.CreateBy) }; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// <para>Describes the properties of an environment.</para> /// </summary> public class CreateEnvironmentResult { private string environmentName; private string environmentId; private string applicationName; private string versionLabel; private string solutionStackName; private string templateName; private string description; private string endpointURL; private string cNAME; private DateTime? dateCreated; private DateTime? dateUpdated; private string status; private string health; private EnvironmentResourcesDescription resources; /// <summary> /// The name of this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>4 - 23</description> /// </item> /// </list> /// </para> /// </summary> public string EnvironmentName { get { return this.environmentName; } set { this.environmentName = value; } } /// <summary> /// Sets the EnvironmentName property /// </summary> /// <param name="environmentName">The value to set for the EnvironmentName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithEnvironmentName(string environmentName) { this.environmentName = environmentName; return this; } // Check to see if EnvironmentName property is set internal bool IsSetEnvironmentName() { return this.environmentName != null; } /// <summary> /// The ID of this environment. /// /// </summary> public string EnvironmentId { get { return this.environmentId; } set { this.environmentId = value; } } /// <summary> /// Sets the EnvironmentId property /// </summary> /// <param name="environmentId">The value to set for the EnvironmentId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithEnvironmentId(string environmentId) { this.environmentId = environmentId; return this; } // Check to see if EnvironmentId property is set internal bool IsSetEnvironmentId() { return this.environmentId != null; } /// <summary> /// The name of the application associated with this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string ApplicationName { get { return this.applicationName; } set { this.applicationName = value; } } /// <summary> /// Sets the ApplicationName property /// </summary> /// <param name="applicationName">The value to set for the ApplicationName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithApplicationName(string applicationName) { this.applicationName = applicationName; return this; } // Check to see if ApplicationName property is set internal bool IsSetApplicationName() { return this.applicationName != null; } /// <summary> /// The application version deployed in this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string VersionLabel { get { return this.versionLabel; } set { this.versionLabel = value; } } /// <summary> /// Sets the VersionLabel property /// </summary> /// <param name="versionLabel">The value to set for the VersionLabel property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithVersionLabel(string versionLabel) { this.versionLabel = versionLabel; return this; } // Check to see if VersionLabel property is set internal bool IsSetVersionLabel() { return this.versionLabel != null; } /// <summary> /// The name of the <c>SolutionStack</c> deployed with this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string SolutionStackName { get { return this.solutionStackName; } set { this.solutionStackName = value; } } /// <summary> /// Sets the SolutionStackName property /// </summary> /// <param name="solutionStackName">The value to set for the SolutionStackName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithSolutionStackName(string solutionStackName) { this.solutionStackName = solutionStackName; return this; } // Check to see if SolutionStackName property is set internal bool IsSetSolutionStackName() { return this.solutionStackName != null; } /// <summary> /// The name of the configuration template used to originally launch this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string TemplateName { get { return this.templateName; } set { this.templateName = value; } } /// <summary> /// Sets the TemplateName property /// </summary> /// <param name="templateName">The value to set for the TemplateName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithTemplateName(string templateName) { this.templateName = templateName; return this; } // Check to see if TemplateName property is set internal bool IsSetTemplateName() { return this.templateName != null; } /// <summary> /// Describes this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 200</description> /// </item> /// </list> /// </para> /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// The URL to the LoadBalancer for this environment. /// /// </summary> public string EndpointURL { get { return this.endpointURL; } set { this.endpointURL = value; } } /// <summary> /// Sets the EndpointURL property /// </summary> /// <param name="endpointURL">The value to set for the EndpointURL property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithEndpointURL(string endpointURL) { this.endpointURL = endpointURL; return this; } // Check to see if EndpointURL property is set internal bool IsSetEndpointURL() { return this.endpointURL != null; } /// <summary> /// The URL to the CNAME for this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// </list> /// </para> /// </summary> public string CNAME { get { return this.cNAME; } set { this.cNAME = value; } } /// <summary> /// Sets the CNAME property /// </summary> /// <param name="cNAME">The value to set for the CNAME property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithCNAME(string cNAME) { this.cNAME = cNAME; return this; } // Check to see if CNAME property is set internal bool IsSetCNAME() { return this.cNAME != null; } /// <summary> /// The creation date for this environment. /// /// </summary> public DateTime DateCreated { get { return this.dateCreated ?? default(DateTime); } set { this.dateCreated = value; } } /// <summary> /// Sets the DateCreated property /// </summary> /// <param name="dateCreated">The value to set for the DateCreated property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithDateCreated(DateTime dateCreated) { this.dateCreated = dateCreated; return this; } // Check to see if DateCreated property is set internal bool IsSetDateCreated() { return this.dateCreated.HasValue; } /// <summary> /// The last modified date for this environment. /// /// </summary> public DateTime DateUpdated { get { return this.dateUpdated ?? default(DateTime); } set { this.dateUpdated = value; } } /// <summary> /// Sets the DateUpdated property /// </summary> /// <param name="dateUpdated">The value to set for the DateUpdated property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithDateUpdated(DateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } // Check to see if DateUpdated property is set internal bool IsSetDateUpdated() { return this.dateUpdated.HasValue; } /// <summary> /// The current operational status of the environment: <ul> <li> <c>Launching</c>: Environment is in the process of initial deployment. </li> /// <li> <c>Updating</c>: Environment is in the process of updating its configuration settings or application version. </li> <li> <c>Ready</c>: /// Environment is available to have an action performed on it, such as update or terminate. </li> <li> <c>Terminating</c>: Environment is in /// the shut-down process. </li> <li> <c>Terminated</c>: Environment is not running. </li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>Launching, Updating, Ready, Terminating, Terminated</description> /// </item> /// </list> /// </para> /// </summary> public string Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Sets the Status property /// </summary> /// <param name="status">The value to set for the Status property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithStatus(string status) { this.status = status; return this; } // Check to see if Status property is set internal bool IsSetStatus() { return this.status != null; } /// <summary> /// Describes the health status of the environment. AWS Elastic Beanstalk indicates the failure levels for a running environment: <enumValues> /// <value name="Red"> <c>Red</c> : Indicates the environment is not working. </value> <value name="Yellow"> <c>Yellow</c>: Indicates that /// something is wrong, the application might not be available, but the instances appear running. </value> <value name="Green"> <c>Green</c>: /// Indicates the environment is healthy and fully functional. </value> </enumValues> <ul> <li> <c>Red</c>: Indicates the environment is not /// responsive. Occurs when three or more consecutive failures occur for an environment. </li> <li> <c>Yellow</c>: Indicates that something is /// wrong. Occurs when two consecutive failures occur for an environment. </li> <li> <c>Green</c>: Indicates the environment is healthy and /// fully functional. </li> <li> <c>Grey</c>: Default health for a new environment. The environment is not fully launched and health checks have /// not started or health checks are suspended during an <c>UpdateEnvironment</c> or <c>RestartEnvironement</c> request. </li> </ul> Default: /// <c>Grey</c> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>Green, Yellow, Red, Grey</description> /// </item> /// </list> /// </para> /// </summary> public string Health { get { return this.health; } set { this.health = value; } } /// <summary> /// Sets the Health property /// </summary> /// <param name="health">The value to set for the Health property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithHealth(string health) { this.health = health; return this; } // Check to see if Health property is set internal bool IsSetHealth() { return this.health != null; } /// <summary> /// The description of the AWS resources used by this environment. /// /// </summary> public EnvironmentResourcesDescription Resources { get { return this.resources; } set { this.resources = value; } } /// <summary> /// Sets the Resources property /// </summary> /// <param name="resources">The value to set for the Resources property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateEnvironmentResult WithResources(EnvironmentResourcesDescription resources) { this.resources = resources; return this; } // Check to see if Resources property is set internal bool IsSetResources() { return this.resources != null; } } }
using System; using NUnit.Framework; using it.unifi.dsi.stlab.networkreasoner.model.gas; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance; using it.unifi.dsi.stlab.networkreasoner.gas.system.formulae; using log4net; using log4net.Config; using System.IO; using System.Collections.Generic; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.listeners; using it.unifi.dsi.stlab.utilities.object_with_substitution; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.unknowns_initializations; using it.unifi.dsi.stlab.math.algebra; using it.unifi.dsi.stlab.networkreasoner.model.textualinterface; namespace it.unifi.dsi.stlab.networkreasoner.gas.system.tests { [TestFixture()] public class NetwonRaphsonSystemThreeNodesNetworkRepeatUntilConditions { GasNetwork aGasNetwork{ get; set; } [SetUp()] public void SetupNetwork () { this.aGasNetwork = new GasNetwork (); GasNodeAbstract nodeAwithSupplyGadget = this.makeNodeA (); GasNodeAbstract nodeBwithLoadGadget = this.makeNodeB (); GasNodeAbstract nodeCwithLoadGadger = this.makeNodeC (); GasEdgeAbstract edgeAB = this.makeEdgeAB ( nodeAwithSupplyGadget, nodeBwithLoadGadget); GasEdgeAbstract edgeCB = this.makeEdgeCB ( nodeCwithLoadGadger, nodeBwithLoadGadget); this.aGasNetwork.Nodes.Add ("nodeA", nodeAwithSupplyGadget); this.aGasNetwork.Nodes.Add ("nodeB", nodeBwithLoadGadget); this.aGasNetwork.Nodes.Add ("nodeC", nodeCwithLoadGadger); this.aGasNetwork.Edges.Add ("edgeAB", edgeAB); this.aGasNetwork.Edges.Add ("edgeCB", edgeCB); } GasNodeAbstract makeNodeA () { GasNodeAbstract supplyNode = new GasNodeTopological{ Comment = "node A with supply gadget", Height = 0, Identifier = "nA" }; GasNodeGadget supplyGadget = new GasNodeGadgetSupply{ MaxQ = 198.3, MinQ = 10.4, SetupPressure = 30 }; return new GasNodeWithGadget{ Equipped = supplyNode, Gadget = supplyGadget }; } GasNodeAbstract makeNodeB () { GasNodeAbstract supplyNode = new GasNodeTopological{ Comment = "node B with load gadget", Height = 0, Identifier = "nB" }; GasNodeGadget gadget = new GasNodeGadgetLoad{ Load = 0.0 }; return new GasNodeWithGadget{ Equipped = supplyNode, Gadget = gadget }; } GasNodeAbstract makeNodeC () { GasNodeAbstract supplyNode = new GasNodeTopological{ Comment = "node C with supply gadget", Height = 0, Identifier = "nC" }; GasNodeGadget gadget = new GasNodeGadgetLoad{ Load = 180.0 }; return new GasNodeWithGadget{ Equipped = supplyNode, Gadget = gadget }; } GasEdgeAbstract makeEdgeAB (GasNodeAbstract aStartNode, GasNodeAbstract anEndNode) { GasEdgeAbstract anEdgeAB = new GasEdgeTopological{ StartNode = aStartNode, EndNode = anEndNode, Identifier = "edgeAB" }; return new GasEdgePhysical{ Described = anEdgeAB, Length = 500, Roughness = 55, Diameter = 100, MaxSpeed = 10 }; } GasEdgeAbstract makeEdgeCB (GasNodeAbstract aStartNode, GasNodeAbstract anEndNode) { GasEdgeAbstract anEdgeCB = new GasEdgeTopological{ StartNode = aStartNode, EndNode = anEndNode, Identifier = "edgeCB" }; return new GasEdgePhysical{ Described = anEdgeCB, Length = 500, Roughness = 55, Diameter = 100, MaxSpeed = 10 }; } public AmbientParameters valid_initial_ambient_parameters () { AmbientParameters parameters = new AmbientParametersGas (); parameters.ElementName = "methane"; parameters.MolWeight = 16.0; parameters.ElementTemperatureInKelvin = 288.15; parameters.RefPressureInBar = 1.01325; parameters.RefTemperatureInKelvin = 288.15; parameters.AirPressureInBar = 1.01325; parameters.AirTemperatureInKelvin = 288.15; parameters.ViscosityInPascalTimesSecond = .0000108; return parameters; } class ComplexNetworkRunnableSystem : RunnableSystemCompute { protected override List<FluidDynamicSystemStateTransition> buildTransitionsSequence ( FluidDynamicSystemStateTransitionInitialization initializationTransition, FluidDynamicSystemStateTransitionNewtonRaphsonSolve solveTransition, FluidDynamicSystemStateTransitionNegativeLoadsChecker negativeLoadsCheckerTransition) { return new List<FluidDynamicSystemStateTransition>{ initializationTransition, solveTransition}; } } [Test()] public void do_mutation_via_repetition () { RunnableSystem runnableSystem = new ComplexNetworkRunnableSystem { LogConfigFileInfo = new FileInfo ( "log4net-configurations/for-three-nodes-network.xml"), Precision = 1e-4, UnknownInitialization = new UnknownInitializationSimplyRandomized () }; runnableSystem = new RunnableSystemWithDecorationComputeCompletedHandler{ DecoredRunnableSystem = runnableSystem, OnComputeCompletedHandler = checkAssertions }; runnableSystem.compute ("three nodes network system", this.aGasNetwork.Nodes, this.aGasNetwork.Edges, this.valid_initial_ambient_parameters ()); } void checkAssertions (String systemName, FluidDynamicSystemStateAbstract aSystemState) { Assert.That (aSystemState, Is.InstanceOf ( typeof(FluidDynamicSystemStateMathematicallySolved)) ); OneStepMutationResults results = (aSystemState as FluidDynamicSystemStateMathematicallySolved).MutationResult; var dimensionalUnknowns = results.makeUnknownsDimensional ().WrappedObject; var nodeA = results.StartingUnsolvedState.findNodeByIdentifier ("nA"); var nodeB = results.StartingUnsolvedState.findNodeByIdentifier ("nB"); var nodeC = results.StartingUnsolvedState.findNodeByIdentifier ("nC"); Assert.That (dimensionalUnknowns.valueAt (nodeA), Is.EqualTo (32.34).Within (1e-5)); Assert.That (dimensionalUnknowns.valueAt (nodeB), Is.EqualTo (32.34).Within (1e-5)); Assert.That (dimensionalUnknowns.valueAt (nodeC), Is.EqualTo (32.34).Within (1e-5)); var edgeAB = results.StartingUnsolvedState.findEdgeByIdentifier ("edgeAB"); var edgeCB = results.StartingUnsolvedState.findEdgeByIdentifier ("edgeCB"); Assert.That (results.Qvector.valueAt (edgeAB), Is.EqualTo (32.34).Within (1e-5)); Assert.That (results.Qvector.valueAt (edgeCB), Is.EqualTo (32.34).Within (1e-5)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace owin_scim_host.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Execution; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Tests ETF constituents universe selection with the algorithm framework models (Alpha, PortfolioConstruction, Execution) /// </summary> public class ETFConstituentUniverseFrameworkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private List<ETFConstituentData> ConstituentData = new List<ETFConstituentData>(); /// <summary> /// Initializes the algorithm, setting up the framework classes and ETF constituent universe settings /// </summary> public override void Initialize() { SetStartDate(2020, 12, 1); SetEndDate(2021, 1, 31); SetCash(100000); SetAlpha(new ETFConstituentAlphaModel()); SetPortfolioConstruction(new ETFConstituentPortfolioModel()); SetExecution(new ETFConstituentExecutionModel()); var spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); UniverseSettings.Resolution = Resolution.Hour; AddUniverse(Universe.ETF(spy, UniverseSettings, FilterETFConstituents)); } /// <summary> /// Filters ETF constituents /// </summary> /// <param name="constituents">ETF constituents</param> /// <returns>ETF constituent Symbols that we want to include in the algorithm</returns> public IEnumerable<Symbol> FilterETFConstituents(IEnumerable<ETFConstituentData> constituents) { var constituentData = constituents .Where(x => (x.Weight ?? 0m) >= 0.001m) .ToList(); ConstituentData = constituentData; return constituentData .Select(x => x.Symbol) .ToList(); } /// <summary> /// no-op for performance /// </summary> public override void OnData(Slice data) { } /// <summary> /// Alpha model for ETF constituents, where we generate insights based on the weighting /// of the ETF constituent /// </summary> private class ETFConstituentAlphaModel : IAlphaModel { public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { } /// <summary> /// Creates new insights based on constituent data and their weighting /// in their respective ETF /// </summary> public IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data) { var algo = (ETFConstituentUniverseFrameworkRegressionAlgorithm) algorithm; foreach (var constituent in algo.ConstituentData) { if (!data.Bars.ContainsKey(constituent.Symbol) && !data.QuoteBars.ContainsKey(constituent.Symbol)) { continue; } var insightDirection = constituent.Weight != null && constituent.Weight >= 0.01m ? InsightDirection.Up : InsightDirection.Down; yield return new Insight( algorithm.UtcTime, constituent.Symbol, TimeSpan.FromDays(1), InsightType.Price, insightDirection, 1 * (double)insightDirection, 1.0, weight: (double)(constituent.Weight ?? 0)); } } } /// <summary> /// Generates targets for ETF constituents, which will be set to the weighting /// of the constituent in their respective ETF /// </summary> private class ETFConstituentPortfolioModel : IPortfolioConstructionModel { private bool _hasAdded; /// <summary> /// Securities changed, detects if we've got new additions to the universe /// so that we don't try to trade every loop /// </summary> public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { _hasAdded = changes.AddedSecurities.Count != 0; } /// <summary> /// Creates portfolio targets based on the insights provided to us by the alpha model. /// Emits portfolio targets setting the quantity to the weight of the constituent /// in its respective ETF. /// </summary> public IEnumerable<IPortfolioTarget> CreateTargets(QCAlgorithm algorithm, Insight[] insights) { if (!_hasAdded) { yield break; } foreach (var insight in insights) { yield return new PortfolioTarget(insight.Symbol, (decimal) (insight.Weight ?? 0)); _hasAdded = false; } } } /// <summary> /// Executes based on ETF constituent weighting /// </summary> private class ETFConstituentExecutionModel : IExecutionModel { /// <summary> /// Liquidates if constituents have been removed from the universe /// </summary> public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { foreach (var change in changes.RemovedSecurities) { algorithm.Liquidate(change.Symbol); } } /// <summary> /// Creates orders for constituents that attempts to add /// the weighting of the constituent in our portfolio. The /// resulting algorithm portfolio weight might not be equal /// to the leverage of the ETF (1x, 2x, 3x, etc.) /// </summary> public void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets) { foreach (var target in targets) { algorithm.SetHoldings(target.Symbol, target.Quantity); } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "4"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "3.225%"}, {"Drawdown", "0.800%"}, {"Expectancy", "0"}, {"Net Profit", "0.520%"}, {"Sharpe Ratio", "1.518"}, {"Probabilistic Sharpe Ratio", "57.759%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.022"}, {"Beta", "0.101"}, {"Annual Standard Deviation", "0.022"}, {"Annual Variance", "0"}, {"Information Ratio", "-0.653"}, {"Tracking Error", "0.117"}, {"Treynor Ratio", "0.333"}, {"Total Fees", "$4.00"}, {"Estimated Strategy Capacity", "$1300000000.00"}, {"Lowest Capacity Asset", "AIG R735QTJ8XC9X"}, {"Fitness Score", "0.001"}, {"Kelly Criterion Estimate", "1.528"}, {"Kelly Criterion Probability Value", "0.091"}, {"Sortino Ratio", "4.929"}, {"Return Over Maximum Drawdown", "8.624"}, {"Portfolio Turnover", "0.001"}, {"Total Insights Generated", "1108"}, {"Total Insights Closed", "1080"}, {"Total Insights Analysis Completed", "1080"}, {"Long Insight Count", "277"}, {"Short Insight Count", "831"}, {"Long/Short Ratio", "33.33%"}, {"Estimated Monthly Alpha Value", "$4169774.3402"}, {"Total Accumulated Estimated Alpha Value", "$8322174.6207"}, {"Mean Population Estimated Insight Value", "$7705.7172"}, {"Mean Population Direction", "49.7222%"}, {"Mean Population Magnitude", "49.7222%"}, {"Rolling Averaged Population Direction", "56.0724%"}, {"Rolling Averaged Population Magnitude", "56.0724%"}, {"OrderListHash", "eb27e818f4a6609329a52feeb74bd554"} }; } }
// Copyright 2014, Google 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. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Dfp.Lib; using Google.Api.Ads.Dfp.Util.v201408; using Google.Api.Ads.Dfp.v201408; using System; namespace Google.Api.Ads.Dfp.Examples.CSharp.v201408 { /// <summary> /// This code example creates new line items. To determine which line items /// exist, run GetAllLineItems.cs. To determine which orders exist, run /// GetAllOrders.cs. To determine which placements exist, run /// GetAllPlacements.cs. To determine the IDs for locations, run /// GetAllCities.cs, GetAllCountries.cs, GetAllMetros.cs, GetAllRegions.cs and /// GetAllPostalCodes. /// /// Tags: LineItemService.createLineItems /// </summary> class CreateLineItems : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates new line items. To determine which line items " + "exist, run GetAllLineItems.cs. To determine which orders exist, run GetAllOrders.cs" + ". To determine which placements exist, run GetAllPlacements.cs. To determine the " + "IDs for locations, run GetAllCities.cs, GetAllCountries.cs, GetAllMetros.cs, " + "GetAllRegions.cs and GetAllPostalCodes."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { SampleBase codeExample = new CreateLineItems(); Console.WriteLine(codeExample.Description); codeExample.Run(new DfpUser()); } /// <summary> /// Run the code examples. /// </summary> /// <param name="user">The DFP user object running the code examples.</param> public override void Run(DfpUser user) { // Get the LineItemService. LineItemService lineItemService = (LineItemService) user.GetService(DfpService.v201408.LineItemService); // Set the order that all created line items will belong to and the // placement ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); long[] targetPlacementIds = new long[] {long.Parse(_T("INSERT_PLACEMENT_ID_HERE"))}; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); inventoryTargeting.targetedPlacementIds = targetPlacementIds; // Create geographical targeting. GeoTargeting geoTargeting = new GeoTargeting(); // Include the US and Quebec, Canada. Location countryLocation = new Location(); countryLocation.id = 2840L; Location regionLocation = new Location(); regionLocation.id = 20123L; geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation}; Location postalCodeLocation = new Location(); postalCodeLocation.id = 9000093; // Exclude Chicago and the New York metro area. Location cityLocation = new Location(); cityLocation.id = 1016367L; Location metroLocation = new Location(); metroLocation.id = 200501L; geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation}; // Exclude domains that are not under the network's control. UserDomainTargeting userDomainTargeting = new UserDomainTargeting(); userDomainTargeting.domains = new String[] {"usa.gov"}; userDomainTargeting.targeted = false; // Create day-part targeting. DayPartTargeting dayPartTargeting = new DayPartTargeting(); dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER; // Target only the weekend in the browser's timezone. DayPart saturdayDayPart = new DayPart(); saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201408.DayOfWeek.SATURDAY; saturdayDayPart.startTime = new TimeOfDay(); saturdayDayPart.startTime.hour = 0; saturdayDayPart.startTime.minute = MinuteOfHour.ZERO; saturdayDayPart.endTime = new TimeOfDay(); saturdayDayPart.endTime.hour = 24; saturdayDayPart.endTime.minute = MinuteOfHour.ZERO; DayPart sundayDayPart = new DayPart(); sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201408.DayOfWeek.SUNDAY; sundayDayPart.startTime = new TimeOfDay(); sundayDayPart.startTime.hour = 0; sundayDayPart.startTime.minute = MinuteOfHour.ZERO; sundayDayPart.endTime = new TimeOfDay(); sundayDayPart.endTime.hour = 24; sundayDayPart.endTime.minute = MinuteOfHour.ZERO; dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart}; // Create technology targeting. TechnologyTargeting technologyTargeting = new TechnologyTargeting(); // Create browser targeting. BrowserTargeting browserTargeting = new BrowserTargeting(); browserTargeting.isTargeted = true; // Target just the Chrome browser. Technology browserTechnology = new Technology(); browserTechnology.id = 500072L; browserTargeting.browsers = new Technology[] {browserTechnology}; technologyTargeting.browserTargeting = browserTargeting; // Create an array to store local line item objects. LineItem[] lineItems = new LineItem[5]; for (int i = 0; i < 5; i++) { LineItem lineItem = new LineItem(); lineItem.name = "Line item #" + i; lineItem.orderId = orderId; lineItem.targeting = new Targeting(); lineItem.targeting.inventoryTargeting = inventoryTargeting; lineItem.targeting.geoTargeting = geoTargeting; lineItem.targeting.userDomainTargeting = userDomainTargeting; lineItem.targeting.dayPartTargeting = dayPartTargeting; lineItem.targeting.technologyTargeting = technologyTargeting; lineItem.lineItemType = LineItemType.STANDARD; lineItem.allowOverbook = true; // Set the creative rotation type to even. lineItem.creativeRotationType = CreativeRotationType.EVEN; // Set the size of creatives that can be associated with this line item. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; // Create the creative placeholder. CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder}; // Set the length of the line item to run. //lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1)); // Set the cost per unit to $2. lineItem.costType = CostType.CPM; lineItem.costPerUnit = new Money(); lineItem.costPerUnit.currencyCode = "USD"; lineItem.costPerUnit.microAmount = 2000000L; // Set the number of units bought to 500,000 so that the budget is // $1,000. Goal goal = new Goal(); goal.goalType = GoalType.LIFETIME; goal.unitType = UnitType.IMPRESSIONS; goal.units = 500000L; lineItem.primaryGoal = goal; lineItems[i] = lineItem; } try { // Create the line items on the server. lineItems = lineItemService.createLineItems(lineItems); if (lineItems != null) { foreach (LineItem lineItem in lineItems) { Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and" + " named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name); } } else { Console.WriteLine("No line items created."); } } catch (Exception ex) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", ex.Message); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector64_UInt32() { var test = new LoadUnaryOpTest__LoadVector64_UInt32(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector64_UInt32 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector64_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector64( (UInt32*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector64), new Type[] { typeof(UInt32*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector64<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector64)}<UInt32>(Vector64<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// --------------------------------------------------------------------------- // <copyright file="UserId.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the UserId class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; /// <summary> /// Represents the Id of a user. /// </summary> public sealed class UserId : ComplexProperty { private string sID; private string primarySmtpAddress; private string displayName; private StandardUser? standardUser; /// <summary> /// Initializes a new instance of the <see cref="UserId"/> class. /// </summary> public UserId() : base() { } /// <summary> /// Initializes a new instance of the <see cref="UserId"/> class. /// </summary> /// <param name="primarySmtpAddress">The primary SMTP address used to initialize the UserId.</param> public UserId(string primarySmtpAddress) : this() { this.primarySmtpAddress = primarySmtpAddress; } /// <summary> /// Initializes a new instance of the <see cref="UserId"/> class. /// </summary> /// <param name="standardUser">The StandardUser value used to initialize the UserId.</param> public UserId(StandardUser standardUser) : this() { this.standardUser = standardUser; } /// <summary> /// Determines whether this instance is valid. /// </summary> /// <returns><c>true</c> if this instance is valid; otherwise, <c>false</c>.</returns> internal bool IsValid() { return this.StandardUser.HasValue || !string.IsNullOrEmpty(this.PrimarySmtpAddress) || !string.IsNullOrEmpty(this.SID); } /// <summary> /// Gets or sets the SID of the user. /// </summary> public string SID { get { return this.sID; } set { this.SetFieldValue<string>(ref this.sID, value); } } /// <summary> /// Gets or sets the primary SMTP address or the user. /// </summary> public string PrimarySmtpAddress { get { return this.primarySmtpAddress; } set { this.SetFieldValue<string>(ref this.primarySmtpAddress, value); } } /// <summary> /// Gets or sets the display name of the user. /// </summary> public string DisplayName { get { return this.displayName; } set { this.SetFieldValue<string>(ref this.displayName, value); } } /// <summary> /// Gets or sets a value indicating which standard user the user represents. /// </summary> public StandardUser? StandardUser { get { return this.standardUser; } set { this.SetFieldValue<StandardUser?>(ref this.standardUser, value); } } /// <summary> /// Implements an implicit conversion between a string representing a primary SMTP address and UserId. /// </summary> /// <param name="primarySmtpAddress">The string representing a primary SMTP address.</param> /// <returns>A UserId initialized with the specified primary SMTP address.</returns> public static implicit operator UserId(string primarySmtpAddress) { return new UserId(primarySmtpAddress); } /// <summary> /// Implements an implicit conversion between StandardUser and UserId. /// </summary> /// <param name="standardUser">The standard user used to initialize the user Id.</param> /// <returns>A UserId initialized with the specified standard user value.</returns> public static implicit operator UserId(StandardUser standardUser) { return new UserId(standardUser); } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.SID: this.sID = reader.ReadValue(); return true; case XmlElementNames.PrimarySmtpAddress: this.primarySmtpAddress = reader.ReadValue(); return true; case XmlElementNames.DisplayName: this.displayName = reader.ReadValue(); return true; case XmlElementNames.DistinguishedUser: this.standardUser = reader.ReadValue<StandardUser>(); return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.SID: this.sID = jsonProperty.ReadAsString(key); break; case XmlElementNames.PrimarySmtpAddress: this.primarySmtpAddress = jsonProperty.ReadAsString(key); break; case XmlElementNames.DisplayName: this.displayName = jsonProperty.ReadAsString(key); break; case XmlElementNames.DistinguishedUser: this.standardUser = jsonProperty.ReadEnumValue<StandardUser>(key); break; default: break; } } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.SID, this.SID); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.PrimarySmtpAddress, this.PrimarySmtpAddress); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DisplayName, this.DisplayName); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DistinguishedUser, this.StandardUser); } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonProperty = new JsonObject(); jsonProperty.Add(XmlElementNames.SID, this.SID); jsonProperty.Add(XmlElementNames.PrimarySmtpAddress, this.PrimarySmtpAddress); jsonProperty.Add(XmlElementNames.DisplayName, this.DisplayName); if (this.StandardUser.HasValue) { jsonProperty.Add(XmlElementNames.DistinguishedUser, this.StandardUser.Value); } return jsonProperty; } } }
using System; using System.IO; namespace CatLib._3rd.SharpCompress.Compressors.LZMA.RangeCoder { internal class Encoder { public const uint kTopValue = (1 << 24); private Stream Stream; public UInt64 Low; public uint Range; private uint _cacheSize; private byte _cache; //long StartPosition; public void SetStream(Stream stream) { Stream = stream; } public void ReleaseStream() { Stream = null; } public void Init() { //StartPosition = Stream.Position; Low = 0; Range = 0xFFFFFFFF; _cacheSize = 1; _cache = 0; } public void FlushData() { for (int i = 0; i < 5; i++) { ShiftLow(); } } public void FlushStream() { Stream.Flush(); } public void CloseStream() { Stream.Dispose(); } public void Encode(uint start, uint size, uint total) { Low += start * (Range /= total); Range *= size; while (Range < kTopValue) { Range <<= 8; ShiftLow(); } } public void ShiftLow() { if ((uint)Low < 0xFF000000 || (uint)(Low >> 32) == 1) { byte temp = _cache; do { Stream.WriteByte((byte)(temp + (Low >> 32))); temp = 0xFF; } while (--_cacheSize != 0); _cache = (byte)(((uint)Low) >> 24); } _cacheSize++; Low = ((uint)Low) << 8; } public void EncodeDirectBits(uint v, int numTotalBits) { for (int i = numTotalBits - 1; i >= 0; i--) { Range >>= 1; if (((v >> i) & 1) == 1) { Low += Range; } if (Range < kTopValue) { Range <<= 8; ShiftLow(); } } } public void EncodeBit(uint size0, int numTotalBits, uint symbol) { uint newBound = (Range >> numTotalBits) * size0; if (symbol == 0) { Range = newBound; } else { Low += newBound; Range -= newBound; } while (Range < kTopValue) { Range <<= 8; ShiftLow(); } } public long GetProcessedSizeAdd() { return -1; //return _cacheSize + Stream.Position - StartPosition + 4; // (long)Stream.GetProcessedSize(); } } internal class Decoder { public const uint kTopValue = (1 << 24); public uint Range; public uint Code; // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); public Stream Stream; public long Total; public void Init(Stream stream) { // Stream.Init(stream); Stream = stream; Code = 0; Range = 0xFFFFFFFF; for (int i = 0; i < 5; i++) { Code = (Code << 8) | (byte)Stream.ReadByte(); } Total = 5; } public void ReleaseStream() { // Stream.ReleaseStream(); Stream = null; } public void CloseStream() { Stream.Dispose(); } public void Normalize() { while (Range < kTopValue) { Code = (Code << 8) | (byte)Stream.ReadByte(); Range <<= 8; Total++; } } public void Normalize2() { if (Range < kTopValue) { Code = (Code << 8) | (byte)Stream.ReadByte(); Range <<= 8; Total++; } } public uint GetThreshold(uint total) { return Code / (Range /= total); } public void Decode(uint start, uint size) { Code -= start * Range; Range *= size; Normalize(); } public uint DecodeDirectBits(int numTotalBits) { uint range = Range; uint code = Code; uint result = 0; for (int i = numTotalBits; i > 0; i--) { range >>= 1; /* result <<= 1; if (code >= range) { code -= range; result |= 1; } */ uint t = (code - range) >> 31; code -= range & (t - 1); result = (result << 1) | (1 - t); if (range < kTopValue) { code = (code << 8) | (byte)Stream.ReadByte(); range <<= 8; Total++; } } Range = range; Code = code; return result; } public uint DecodeBit(uint size0, int numTotalBits) { uint newBound = (Range >> numTotalBits) * size0; uint symbol; if (Code < newBound) { symbol = 0; Range = newBound; } else { symbol = 1; Code -= newBound; Range -= newBound; } Normalize(); return symbol; } public bool IsFinished { get { return Code == 0; } } // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ResetLowestSetBitUInt64() { var test = new ScalarUnaryOpTest__ResetLowestSetBitUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarUnaryOpTest__ResetLowestSetBitUInt64 { private struct TestStruct { public UInt64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetUInt64(); return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__ResetLowestSetBitUInt64 testClass) { var result = Bmi1.X64.ResetLowestSetBit(_fld); testClass.ValidateResult(_fld, result); } } private static UInt64 _data; private static UInt64 _clsVar; private UInt64 _fld; static ScalarUnaryOpTest__ResetLowestSetBitUInt64() { _clsVar = TestLibrary.Generator.GetUInt64(); } public ScalarUnaryOpTest__ResetLowestSetBitUInt64() { Succeeded = true; _fld = TestLibrary.Generator.GetUInt64(); _data = TestLibrary.Generator.GetUInt64(); } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.ResetLowestSetBit( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.ResetLowestSetBit), new Type[] { typeof(UInt64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) }); ValidateResult(_data, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.ResetLowestSetBit( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)); var result = Bmi1.X64.ResetLowestSetBit(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__ResetLowestSetBitUInt64(); var result = Bmi1.X64.ResetLowestSetBit(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.ResetLowestSetBit(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.ResetLowestSetBit(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(UInt64 data, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; isUnexpectedResult = (((data - 1) & data) != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.ResetLowestSetBit)}<UInt64>(UInt64): ResetLowestSetBit failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace AWTY.Http.IntegrationTests { using TestApplication; /// <summary> /// Integration tests for <see cref="ProgressHandler"/>. /// </summary> [Collection("NeedsTestServer")] public class ProgressHandlerTests { /// <summary> /// Create a new HTTP progress handler integration-test suite. /// </summary> /// <param name="testServer"> /// The server used for test requests. /// </param> /// <param name="testOutput"> /// XUnit test output. /// </param> public ProgressHandlerTests(TestServer testServer, ITestOutputHelper testOutput) { if (testServer == null) throw new ArgumentNullException(nameof(testServer)); if (testOutput == null) throw new ArgumentNullException(nameof(testOutput)); TestServer = testServer; Output = testOutput; TestServer.Start(Output); } /// <summary> /// Dispose of resources being used by the test suite. /// </summary> public void Dispose() { TestServer?.Dispose(); } /// <summary> /// The server used for test requests. /// </summary> TestServer TestServer { get; } /// <summary> /// XUnit test output. /// </summary> ITestOutputHelper Output { get; } /// <summary> /// Retrieve a response payload with progress reporting. /// </summary> /// <param name="bufferSize"> /// The buffer size for transferring data. /// </param> /// <param name="payloadSize"> /// The number of bytes in the payload. /// </param> /// <param name="minPercentage"> /// The minimum change in percentage to capture. /// </param> /// <param name="expectedPercentages"> /// An array of expected percentage values. /// </param> [Theory] [MemberData(nameof(GetPostData))] public async Task Get(int bufferSize, int payloadSize, int minPercentage, int[] expectedPercentages) { List<int> actualPercentages = new List<int>(); ProgressHandler progressHandler = CreateResponseProgressHandler(bufferSize); progressHandler.ResponseStarted.Subscribe(responseStarted => { responseStarted.Progress.Percentage(minPercentage).Subscribe(progress => { Output.WriteLine("{0}% ({1}/{2})", progress.PercentComplete, progress.Current, progress.Total); actualPercentages.Add(progress.PercentComplete); }); }); using (HttpClient client = TestServer.CreateClient(progressHandler)) { using (HttpResponseMessage response = await client.GetAsync($"test/data?length={payloadSize}", HttpCompletionOption.ResponseHeadersRead)) { foreach (var header in response.Headers) { Output.WriteLine("ResponseHeader: '{0}' -> '{1}'", header.Key, String.Join(",", header.Value) ); } foreach (var header in response.Content.Headers) { Output.WriteLine("ContentHeader: '{0}' -> '{1}'", header.Key, String.Join(",", header.Value) ); } string responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(payloadSize, responseContent.Length); } } Assert.Equal(expectedPercentages.Length, actualPercentages.Count); Assert.Equal(expectedPercentages, actualPercentages); } /// <summary> /// Send a request payload with progress reporting. /// </summary> /// <param name="bufferSize"> /// The buffer size for transferring data. /// </param> /// <param name="payloadSize"> /// The number of bytes in the payload. /// </param> /// <param name="minPercentage"> /// The minimum change in percentage to capture. /// </param> /// <param name="expectedPercentages"> /// An array of expected percentage values. /// </param> [Theory] [MemberData(nameof(GetPostData))] public async Task Post(int bufferSize, int payloadSize, int minPercentage, int[] expectedPercentages) { List<int> actualPercentages = new List<int>(); ProgressHandler progressHandler = CreateRequestProgressHandler(bufferSize); progressHandler.RequestStarted.Subscribe(requestStarted => { requestStarted.Progress.Percentage(5).Subscribe(progress => { actualPercentages.Add(progress.PercentComplete); Output.WriteLine("{0}% ({1}/{2})", progress.PercentComplete, progress.Current, progress.Total); }); }); using (HttpClient client = TestServer.CreateClient(progressHandler)) { // Use a streaming request because buffering breaks progress reporting. HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "test/echo") { Content = new StreamContent(FillMemoryStream(payloadSize)) { Headers = { ContentLength = payloadSize } } }; using (request) using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Output.WriteLine("StatusCode: {0}", response.StatusCode); foreach (var header in response.Headers) { Output.WriteLine("ResponseHeader: '{0}' -> '{1}'", header.Key, String.Join(",", header.Value) ); } foreach (var header in response.Content.Headers) { Output.WriteLine("ContentHeader: '{0}' -> '{1}'", header.Key, String.Join(",", header.Value) ); } string responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(payloadSize, responseContent.Length); } } Assert.Equal(expectedPercentages.Length, actualPercentages.Count); Assert.Equal(expectedPercentages, actualPercentages); } /// <summary> /// Data for the <see cref="Get"/> and <see cref="Post"/> theories. /// </summary> public static IEnumerable<object[]> GetPostData { get { yield return TestData.ProgressHandlerRow( bufferSize: 1024, responseSize: 10 * 1024, minPercentage: 5, expectedPercentages: new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 } ); yield return TestData.ProgressHandlerRow( bufferSize: 4096, responseSize: 50 * 1024 * 1024, minPercentage: 5, expectedPercentages: new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 } ); } } /// <summary> /// Create a <see cref="ProgressHandler"/> for use in tests that publishes progress for requests. /// </summary> /// <param name="bufferSize"> /// The buffer size to use when transferring content. /// </param> /// <returns> /// The configured <see cref="ProgressHandler"/>. /// </returns> ProgressHandler CreateRequestProgressHandler(int bufferSize) { ProgressHandler progressHandler = new ProgressHandler( nextHandler: new HttpClientHandler(), progressTypes: HttpProgressTypes.Request, bufferSize: bufferSize ); return progressHandler; } /// <summary> /// Create a <see cref="ProgressHandler"/> for use in tests that publishes progress for responses. /// </summary> /// <param name="bufferSize"> /// The buffer size to use when transferring content. /// </param> /// <returns> /// The configured <see cref="ProgressHandler"/>. /// </returns> ProgressHandler CreateResponseProgressHandler(int bufferSize) { ProgressHandler progressHandler = new ProgressHandler( nextHandler: new HttpClientHandler(), progressTypes: HttpProgressTypes.Response, bufferSize: bufferSize ); return progressHandler; } /// <summary> /// Fill a <see cref="MemoryStream"/> with data. /// </summary> /// <param name="size"> /// The number of bytes to write to the stream. /// </param> /// <returns> /// The <see cref="MemoryStream"/> (actually a <see cref="DumbMemoryStream"/>). /// </returns> MemoryStream FillMemoryStream(int size) { DumbMemoryStream memoryStream = new DumbMemoryStream(); StreamWriter writer = new StreamWriter(memoryStream); writer.Write( new String('x', size) ); writer.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream; } } }
//--------------------------------------------------------------------------- // // <copyright file="QuaternionRotation3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class QuaternionRotation3D : Rotation3D { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new QuaternionRotation3D Clone() { return (QuaternionRotation3D)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new QuaternionRotation3D CloneCurrentValue() { return (QuaternionRotation3D)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void QuaternionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { QuaternionRotation3D target = ((QuaternionRotation3D) d); target._cachedQuaternionValue = (Quaternion)e.NewValue; target.PropertyChanged(QuaternionProperty); } #region Public Properties /// <summary> /// Quaternion - Quaternion. Default value is Quaternion.Identity. /// </summary> public Quaternion Quaternion { get { ReadPreamble(); return _cachedQuaternionValue; } set { SetValueInternal(QuaternionProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new QuaternionRotation3D(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Obtain handles for animated properties DUCE.ResourceHandle hQuaternionAnimations = GetAnimationResourceHandle(QuaternionProperty, channel); // Pack & send command packet DUCE.MILCMD_QUATERNIONROTATION3D data; unsafe { data.Type = MILCMD.MilCmdQuaternionRotation3D; data.Handle = _duceResource.GetHandle(channel); if (hQuaternionAnimations.IsNull) { data.quaternion = CompositionResourceManager.QuaternionToMilQuaternionF(Quaternion); } data.hQuaternionAnimations = hQuaternionAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_QUATERNIONROTATION3D)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_QUATERNIONROTATION3D)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // Quaternion // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the QuaternionRotation3D.Quaternion property. /// </summary> public static readonly DependencyProperty QuaternionProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields private Quaternion _cachedQuaternionValue = Quaternion.Identity; internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Quaternion s_Quaternion = Quaternion.Identity; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static QuaternionRotation3D() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(QuaternionRotation3D); QuaternionProperty = RegisterProperty("Quaternion", typeof(Quaternion), typeofThis, Quaternion.Identity, new PropertyChangedCallback(QuaternionPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !NET40 namespace ProductivityApiTests { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.TestHelpers; using System.IO; using System.Linq; using System.Transactions; using SimpleModel; using Xunit; public class SimpleScenariosForLocalDb : FunctionalTestBase, IDisposable { #region Infrastructure/setup private readonly object _previousDataDirectory; public SimpleScenariosForLocalDb() { _previousDataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory"); AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetTempPath()); MutableResolver.AddResolver<IDbConnectionFactory>(k => new LocalDbConnectionFactory("v11.0")); } [Fact] public void Scenario_Find() { using (var context = new SimpleLocalDbModelContext()) { var product = context.Products.Find(1); var category = context.Categories.Find("Foods"); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Foods", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Vegemite" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotEqual(0, product.Id); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } public void Dispose() { try { // Ensure LocalDb databases are deleted after use so that LocalDb doesn't throw if // the temp location in which they are stored is later cleaned. using (var context = new SimpleLocalDbModelContext()) { context.Database.Delete(); } using (var context = new LocalDbLoginsContext()) { context.Database.Delete(); } using (var context = new ModelWithWideProperties()) { context.Database.Delete(); } Database.Delete("Scenario_CodeFirstWithModelBuilder"); Database.Delete("Scenario_Use_AppConfig_LocalDb_connection_string"); } finally { MutableResolver.ClearResolvers(); AppDomain.CurrentDomain.SetData("DataDirectory", _previousDataDirectory); } } #endregion #region Scenarios for SQL Server LocalDb using LocalDbConnectionFactory [Fact] [UseDefaultExecutionStrategy] public void SqlServer_Database_can_be_created_with_columns_that_explicitly_total_more_that_8060_bytes_and_data_longer_than_8060_can_be_inserted() { EnsureDatabaseInitialized(() => new ModelWithWideProperties()); using (new TransactionScope()) { using (var context = new ModelWithWideProperties()) { var entity = new EntityWithExplicitWideProperties { Property1 = new String('1', 1000), Property2 = new String('2', 1000), Property3 = new String('3', 1000), Property4 = new String('4', 1000), }; context.ExplicitlyWide.Add(entity); context.SaveChanges(); entity.Property1 = new String('A', 4000); entity.Property2 = new String('B', 4000); context.SaveChanges(); } } } [Fact] [UseDefaultExecutionStrategy] public void SqlServer_Database_can_be_created_with_columns_that_implicitly_total_more_that_8060_bytes_and_data_longer_than_8060_can_be_inserted() { EnsureDatabaseInitialized(() => new ModelWithWideProperties()); using (new TransactionScope()) { using (var context = new ModelWithWideProperties()) { var entity = new EntityWithImplicitWideProperties { Property1 = new String('1', 1000), Property2 = new String('2', 1000), Property3 = new String('3', 1000), Property4 = new String('4', 1000), }; context.ImplicitlyWide.Add(entity); context.SaveChanges(); entity.Property1 = new String('A', 4000); entity.Property2 = new String('B', 4000); context.SaveChanges(); } } } [Fact] public void Scenario_Insert() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Vegemite" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotEqual(0, product.Id); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Update() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = context.Products.Find(1); product.Name = "iSnack 2.0"; context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Equal("iSnack 2.0", product.Name); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Query() { using (var context = new SimpleLocalDbModelContext()) { var products = context.Products.ToList(); // Scenario ends; simple validation of final state follows Assert.Equal(7, products.Count); Assert.True(products.TrueForAll(p => GetStateEntry(context, p).State == EntityState.Unchanged)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Relate_using_query() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var category = context.Categories.Find("Foods"); var product = new Product { Name = "Bovril", Category = category }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Foods", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Relate_using_FK() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Bovril", CategoryId = "Foods" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal("Foods", product.CategoryId); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_CodeFirst_with_ModelBuilder() { Database.Delete("Scenario_CodeFirstWithModelBuilder"); var builder = new DbModelBuilder(); builder.Entity<Product>(); builder.Entity<Category>(); var model = builder.Build(ProviderRegistry.Sql2008_ProviderInfo).Compile(); using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_CodeFirstWithModelBuilder", model)) { InsertIntoCleanContext(context); } using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_CodeFirstWithModelBuilder", model)) { ValidateFromCleanContext(context); } } private void ValidateFromCleanContext(SimpleLocalDbModelContextWithNoData context) { var product = context.Products.Find(1); var category = context.Categories.Find("Large Hadron Collider"); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Large Hadron Collider", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } private void InsertIntoCleanContext(SimpleLocalDbModelContextWithNoData context) { context.Categories.Add( new Category { Id = "Large Hadron Collider" }); context.Products.Add( new Product { Name = "Higgs Boson", CategoryId = "Large Hadron Collider" }); context.SaveChanges(); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } [Fact] public void Scenario_Using_two_databases() { EnsureDatabaseInitialized(() => new LocalDbLoginsContext()); EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new LocalDbLoginsContext()) { var login = new Login { Id = Guid.NewGuid(), Username = "elmo" }; context.Logins.Add(login); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Same(login, context.Logins.Find(login.Id)); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, login).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } using (var context = new SimpleLocalDbModelContext()) { var category = new Category { Id = "Books" }; var product = new Product { Name = "The Unbearable Lightness of Being", Category = category }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Books", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Use_AppConfig_connection_string() { Database.Delete("Scenario_Use_AppConfig_LocalDb_connection_string"); using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_Use_AppConfig_LocalDb_connection_string")) { Assert.Equal("Scenario_Use_AppConfig_LocalDb", context.Database.Connection.Database); InsertIntoCleanContext(context); } using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_Use_AppConfig_LocalDb_connection_string")) { ValidateFromCleanContext(context); } } [Fact] public void Scenario_Include() { using (var context = new SimpleLocalDbModelContext()) { context.Configuration.LazyLoadingEnabled = false; var products = context.Products.Where(p => p != null).Include("Category").ToList(); foreach (var product in products) { Assert.NotNull(product.Category); } Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_IncludeWithLambda() { using (var context = new SimpleLocalDbModelContext()) { context.Configuration.LazyLoadingEnabled = false; var products = context.Products.Where(p => p != null).Include(p => p.Category).ToList(); foreach (var product in products) { Assert.NotNull(product.Category); } Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } #endregion } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AxTrioPCLib; using System.Windows.Forms; using System.Threading; namespace RCCM { /// <summary> /// Class representing Trio stepper motor controller /// </summary> public class TrioController { /// <summary> /// Enum constant identifying controller port as an ethernet connection /// </summary> public static short PORT_TYPE = 2; /// <summary> /// Port id used to connect to controller /// </summary> public static short PORT_ID = 3240; /// <summary> /// Static IP address of controller /// </summary> public static string IP = "192.168.0.250"; /// <summary> /// Number of axes on controller /// </summary> public static short NUMBER_AXES = 8; /// <summary> /// Enum value identifying a step-direction stepper driver type /// </summary> public static short ATYPE = 43; /// <summary> /// Property names accessible for each motor /// </summary> public static string[] AX_PROPERTIES = { "ATYPE", "P_GAIN", "I_GAIN", "D_GAIN", "OV_GAIN", "VFF_GAIN", "UNITS", "SPEED", "ACCEL", "DECEL", "CREEP", "JOGSPEED", "FE_LIMIT", "DAC", "SERVO", "REP_DIST", "FWD_IN", "REV_IN", "DATUM_IN", "FS_LIMIT", "RS_LIMIT", "MTYPE", "NTYPE", "MPOS", "DPOS", "FE", "AXISSTATUS" }; /// <summary> /// ActiveX control for Trio controller /// </summary> private AxTrioPC triopc; /// <summary> /// Indicates whether or not controller is connected and port is opened /// </summary> public bool Open { get; private set; } /// <summary> /// Connect to and initialize Trio controller /// </summary> /// <param name="axTrioPC">Trio ActviveX control</param> public TrioController(AxTrioPC axTrioPC) { this.triopc = axTrioPC; this.triopc.HostAddress = TrioController.IP; this.Open = this.triopc.Open(TrioController.PORT_TYPE, TrioController.PORT_ID); for (short ax = 0; ax < TrioController.NUMBER_AXES; ax++) { this.triopc.SetAxisVariable("ATYPE", ax, TrioController.ATYPE); this.triopc.SetAxisVariable("SERVO", ax, 0); } if (this.Open) { this.triopc.SetVariable("WDOG", 1); } else { MessageBox.Show("Could not connect to motion controler. Non-virtual axes are disabled"); } } /// <summary> /// Check if an axis is currently moving /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>True if axis is performing a motion</returns> public bool isMoving(short nAxis) { double distRemaining; this.triopc.GetAxisVariable("REMAIN", nAxis, out distRemaining); return Math.Abs(distRemaining) > 0.001; } /// <summary> /// Get all axis property values /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>Array of property values with indices corresponding to TrioController.AX_PROPERTIES</returns> public double[] GetAllAxisProperties(short nAxis) { // Double which will store read property value double dReadVar; // double[] properties = new double[TrioController.AX_PROPERTIES.Length]; for (int i = 0; i < properties.Length; i++) { // Read property into dReadVar if (this.triopc.IsOpen(TrioController.PORT_ID) && this.triopc.GetAxisVariable(TrioController.AX_PROPERTIES[i], nAxis, out dReadVar)) { properties[i] = dReadVar; } } return properties; } /// <summary> /// Get a specified property of a motor /// </summary> /// <param name="property">Name of property to check</param> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>Specified property value</returns> public double GetAxisProperty(string property, short nAxis) { double dReadVar; if (this.triopc.IsOpen(TrioController.PORT_ID) && this.triopc.GetAxisVariable(property, nAxis, out dReadVar)) { return dReadVar; } throw new Exception(string.Format("Invalid property: {0}", property)); } /// <summary> /// Set a specified property of a motor /// </summary> /// <param name="property">Name of property to check</param> /// <param name="value">Newe value of property</param> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>True if value was set successfully</returns> public bool SetAxisProperty(string property, double value, short nAxis) { if (this.triopc.IsOpen(TrioController.PORT_ID)) { return this.triopc.SetAxisVariable(property, nAxis, value); } throw new Exception(string.Format("Invalid property: {0}", property)); } /// <summary> /// Get property value (could be axis or controller property) /// </summary> /// <param name="property">Property name</param> /// <param name="value">Property value</param> /// <returns>True if successful</returns> public bool SetProperty(string property, double value) { if (this.triopc.IsOpen(TrioController.PORT_ID)) { return this.triopc.SetVariable(property, value); } return false; } /// <summary> /// Get property value (could be axis or controller property) /// </summary> /// <param name="property">Property name</param> /// <returns>Current property value</returns> public double GetProperty(string property) { double dReadVar; if (this.triopc.IsOpen(TrioController.PORT_ID) && this.triopc.GetVariable(property, out dReadVar)) { return dReadVar; } throw new Exception("Invalid property"); } /// <summary> /// Move a specified actuator to a new coordinate /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <param name="pos">New position of axis</param> /// <returns>True if command was sent successfully</returns> public bool MoveAbs(short nAxis, double pos) { double movesBuffered = 0; this.triopc.GetAxisVariable("MOVE_COUNT", nAxis, out movesBuffered); // If moves are buffered, cancel them and wait for them to end if (movesBuffered > 0.01) { Console.WriteLine("buffered moves?"); this.triopc.Cancel(0, nAxis); // Cancel current move this.triopc.Cancel(1, nAxis); // Cancel buffered move this.WaitForEndOfMove(nAxis); // Wait for axis to stop } return this.triopc.MoveAbs(1, pos, nAxis); // Send new move command } /// <summary> /// Move a specified distance from current actuator position /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <param name="pos">Distance to move</param> /// <returns>True if command was sent successfully</returns> public bool MoveRel(short nAxis, double pos) { return this.triopc.MoveRel(1, pos, nAxis); } /// <summary> /// Begin moving an actuator continuously /// </summary> /// <param name="fwd">Flag to indicate if actuator should move forward or backward</param> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>True if command was sent successfully</returns> public bool Jog(bool fwd, short nAxis) { if (fwd) { return this.triopc.Forward(nAxis); } return this.triopc.Reverse(nAxis); } /// <summary> /// Stop continuous actuator motion /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> /// <returns>True if command was sent successfully</returns> public bool JogStop(short nAxis) { bool status1 = this.triopc.Cancel(0, nAxis); // Cancel current move bool status2 = this.triopc.Cancel(1, nAxis); // Cancel buffered moves return status1 && status2; } /// <summary> /// Set current actuator position as 0 and clear errors /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> public void Zero(short nAxis) { this.triopc.Datum(0, nAxis); } /// <summary> /// Define current actuator position as a new numeric position /// </summary> /// <param name="value">Corrected current actuator position</param> public void FixPosition(double value, short nAxis) { this.triopc.Base(1, nAxis); this.triopc.Execute("DEFPOS(" + value.ToString() + ")"); } /// <summary> /// Stop all moving actuators /// </summary> /// <returns>True if command was sent successfully</returns> public bool Stop() { return this.triopc.RapidStop(); } /// <summary> /// Blocking function that completes once current actuator motion completes /// </summary> /// <param name="nAxis">Number (0-7) of port where axis is connected to trio controller</param> public void WaitForEndOfMove(short nAxis) { double distRemaining = 0; bool bWaiting; this.triopc.GetAxisVariable("REMAIN", nAxis, out distRemaining); bWaiting = Math.Abs(distRemaining) > 0.001; while (bWaiting) { Console.WriteLine("waiting"); Thread.Sleep(100); this.triopc.GetAxisVariable("REMAIN", nAxis, out distRemaining); bWaiting = Math.Abs(distRemaining) > 0.001; } } } }
using System; using System.Linq; using System.Collections.Generic; using Microsoft.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; using msFormatter = Microsoft.CodeAnalysis.Formatting.Formatter; namespace RoslynIntellisense { public static class Formatter { static Formatter() { AppDomainHelper.Init(); } static MSBuildWorkspace dummyWorkspace; static MSBuildWorkspace DummyWorkspace { get { if (dummyWorkspace == null) { //https://github.com/dotnet/roslyn/issues/202 dummyWorkspace = MSBuildWorkspace.Create(); //var opt = workspace.Options; //.WithChangedOption(CSharpFormattingOptions.SpaceBeforeDot, true) //.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, false) //.WithChangedOption(CSharpFormattingOptions.OpenBracesInNewLineForMethods, false) //.WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, 2); //msFormatter.Format(tree.GetRoot(), DummyWorkspace, opt); } return dummyWorkspace; } } public static string Format(string code, string file) { return Format(code, false, file); } public static string FormatHybrid(string code, string file) { return Format(code, true, file); } static string Format(string code, bool normaliseLines, string file) { bool isVB = file.EndsWith(".vb", StringComparison.OrdinalIgnoreCase); if (isVB) return FormatVB(code, normaliseLines); else return FormatCS(code, normaliseLines); } static string FormatCS(string code, bool normaliseLines) { var result = ""; SyntaxTree tree = code.Trim().ParseAsCs(); SyntaxNode root = msFormatter.Format(tree.GetRoot(), DummyWorkspace); if (normaliseLines) { //injecting line-breaks to separate declarations var declarations = root.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.MethodDeclaration) || n.IsKind(SyntaxKind.ClassDeclaration) || n.IsKind(SyntaxKind.LocalDeclarationStatement) || n.IsNewBlockStatement() || n.IsNewDeclarationBlock()) .ToList(); root = root.ReplaceNodes(declarations, (_, node) => { var isPrevLocalDeclaration = declarations.Prev(node).IsKind(SyntaxKind.LocalDeclarationStatement); var isLocalDeclaration = node.IsKind(SyntaxKind.LocalDeclarationStatement); var supressEmptyLineInsertion = isPrevLocalDeclaration && isLocalDeclaration; var existingTrivia = node.GetLeadingTrivia().ToFullString(); if (existingTrivia.Contains(Environment.NewLine) || supressEmptyLineInsertion) return node; else return node.WithLeadingTrivia(SyntaxFactory.Whitespace(Environment.NewLine + existingTrivia)); }); result = root.ToFullString() .NormalizeLine(root, false); } else result = root.ToFullString(); return result; } static string FormatVB(string code, bool normaliseLines) { var result = ""; SyntaxTree tree = code.Trim().ParseAsVb(); SyntaxNode root = msFormatter.Format(tree.GetRoot(), DummyWorkspace); if (normaliseLines) //VB doesn't do formatting nicely so limit it to default Roslyn handling { //injecting line-breaks to separate declarations { root = InjectLineBreaksVB(root); } //Removing multiple line breaks. //doesn't visit all "\r\n\r\n" cases. No time for this right now. //Using primitive RemoveDoubleLineBreaks instead but may need to be solved in the future //root = root.ReplaceNodes(root.DescendantNodes() // .Where(n => !n.IsKind(SyntaxKind.StringLiteralExpression)), // (_, node) => // { // var existingLTrivia = node.GetLeadingTrivia().ToFullString(); // if (existingLTrivia.Contains(Environment.NewLine + Environment.NewLine)) // return node.WithLeadingTrivia(SyntaxFactory.Whitespace(existingLTrivia.RemoveDoubleLineBreaks())); // else // return node; // }); result = root.ToFullString() .NormalizeLine(root, true); } else result = root.ToFullString(); return result; } static SyntaxNode InjectLineBreaksVB(SyntaxNode root) { return root.ReplaceNodes(root.DescendantNodes() .Where(n => n.IsVbMethodDeclaration() || n.IsVbClassDeclaration() || n.IsNewBlockStatement() || n.IsNewDeclarationBlock(true)), (_, node) => { var existingTrivia = node.GetLeadingTrivia().ToFullString(); if (existingTrivia.Contains(Environment.NewLine)) return node; else return node.WithLeadingTrivia((Environment.NewLine + existingTrivia).ToVbWhitespace()); }); } static SyntaxNode NodeAbove(this SyntaxNode node) { if (node.Parent != null) { SyntaxNode result = null; foreach (var item in node.Parent.ChildNodes()) if (item == node) return result; else result = item; } return null; } static public string RemoveDoubleLineBreaks(this string formattedCode) { Func<string, string> clear = text => text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); string current = formattedCode; string next; while (current != (next = clear(current))) current = next; return next; } static string NormalizeLine(this string formattedCode, SyntaxNode root, bool isVB) { var strings = root.DescendantNodes() .Where(n => n.IsKind(VB.SyntaxKind.StringLiteralExpression) || n.IsKind(SyntaxKind.StringLiteralExpression)) .Select(x => new { Start = x.FullSpan.Start, End = x.FullSpan.End }) .ToArray(); var sb = new StringBuilder(formattedCode); for (int pos = formattedCode.Length; pos > 0;) { pos = formattedCode.LastIndexOf("\r\n", pos); if (pos != -1) { if (strings.Any(x => x.Start <= pos && pos <= x.End)) continue; string prevLine = sb.GetPrevLineFrom(pos); string currLine = sb.GetLineFrom(pos); if (currLine.EndsWith("}") && prevLine == "") { //remove extra line before 'end-of-block' // var t = ""; // -> remove //} int lineStartPos = sb.GetLineOffset(pos); sb.Remove(lineStartPos, 2); pos = lineStartPos; } else if (prevLine.EndsWith("{") && currLine == "") { //remove extra line after 'start-of-block' //{ // -> remove // var t = ""; sb.Remove(pos, 2); } else { int doubleLineBreak = formattedCode.LastIndexOf("\r\n\r\n", pos); if (doubleLineBreak != -1 && (pos - doubleLineBreak) == 4) { //remove double line-break sb.Remove(pos, 2); } } } } var result = sb.ToString(); return result; } static int GetLineOffset(this StringBuilder sb, int pos) { int startPos = pos; bool atLineEnd = sb[pos] == '\r'; if (atLineEnd) startPos = pos - 1; for (int i = startPos; i >= 0; i--) if (sb[i] == '\r') return i; return 0; } static string GetLineFrom(this StringBuilder sb, int pos) { var chars = new List<char>(); bool atLineEnd = sb[pos] == '\r'; int startPos = pos; if (atLineEnd) startPos = pos - 1; for (int i = startPos; i >= 0; i--) { if (sb[i] == '\n') // || sb[i-1] == '\r') break; chars.Insert(0, sb[i]); } for (int i = startPos + 1; !atLineEnd && i < sb.Length; i++) { if (sb[i] == '\r') // || sb[i] == '\n') break; chars.Add(sb[i]); } return new string(chars.ToArray()).Trim(); } static string GetNextLineFrom(this StringBuilder sb, int pos) { var chars = new List<char>(); bool atLineEnd = sb[pos] == '\r'; int startPos = pos; if (atLineEnd) startPos = pos + 2; //advance forward for (int i = startPos; i < sb.Length; i++) { if (sb[i] == '\n') // || sb[i-1] == '\r') break; chars.Insert(0, sb[i]); } return new string(chars.ToArray()).Trim(); } static string GetPrevLineFrom(this StringBuilder sb, int pos) { var chars = new List<char>(); bool atLineEnd = sb[pos] == '\r'; int startPos = pos; if (atLineEnd) startPos--; for (int i = startPos; i >= 0; i--) { if (sb[i] == '\n') // || sb[i-1] == '\r') { startPos = i - 1; break; } } for (int i = startPos; i >= 0; i--) { if (sb[i] == '\n') // || sb[i-1] == '\r') break; chars.Insert(0, sb[i]); } for (int i = startPos + 1; !atLineEnd && i < sb.Length; i++) { if (sb[i] == '\r') // || sb[i] == '\n') break; chars.Add(sb[i]); } return new string(chars.ToArray()).Trim(); } public static bool DoesntStartsWithAny(this string text, params string[] patterns) { foreach (string item in patterns) if (text.StartsWith(item)) return false; return true; } public static bool IsNewBlockStatement(this SyntaxNode node, bool isVB = false) { var prevNode = node.NodeAbove(); if (isVB) return node.IsVbBlockStatement() && prevNode != null && prevNode.IsKind(VB.SyntaxKind.LocalDeclarationStatement); else return Formatter.IsBlockStatement(node) && prevNode != null && prevNode.IsKind(SyntaxKind.LocalDeclarationStatement); } public static bool IsNewDeclarationBlock(this SyntaxNode node, bool isVB = false) { var prevNode = node.NodeAbove(); if (isVB) return node.IsKind(VB.SyntaxKind.LocalDeclarationStatement) && prevNode != null && prevNode.IsKind(VB.SyntaxKind.LocalDeclarationStatement); else return node.IsKind(SyntaxKind.LocalDeclarationStatement) && prevNode != null && prevNode.IsKind(SyntaxKind.LocalDeclarationStatement); } private static bool IsBlockStatement(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.UsingStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.UnsafeStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.TryStatement: case SyntaxKind.Block: return true; default: return false; } } } static class VBSyntaxExtebnsions { // It's important to keep all VB related calls in separate methods. // It allows to avoid triggering Roslyn-VB assembly probing on Linux when parsing C# code public static bool IsVbMethodDeclaration(this SyntaxNode node) { return node.IsKind(VB.SyntaxKind.DeclareSubStatement /*MethodDeclaration*/); } public static bool IsVbClassDeclaration(this SyntaxNode node) { return node.IsKind(VB.SyntaxKind.EndClassStatement /*ClassDeclaration*/); } public static SyntaxTree ParseAsVb(this string text) { return VB.VisualBasicSyntaxTree.ParseText(text); } public static SyntaxTree ParseAsCs(this string text) { return CSharpSyntaxTree.ParseText(text); } public static SyntaxTrivia ToVbWhitespace(this string text) { return VB.SyntaxFactory.Whitespace(text); } public static bool IsVbBlockStatement(this SyntaxNode node) { switch (VB.VisualBasicExtensions.Kind(node)) { case VB.SyntaxKind.WhileStatement: case VB.SyntaxKind.DoUntilStatement: case VB.SyntaxKind.ForStatement: case VB.SyntaxKind.ForEachStatement: case VB.SyntaxKind.UsingStatement: case VB.SyntaxKind.SyncLockKeyword: case VB.SyntaxKind.IfStatement: case VB.SyntaxKind.TryStatement: return true; default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace System.ComponentModel { /// <devdoc> /// This type description provider provides type information through /// reflection. Unless someone has provided a custom type description /// provider for a type or instance, or unless an instance implements /// ICustomTypeDescriptor, any query for type information will go through /// this class. There should be a single instance of this class associated /// with "object", as it can provide all type information for any type. /// </devdoc> internal sealed class ReflectTypeDescriptionProvider { // This is where we store the various converters for the intrinsic types. // private static volatile Dictionary<object, object> s_intrinsicConverters; // For converters, etc that are bound to class attribute data, rather than a class // type, we have special key sentinel values that we put into the hash table. // private static object s_intrinsicNullableKey = new object(); private static object s_syncObject = new object(); /// <devdoc> /// Creates a new ReflectTypeDescriptionProvider. The type is the /// type we will obtain type information for. /// </devdoc> internal ReflectTypeDescriptionProvider() { } /// <devdoc> /// This is a table we create for intrinsic types. /// There should be entries here ONLY for intrinsic /// types, as all other types we should be able to /// add attributes directly as metadata. /// </devdoc> private static Dictionary<object, object> IntrinsicTypeConverters { get { // It is not worth taking a lock for this -- worst case of a collision // would build two tables, one that garbage collects very quickly. // if (ReflectTypeDescriptionProvider.s_intrinsicConverters == null) { Dictionary<object, object> temp = new Dictionary<object, object>(); // Add the intrinsics // temp[typeof(bool)] = typeof(BooleanConverter); temp[typeof(byte)] = typeof(ByteConverter); temp[typeof(SByte)] = typeof(SByteConverter); temp[typeof(char)] = typeof(CharConverter); temp[typeof(double)] = typeof(DoubleConverter); temp[typeof(string)] = typeof(StringConverter); temp[typeof(int)] = typeof(Int32Converter); temp[typeof(short)] = typeof(Int16Converter); temp[typeof(long)] = typeof(Int64Converter); temp[typeof(float)] = typeof(SingleConverter); temp[typeof(UInt16)] = typeof(UInt16Converter); temp[typeof(UInt32)] = typeof(UInt32Converter); temp[typeof(UInt64)] = typeof(UInt64Converter); temp[typeof(object)] = typeof(TypeConverter); temp[typeof(void)] = typeof(TypeConverter); temp[typeof(DateTime)] = typeof(DateTimeConverter); temp[typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter); temp[typeof(Decimal)] = typeof(DecimalConverter); temp[typeof(TimeSpan)] = typeof(TimeSpanConverter); temp[typeof(Guid)] = typeof(GuidConverter); temp[typeof(Array)] = typeof(ArrayConverter); temp[typeof(ICollection)] = typeof(CollectionConverter); temp[typeof(Enum)] = typeof(EnumConverter); // Special cases for things that are not bound to a specific type // temp[ReflectTypeDescriptionProvider.s_intrinsicNullableKey] = typeof(NullableConverter); ReflectTypeDescriptionProvider.s_intrinsicConverters = temp; } return ReflectTypeDescriptionProvider.s_intrinsicConverters; } } /// <devdoc> /// Helper method to create type converters. This checks to see if the /// type implements a Type constructor, and if it does it invokes that ctor. /// Otherwise, it just tries to create the type. /// </devdoc> private static object CreateInstance(Type objectType, Type parameterType, ref bool noTypeConstructor) { ConstructorInfo typeConstructor = null; noTypeConstructor = true; foreach (ConstructorInfo constructor in objectType.GetTypeInfo().DeclaredConstructors) { if (!constructor.IsPublic) { continue; } // This is the signature we look for when creating types that are generic, but // want to know what type they are dealing with. Enums are a good example of this; // there is one enum converter that can work with all enums, but it needs to know // the type of enum it is dealing with. // ParameterInfo[] parameters = constructor.GetParameters(); if (parameters.Length != 1 || !parameters[0].ParameterType.Equals(typeof(Type))) { continue; } typeConstructor = constructor; break; } if (typeConstructor != null) { noTypeConstructor = false; return typeConstructor.Invoke(new object[] { parameterType }); } return Activator.CreateInstance(objectType); } private static TypeConverterAttribute GetTypeConverterAttributeIfAny(Type type) { foreach (TypeConverterAttribute attribute in type.GetTypeInfo().GetCustomAttributes<TypeConverterAttribute>(false)) { return attribute; } return null; } /// <devdoc> /// Gets a type converter for the specified type. /// </devdoc> internal static TypeConverter GetConverter(Type type) { if (type == null) { throw new ArgumentNullException("type"); } // Check the cached TypeConverter dictionary for an exact match of the given type. object ans = SearchIntrinsicTable_ExactTypeMatch(type); if (ans != null) return (TypeConverter)ans; // Obtaining attributes follows a very critical order: we must take care that // we merge attributes the right way. Consider this: // // [A4] // interface IBase; // // [A3] // interface IDerived; // // [A2] // class Base : IBase; // // [A1] // class Derived : Base, IDerived // // We are retreving attributes in the following order: A1 - A4. // Interfaces always lose to types, and interfaces and types // must be looked up in the same order. TypeConverterAttribute converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(type); if (converterAttribute == null) { Type baseType = type.GetTypeInfo().BaseType; while (baseType != null && baseType != typeof(object)) { converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(baseType); if (converterAttribute != null) { break; } baseType = baseType.GetTypeInfo().BaseType; } } if (converterAttribute == null) { IEnumerable<Type> interfaces = type.GetTypeInfo().ImplementedInterfaces; foreach (Type iface in interfaces) { // only do this for public interfaces. // if ((iface.GetTypeInfo().Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0) { converterAttribute = GetTypeConverterAttributeIfAny(iface); if (converterAttribute != null) { break; } } } } if (converterAttribute != null) { Type converterType = ReflectTypeDescriptionProvider.GetTypeFromName(converterAttribute.ConverterTypeName, type); if (converterType != null && typeof(TypeConverter).GetTypeInfo().IsAssignableFrom(converterType.GetTypeInfo())) { bool noTypeConstructor = true; object instance = (TypeConverter)ReflectTypeDescriptionProvider.CreateInstance(converterType, type, ref noTypeConstructor); if (noTypeConstructor) ReflectTypeDescriptionProvider.IntrinsicTypeConverters[type] = instance; return (TypeConverter)instance; } } // We did not get a converter. Traverse up the base class chain until // we find one in the stock hashtable. // return (TypeConverter)ReflectTypeDescriptionProvider.SearchIntrinsicTable(type); } /// <devdoc> /// Retrieve a type from a name, if the name is not a fully qualified assembly name, then /// look for this type name in the same assembly as the "type" parameter is defined in. /// </devdoc> private static Type GetTypeFromName(string typeName, Type type) { if (string.IsNullOrEmpty(typeName)) { return null; } int commaIndex = typeName.IndexOf(','); Type t = null; if (commaIndex == -1) { t = type.GetTypeInfo().Assembly.GetType(typeName); } if (t == null) { t = Type.GetType(typeName); } return t; } /// <devdoc> /// Searches the provided intrinsic hashtable for a match with the object type. /// At the beginning, the hashtable contains types for the various converters. /// As this table is searched, the types for these objects /// are replaced with instances, so we only create as needed. This method /// does the search up the base class hierarchy and will create instances /// for types as needed. These instances are stored back into the table /// for the base type, and for the original component type, for fast access. /// </devdoc> private static object SearchIntrinsicTable(Type callingType) { object hashEntry = null; // We take a lock on this table. Nothing in this code calls out to // other methods that lock, so it should be fairly safe to grab this // lock. Also, this allows multiple intrinsic tables to be searched // at once. // lock (ReflectTypeDescriptionProvider.s_syncObject) { Type baseType = callingType; while (baseType != null && baseType != typeof(object)) { if (ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(baseType, out hashEntry) && hashEntry != null) { break; } baseType = baseType.GetTypeInfo().BaseType; } TypeInfo callingTypeInfo = callingType.GetTypeInfo(); // Now make a scan through each value in the table, looking for interfaces. // If we find one, see if the object implements the interface. // if (hashEntry == null) { foreach (object key in ReflectTypeDescriptionProvider.IntrinsicTypeConverters.Keys) { Type keyType = key as Type; if (keyType != null) { TypeInfo keyTypeInfo = keyType.GetTypeInfo(); if (keyTypeInfo.IsInterface && keyTypeInfo.IsAssignableFrom(callingTypeInfo)) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(key, out hashEntry); string converterTypeString = hashEntry as string; if (converterTypeString != null) { hashEntry = Type.GetType(converterTypeString); if (hashEntry != null) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry; } } if (hashEntry != null) { break; } } } } } // Special case converter // if (hashEntry == null) { if (callingTypeInfo.IsGenericType && callingTypeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)) { // Check if it is a nullable value ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(ReflectTypeDescriptionProvider.s_intrinsicNullableKey, out hashEntry); } } // Interfaces do not derive from object, so we // must handle the case of no hash entry here. // if (hashEntry == null) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(typeof(object), out hashEntry); } // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. // We can only do this if the object doesn't want a type // in its constructor. // Type type = hashEntry as Type; if (type != null) { bool noTypeConstructor = true; hashEntry = ReflectTypeDescriptionProvider.CreateInstance(type, callingType, ref noTypeConstructor); if (noTypeConstructor) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry; } } } return hashEntry; } private static object SearchIntrinsicTable_ExactTypeMatch(Type callingType) { object hashEntry = null; // We take a lock on this table. Nothing in this code calls out to // other methods that lock, so it should be fairly safe to grab this // lock. Also, this allows multiple intrinsic tables to be searched // at once. // lock (s_syncObject) { if (callingType != null && !IntrinsicTypeConverters.TryGetValue(callingType, out hashEntry)) return null; // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. // We can only do this if the object doesn't want a type // in its constructor. Type type = hashEntry as Type; if (type != null) { bool noTypeConstructor = true; hashEntry = CreateInstance(type, callingType, ref noTypeConstructor); if (noTypeConstructor) IntrinsicTypeConverters[callingType] = hashEntry; } } return hashEntry; } } }
// 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.Xml; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Xml.Serialization; using System.Collections; namespace System.Data.Common { internal sealed class SqlDecimalStorage : DataStorage { private SqlDecimal[] _values; public SqlDecimalStorage(DataColumn column) : base(column, typeof(SqlDecimal), SqlDecimal.Null, SqlDecimal.Null, StorageType.SqlDecimal) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: SqlDecimal sum = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += _values[record]; } hasData = true; } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: SqlDecimal meanSum = 0; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += _values[record]; } meanCount++; hasData = true; } if (hasData) { SqlDecimal mean = 0; checked { mean = (meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; SqlDouble var = 0; SqlDouble prec = 0; SqlDouble dsum = 0; SqlDouble sqrsum = 0; foreach (int record in records) { if (IsNull(record)) continue; dsum += _values[record].ToSqlDouble(); sqrsum += (_values[record]).ToSqlDouble() * (_values[record]).ToSqlDouble(); count++; } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var.Value); } return var; } return _nullValue; case AggregateType.Min: SqlDecimal min = SqlDecimal.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlDecimal.LessThan(_values[record], min)).IsTrue) min = _values[record]; hasData = true; } if (hasData) { return min; } return _nullValue; case AggregateType.Max: SqlDecimal max = SqlDecimal.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlDecimal.GreaterThan(_values[record], max)).IsTrue) max = _values[record]; hasData = true; } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (!IsNull(records[i])) count++; } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(SqlDecimal)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { return _values[recordNo1].CompareTo(_values[recordNo2]); } public override int CompareValueTo(int recordNo, object value) { return _values[recordNo].CompareTo((SqlDecimal)value); } public override object ConvertValue(object value) { if (null != value) { return SqlConvert.ConvertToSqlDecimal(value); } return _nullValue; } public override void Copy(int recordNo1, int recordNo2) { _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { return _values[record]; } public override bool IsNull(int record) { return (_values[record].IsNull); } public override void Set(int record, object value) { _values[record] = SqlConvert.ConvertToSqlDecimal(value); } public override void SetCapacity(int capacity) { SqlDecimal[] newValues = new SqlDecimal[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; } public override object ConvertXmlToObject(string s) { SqlDecimal newValue = new SqlDecimal(); string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader StringReader strReader = new StringReader(tempStr); IXmlSerializable tmp = newValue; using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { tmp.ReadXml(xmlTextReader); } return ((SqlDecimal)tmp); } public override string ConvertObjectToXml(object value) { Debug.Assert(!DataStorage.IsObjectNull(value), "we shouldn't have null here"); Debug.Assert((value.GetType() == typeof(SqlDecimal)), "wrong input type"); StringWriter strwriter = new StringWriter(FormatProvider); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter)) { ((IXmlSerializable)value).WriteXml(xmlTextWriter); } return (strwriter.ToString()); } protected override object GetEmptyStorage(int recordCount) { return new SqlDecimal[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { SqlDecimal[] typedStore = (SqlDecimal[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (SqlDecimal[])store; //SetNullStorage(nullbits); } } }
// 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.Linq; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests { public static partial class SignerInfoTests { [Fact] public static void SignerInfo_SignedAttributes_Cached_WhenEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo signer = cms.SignerInfos[0]; CryptographicAttributeObjectCollection attrs = signer.SignedAttributes; CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes; Assert.Same(attrs, attrs2); Assert.Empty(attrs); } [Fact] public static void SignerInfo_SignedAttributes_Cached_WhenNonEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPssDocument); SignerInfo signer = cms.SignerInfos[0]; CryptographicAttributeObjectCollection attrs = signer.SignedAttributes; CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes; Assert.Same(attrs, attrs2); Assert.Equal(4, attrs.Count); } [Fact] public static void SignerInfo_UnsignedAttributes_Cached_WhenEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo signer = cms.SignerInfos[0]; CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes; CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes; Assert.Same(attrs, attrs2); Assert.Empty(attrs); Assert.Empty(attrs2); } [Fact] public static void SignerInfo_UnsignedAttributes_Cached_WhenNonEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes; CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes; Assert.Same(attrs, attrs2); Assert.Single(attrs); } [Fact] public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo signer = cms.SignerInfos[0]; SignerInfoCollection counterSigners = signer.CounterSignerInfos; SignerInfoCollection counterSigners2 = signer.CounterSignerInfos; Assert.NotSame(counterSigners, counterSigners2); Assert.Empty(counterSigners); Assert.Empty(counterSigners2); } [Fact] public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenNonEmpty() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; SignerInfoCollection counterSigners = signer.CounterSignerInfos; SignerInfoCollection counterSigners2 = signer.CounterSignerInfos; Assert.NotSame(counterSigners, counterSigners2); Assert.Single(counterSigners); Assert.Single(counterSigners2); for (int i = 0; i < counterSigners.Count; i++) { SignerInfo counterSigner = counterSigners[i]; SignerInfo counterSigner2 = counterSigners2[i]; Assert.NotSame(counterSigner, counterSigner2); Assert.NotSame(counterSigner.Certificate, counterSigner2.Certificate); Assert.Equal(counterSigner.Certificate, counterSigner2.Certificate); #if netcoreapp byte[] signature = counterSigner.GetSignature(); byte[] signature2 = counterSigner2.GetSignature(); Assert.NotSame(signature, signature2); Assert.Equal(signature, signature2); #endif } } #if netcoreapp [Fact] public static void SignerInfo_GetSignature_UniquePerCall() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; byte[] signature = signer.GetSignature(); byte[] signature2 = signer.GetSignature(); Assert.NotSame(signature, signature2); Assert.Equal(signature, signature2); } #endif [Fact] public static void SignerInfo_DigestAlgorithm_NotSame() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; Oid oid = signer.DigestAlgorithm; Oid oid2 = signer.DigestAlgorithm; Assert.NotSame(oid, oid2); } #if netcoreapp [Fact] public static void SignerInfo_SignatureAlgorithm_NotSame() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; Oid oid = signer.SignatureAlgorithm; Oid oid2 = signer.SignatureAlgorithm; Assert.NotSame(oid, oid2); } #endif [Fact] public static void SignerInfo_Certificate_Same() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signer = cms.SignerInfos[0]; X509Certificate2 cert = signer.Certificate; X509Certificate2 cert2 = signer.Certificate; Assert.Same(cert, cert2); } [Fact] public static void CheckSignature_ThrowsOnNullStore() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPssDocument); SignerInfo signer = cms.SignerInfos[0]; AssertExtensions.Throws<ArgumentNullException>( "extraStore", () => signer.CheckSignature(null, true)); AssertExtensions.Throws<ArgumentNullException>( "extraStore", () => signer.CheckSignature(null, false)); } [Fact] public static void CheckSignature_ExtraStore_IsAdditional() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo signer = cms.SignerInfos[0]; Assert.NotNull(signer.Certificate); // Assert.NotThrows signer.CheckSignature(true); // Assert.NotThrows signer.CheckSignature(new X509Certificate2Collection(), true); } [Fact] public static void CheckSignature_MD5WithRSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.MD5WithRSADigestAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Md5, signer.DigestAlgorithm.Value); Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_SHA1WithRSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA1WithRSADigestAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha1, signer.DigestAlgorithm.Value); Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_SHA256WithRSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA256WithRSADigestAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value); Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_SHA384WithRSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA384WithRSADigestAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha384, signer.DigestAlgorithm.Value); Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_SHA512WithRSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA512WithRSADigestAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha512, signer.DigestAlgorithm.Value); Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_SHA256WithRSADigest_And_RSA256WithRSASignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA256withRSADigestAndSHA256WithRSASignatureAlgorithm); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value); Assert.Equal(Oids.RsaPkcs1Sha256, signer.SignatureAlgorithm.Value); //Assert.NotThrows signer.CheckSignature(true); } [Fact] public static void CheckSignature_ECDSA256SignedWithRSASha256HashIdentifier() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.SHA256ECDSAWithRsaSha256DigestIdentifier); SignerInfo signer = cms.SignerInfos[0]; Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value); Assert.Equal(Oids.EcdsaSha256, signer.SignatureAlgorithm.Value); // Assert.NotThrows signer.CheckSignature(true); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")] public static void RemoveCounterSignature_MatchesIssuerAndSerialNumber() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signerInfo = cms.SignerInfos[0]; SignerInfo counterSigner = signerInfo.CounterSignerInfos[1]; Assert.Equal( SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type); int countBefore = cms.Certificates.Count; Assert.NotEqual(signerInfo.Certificate, counterSigner.Certificate); signerInfo.RemoveCounterSignature(counterSigner); Assert.Single(cms.SignerInfos); // Removing a CounterSigner doesn't update the current object, it updates // the underlying SignedCms object, and a new signer has to be retrieved. Assert.Equal(2, signerInfo.CounterSignerInfos.Count); Assert.Single(cms.SignerInfos[0].CounterSignerInfos); Assert.Equal(countBefore, cms.Certificates.Count); // Assert.NotThrows cms.CheckSignature(true); cms.CheckHash(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")] public static void RemoveCounterSignature_MatchesSubjectKeyIdentifier() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signerInfo = cms.SignerInfos[0]; SignerInfo counterSigner = signerInfo.CounterSignerInfos[0]; Assert.Equal( SubjectIdentifierType.SubjectKeyIdentifier, counterSigner.SignerIdentifier.Type); int countBefore = cms.Certificates.Count; Assert.Equal(signerInfo.Certificate, counterSigner.Certificate); signerInfo.RemoveCounterSignature(counterSigner); Assert.Single(cms.SignerInfos); // Removing a CounterSigner doesn't update the current object, it updates // the underlying SignedCms object, and a new signer has to be retrieved. Assert.Equal(2, signerInfo.CounterSignerInfos.Count); Assert.Single(cms.SignerInfos[0].CounterSignerInfos); // This certificate is still in use, since we counter-signed ourself, // and the remaining countersigner is us. Assert.Equal(countBefore, cms.Certificates.Count); // Assert.NotThrows cms.CheckSignature(true); cms.CheckHash(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")] public static void RemoveCounterSignature_MatchesNoSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1CounterSignedWithNoSignature); SignerInfo signerInfo = cms.SignerInfos[0]; SignerInfo counterSigner = signerInfo.CounterSignerInfos[0]; Assert.Single(signerInfo.CounterSignerInfos); Assert.Equal(SubjectIdentifierType.NoSignature, counterSigner.SignerIdentifier.Type); int countBefore = cms.Certificates.Count; // cms.CheckSignature fails because there's a NoSignature countersigner: Assert.Throws<CryptographicException>(() => cms.CheckSignature(true)); signerInfo.RemoveCounterSignature(counterSigner); // Removing a CounterSigner doesn't update the current object, it updates // the underlying SignedCms object, and a new signer has to be retrieved. Assert.Single(signerInfo.CounterSignerInfos); Assert.Empty(cms.SignerInfos[0].CounterSignerInfos); // This certificate is still in use, since we counter-signed ourself, // and the remaining countersigner is us. Assert.Equal(countBefore, cms.Certificates.Count); // And we succeed now, because we got rid of the NoSignature signer. cms.CheckSignature(true); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")] public static void RemoveCounterSignature_UsesLiveState() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signerInfo = cms.SignerInfos[0]; SignerInfo counterSigner = signerInfo.CounterSignerInfos[0]; Assert.Equal( SubjectIdentifierType.SubjectKeyIdentifier, counterSigner.SignerIdentifier.Type); int countBefore = cms.Certificates.Count; Assert.Equal(signerInfo.Certificate, counterSigner.Certificate); signerInfo.RemoveCounterSignature(counterSigner); Assert.Single(cms.SignerInfos); // Removing a CounterSigner doesn't update the current object, it updates // the underlying SignedCms object, and a new signer has to be retrieved. Assert.Equal(2, signerInfo.CounterSignerInfos.Count); Assert.Single(cms.SignerInfos[0].CounterSignerInfos); Assert.Equal(countBefore, cms.Certificates.Count); // Even though the CounterSignerInfos collection still contains this, the live // document doesn't. Assert.Throws<CryptographicException>( () => signerInfo.RemoveCounterSignature(counterSigner)); // Assert.NotThrows cms.CheckSignature(true); cms.CheckHash(); } [Fact] public static void RemoveCounterSignature_WithNoMatch() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signerInfo = cms.SignerInfos[0]; // Even though we counter-signed ourself, the counter-signer version of us // is SubjectKeyIdentifier, and we're IssuerAndSerialNumber, so no match. Assert.Throws<CryptographicException>( () => signerInfo.RemoveCounterSignature(signerInfo)); } [Theory] [InlineData(0)] [InlineData(1)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug")] [ActiveIssue(31977, TargetFrameworkMonikers.Uap)] public static void RemoveCounterSignature_EncodedInSingleAttribute(int indexToRemove) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1TwoCounterSignaturesInSingleAttribute); SignerInfo signerInfo = cms.SignerInfos[0]; Assert.Equal(2, signerInfo.CounterSignerInfos.Count); signerInfo.RemoveCounterSignature(indexToRemove); Assert.Equal(1, signerInfo.CounterSignerInfos.Count); cms.CheckSignature(true); } [Fact] public static void RemoveCounterSignature_Null() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count); AssertExtensions.Throws<ArgumentNullException>( "counterSignerInfo", () => cms.SignerInfos[0].RemoveCounterSignature(null)); Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count); } [Fact] public static void RemoveCounterSignature_Negative() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; ArgumentOutOfRangeException ex = AssertExtensions.Throws<ArgumentOutOfRangeException>( "childIndex", () => signer.RemoveCounterSignature(-1)); Assert.Equal(null, ex.ActualValue); } [Fact] public static void RemoveCounterSignature_TooBigByValue() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(2)); signer.RemoveCounterSignature(1); Assert.Equal(2, signer.CounterSignerInfos.Count); Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(1)); } [Fact] public static void RemoveCounterSignature_TooBigByValue_Past0() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; signer.RemoveCounterSignature(0); signer.RemoveCounterSignature(0); Assert.Equal(2, signer.CounterSignerInfos.Count); Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(0)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")] public static void RemoveCounterSignature_TooBigByMatch() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; SignerInfo counterSigner = signer.CounterSignerInfos[1]; // This succeeeds, but reduces the real count to 1. signer.RemoveCounterSignature(counterSigner); Assert.Equal(2, signer.CounterSignerInfos.Count); Assert.Single(cms.SignerInfos[0].CounterSignerInfos); Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(counterSigner)); } [Fact] public static void RemoveCounterSignature_BySignerInfo_OnRemovedSigner() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; SignerInfo counterSigner = signer.CounterSignerInfos[0]; cms.RemoveSignature(signer); Assert.NotEmpty(signer.CounterSignerInfos); Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(counterSigner)); } [Fact] public static void RemoveCounterSignature_ByIndex_OnRemovedSigner() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); SignerInfo signer = cms.SignerInfos[0]; cms.RemoveSignature(signer); Assert.NotEmpty(signer.CounterSignerInfos); Assert.Throws<CryptographicException>( () => signer.RemoveCounterSignature(0)); } [Fact] public static void AddCounterSigner_DuplicateCert_RSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type); // On NetFx there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedAttrCount = 1; // One of them is a V3 signer. #if netfx expectedAttrCount = 2; #endif Assert.Equal(expectedAttrCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedAttrCount - 1].Oid.Value); Assert.Equal(firstSigner2.Certificate, counterSigner.Certificate); Assert.Single(cms.Certificates); counterSigner.CheckSignature(true); firstSigner2.CheckSignature(true); cms.CheckSignature(true); } [Theory] [InlineData(SubjectIdentifierType.IssuerAndSerialNumber)] [InlineData(SubjectIdentifierType.SubjectKeyIdentifier)] public static void AddCounterSigner_RSA(SubjectIdentifierType identifierType) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(identifierType, signerCert); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; Assert.Equal(identifierType, counterSigner.SignerIdentifier.Type); // On NetFx there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedCount = 1; #if netfx expectedCount = 2; #endif Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value); Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate); Assert.Equal(2, cms.Certificates.Count); counterSigner.CheckSignature(true); firstSigner2.CheckSignature(true); cms.CheckSignature(true); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Not supported by crypt32")] public static void AddCounterSignerToUnsortedAttributeSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.DigiCertTimeStampToken); // Assert.NoThrows cms.CheckSignature(true); SignerInfoCollection signers = cms.SignerInfos; Assert.Equal(1, signers.Count); SignerInfo signerInfo = signers[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { signerInfo.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.IssuerAndSerialNumber, cert)); signerInfo.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.SubjectKeyIdentifier, cert)); } // Assert.NoThrows cms.CheckSignature(true); byte[] exported = cms.Encode(); cms = new SignedCms(); cms.Decode(exported); // Assert.NoThrows cms.CheckSignature(true); } [Fact] [ActiveIssue(31977, TargetFrameworkMonikers.Uap)] public static void AddCounterSigner_DSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); signer.IncludeOption = X509IncludeOption.EndCertOnly; // Best compatibility for DSA is SHA-1 (FIPS 186-2) signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); Assert.Single(cms.SignerInfos); Assert.Equal(2, cms.Certificates.Count); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; Assert.Equal(1, counterSigner.Version); // On NetFx there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedCount = 1; #if netfx expectedCount = 2; #endif Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value); Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate); Assert.Equal(2, cms.Certificates.Count); #if netcoreapp byte[] signature = counterSigner.GetSignature(); Assert.NotEmpty(signature); // DSA PKIX signature format is a DER SEQUENCE. Assert.Equal(0x30, signature[0]); #endif cms.CheckSignature(true); byte[] encoded = cms.Encode(); cms.Decode(encoded); cms.CheckSignature(true); } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha1)] [InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha1)] [InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha256)] [InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha256)] [InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha384)] [InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha384)] [InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha512)] [InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha512)] public static void AddCounterSigner_ECDSA(SubjectIdentifierType identifierType, string digestOid) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(identifierType, signerCert); signer.IncludeOption = X509IncludeOption.EndCertOnly; signer.DigestAlgorithm = new Oid(digestOid, digestOid); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); Assert.Single(cms.SignerInfos); Assert.Equal(2, cms.Certificates.Count); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; int expectedVersion = identifierType == SubjectIdentifierType.IssuerAndSerialNumber ? 1 : 3; Assert.Equal(expectedVersion, counterSigner.Version); // On NetFx there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedCount = 1; #if netfx expectedCount = 2; #endif Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value); Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate); Assert.Equal(2, cms.Certificates.Count); #if netcoreapp byte[] signature = counterSigner.GetSignature(); Assert.NotEmpty(signature); // DSA PKIX signature format is a DER SEQUENCE. Assert.Equal(0x30, signature[0]); // ECDSA Oids are all under 1.2.840.10045.4. Assert.StartsWith("1.2.840.10045.4.", counterSigner.SignatureAlgorithm.Value); #endif cms.CheckSignature(true); byte[] encoded = cms.Encode(); cms.Decode(encoded); cms.CheckSignature(true); } [Fact] public static void AddFirstCounterSigner_NoSignature_NoPrivateKey() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo firstSigner = cms.SignerInfos[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { Action sign = () => firstSigner.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.NoSignature, cert) { IncludeOption = X509IncludeOption.None, }); if (PlatformDetection.IsFullFramework) { Assert.ThrowsAny<CryptographicException>(sign); } else { sign(); cms.CheckHash(); Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true)); firstSigner.CheckSignature(true); } } } [Fact] public static void AddFirstCounterSigner_NoSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo firstSigner = cms.SignerInfos[0]; // A certificate shouldn't really be required here, but on .NET Framework // it will prompt for the counter-signer's certificate if it's null, // even if the signature type is NoSignature. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { firstSigner.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.NoSignature, cert) { IncludeOption = X509IncludeOption.None, }); } Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); byte[] encoded = cms.Encode(); cms = new SignedCms(); cms.Decode(encoded); Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); firstSigner = cms.SignerInfos[0]; firstSigner.CheckSignature(verifySignatureOnly: true); Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash()); SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0]; Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true)); if (PlatformDetection.IsFullFramework) { // NetFX's CheckHash only looks at top-level SignerInfos to find the // crypt32 CMS signer ID, so it fails on any check from a countersigner. Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash()); } else { firstCounterSigner.CheckHash(); } } [Theory] [InlineData(false)] [InlineData(true)] public static void AddSecondCounterSignature_NoSignature_WithCert(bool addExtraCert) { AddSecondCounterSignature_NoSignature(withCertificate: true, addExtraCert); } [Theory] // On .NET Framework it will prompt for the counter-signer's certificate if it's null, // even if the signature type is NoSignature, so don't run the test there. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [InlineData(false)] [InlineData(true)] public static void AddSecondCounterSignature_NoSignature_WithoutCert(bool addExtraCert) { AddSecondCounterSignature_NoSignature(withCertificate: false, addExtraCert); } private static void AddSecondCounterSignature_NoSignature(bool withCertificate, bool addExtraCert) { X509Certificate2Collection certs; SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo firstSigner = cms.SignerInfos[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) using (X509Certificate2 cert2 = Certificates.DHKeyAgree1.GetCertificate()) { firstSigner.ComputeCounterSignature( new CmsSigner(cert) { IncludeOption = X509IncludeOption.None, }); CmsSigner counterSigner; if (withCertificate) { counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature, cert); } else { counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature); } if (addExtraCert) { counterSigner.Certificates.Add(cert2); } firstSigner.ComputeCounterSignature(counterSigner); certs = cms.Certificates; if (addExtraCert) { Assert.Equal(2, certs.Count); Assert.NotEqual(cert2.RawData, certs[0].RawData); Assert.Equal(cert2.RawData, certs[1].RawData); } else { Assert.Equal(1, certs.Count); Assert.NotEqual(cert2.RawData, certs[0].RawData); } } Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); byte[] encoded = cms.Encode(); cms = new SignedCms(); cms.Decode(encoded); Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); firstSigner = cms.SignerInfos[0]; firstSigner.CheckSignature(verifySignatureOnly: true); Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash()); // The NoSignature CounterSigner sorts first. SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0]; Assert.Equal(SubjectIdentifierType.NoSignature, firstCounterSigner.SignerIdentifier.Type); Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true)); if (PlatformDetection.IsFullFramework) { // NetFX's CheckHash only looks at top-level SignerInfos to find the // crypt32 CMS signer ID, so it fails on any check from a countersigner. Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash()); } else { firstCounterSigner.CheckHash(); } certs = cms.Certificates; if (addExtraCert) { Assert.Equal(2, certs.Count); Assert.Equal("CN=DfHelleKeyAgreement1", certs[1].SubjectName.Name); } else { Assert.Equal(1, certs.Count); } Assert.Equal("CN=RSAKeyTransferCapi1", certs[0].SubjectName.Name); } [Fact] [ActiveIssue(31977, TargetFrameworkMonikers.Uap)] public static void EnsureExtraCertsAdded() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneDsa1024); int preCount = cms.Certificates.Count; using (X509Certificate2 unrelated1 = Certificates.DHKeyAgree1.GetCertificate()) using (X509Certificate2 unrelated1Copy = Certificates.DHKeyAgree1.GetCertificate()) using (X509Certificate2 unrelated2 = Certificates.RSAKeyTransfer2.GetCertificate()) using (X509Certificate2 unrelated3 = Certificates.RSAKeyTransfer3.GetCertificate()) using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); signer.Certificates.Add(unrelated1); signer.Certificates.Add(unrelated2); signer.Certificates.Add(unrelated3); signer.Certificates.Add(unrelated1Copy); cms.SignerInfos[0].ComputeCounterSignature(signer); bool ExpectCopyRemoved = #if netfx false #else true #endif ; int expectedAddedCount = 4; if (!ExpectCopyRemoved) { expectedAddedCount++; } // Since adding a counter-signer DER-normalizes the document the certificates // get rewritten to be smallest cert first. X509Certificate2Collection certs = cms.Certificates; List<X509Certificate2> certList = new List<X509Certificate2>(certs.OfType<X509Certificate2>()); int lastSize = -1; for (int i = 0; i < certList.Count; i++) { byte[] rawData = certList[i].RawData; Assert.True( rawData.Length >= lastSize, $"Certificate {i} has an encoded size ({rawData.Length}) no smaller than its predecessor ({lastSize})"); } Assert.Contains(unrelated1, certList); Assert.Contains(unrelated2, certList); Assert.Contains(unrelated3, certList); Assert.Contains(signerCert, certList); Assert.Equal(ExpectCopyRemoved ? 1 : 2, certList.Count(c => c.Equals(unrelated1))); } cms.CheckSignature(true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Transactions; namespace System.Data.SqlClient { internal static class AsyncHelper { internal static Task CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) { if (task == null) { onSuccess(); return null; } else { TaskCompletionSource<object> completion = new TaskCompletionSource<object>(); ContinueTask(task, completion, () => { onSuccess(); completion.SetResult(null); }, connectionToDoom, onFailure); return completion.Task; } } internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) { return CreateContinuationTask(task, () => onSuccess(arg1, arg2), connectionToDoom, onFailure); } internal static void ContinueTask(Task task, TaskCompletionSource<object> completion, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null, Action onCancellation = null, Func<Exception, Exception> exceptionConverter = null, SqlConnection connectionToAbort = null ) { Debug.Assert((connectionToAbort == null) || (connectionToDoom == null), "Should not specify both connectionToDoom and connectionToAbort"); task.ContinueWith( tsk => { if (tsk.Exception != null) { Exception exc = tsk.Exception.InnerException; if (exceptionConverter != null) { exc = exceptionConverter(exc); } try { if (onFailure != null) { onFailure(exc); } } finally { completion.TrySetException(exc); } } else if (tsk.IsCanceled) { try { if (onCancellation != null) { onCancellation(); } } finally { completion.TrySetCanceled(); } } else { try { onSuccess(); } catch (Exception e) { completion.SetException(e); } } }, TaskScheduler.Default ); } internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions = true) { try { task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite); } catch (AggregateException ae) { if (rethrowExceptions) { Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException"); ExceptionDispatchInfo.Capture(ae.InnerException).Throw(); } } if (!task.IsCompleted) { if (onTimeout != null) { onTimeout(); } } } internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken) { if (timeout > 0) { Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) => { if (!tsk.IsCanceled && !completion.Task.IsCompleted) { completion.TrySetException(exc()); } }); } } } internal static class SQL { // The class SQL defines the exceptions that are specific to the SQL Adapter. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource Framework.txt. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error // messages. The resource Framework.txt will ensure proper string text based on the appropriate // locale. // // SQL specific exceptions // // // SQL.Connection // internal static Exception CannotGetDTCAddress() { return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotGetDTCAddress)); } internal static Exception InvalidInternalPacketSize(string str) { return ADP.ArgumentOutOfRange(str); } internal static Exception InvalidPacketSize() { return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_InvalidTDSPacketSize)); } internal static Exception InvalidPacketSizeValue() { return ADP.Argument(SR.GetString(SR.SQL_InvalidPacketSizeValue)); } internal static Exception InvalidSSPIPacketSize() { return ADP.Argument(SR.GetString(SR.SQL_InvalidSSPIPacketSize)); } internal static Exception NullEmptyTransactionName() { return ADP.Argument(SR.GetString(SR.SQL_NullEmptyTransactionName)); } internal static Exception UserInstanceFailoverNotCompatible() { return ADP.Argument(SR.GetString(SR.SQL_UserInstanceFailoverNotCompatible)); } internal static Exception InvalidSQLServerVersionUnknown() { return ADP.DataAdapter(SR.GetString(SR.SQL_InvalidSQLServerVersionUnknown)); } internal static Exception SynchronousCallMayNotPend() { return new Exception(SR.GetString(SR.Sql_InternalError)); } internal static Exception ConnectionLockedForBcpEvent() { return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionLockedForBcpEvent)); } internal static Exception InstanceFailure() { return ADP.InvalidOperation(SR.GetString(SR.SQL_InstanceFailure)); } // // Global Transactions. // internal static Exception GlobalTransactionsNotEnabled() { return ADP.InvalidOperation(SR.GetString(SR.GT_Disabled)); } internal static Exception UnknownSysTxIsolationLevel(Transactions.IsolationLevel isolationLevel) { return ADP.InvalidOperation(SR.GetString(SR.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString())); } internal static Exception InvalidPartnerConfiguration(string server, string database) { return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidPartnerConfiguration, server, database)); } internal static Exception MARSUnspportedOnConnection() { return ADP.InvalidOperation(SR.GetString(SR.SQL_MarsUnsupportedOnConnection)); } internal static Exception CannotModifyPropertyAsyncOperationInProgress([CallerMemberName] string property = "") { return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotModifyPropertyAsyncOperationInProgress, property)); } internal static Exception NonLocalSSEInstance() { return ADP.NotSupported(SR.GetString(SR.SQL_NonLocalSSEInstance)); } // // SQL.DataCommand // internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) { return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); } internal static ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) { #if DEBUG switch (value) { case CommandType.Text: case CommandType.StoredProcedure: Debug.Assert(false, "valid CommandType " + value.ToString()); break; case CommandType.TableDirect: break; default: Debug.Assert(false, "invalid CommandType " + value.ToString()); break; } #endif return NotSupportedEnumerationValue(typeof(CommandType), (int)value); } internal static ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value) { #if DEBUG switch (value) { case IsolationLevel.Unspecified: case IsolationLevel.ReadCommitted: case IsolationLevel.ReadUncommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: Debug.Assert(false, "valid IsolationLevel " + value.ToString()); break; case IsolationLevel.Chaos: break; default: Debug.Assert(false, "invalid IsolationLevel " + value.ToString()); break; } #endif return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value); } internal static Exception OperationCancelled() { Exception exception = ADP.InvalidOperation(SR.GetString(SR.SQL_OperationCancelled)); return exception; } internal static Exception PendingBeginXXXExists() { return ADP.InvalidOperation(SR.GetString(SR.SQL_PendingBeginXXXExists)); } internal static ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) { return ADP.ArgumentOutOfRange(SR.GetString(SR.SqlDependency_InvalidTimeout), param); } internal static Exception NonXmlResult() { return ADP.InvalidOperation(SR.GetString(SR.SQL_NonXmlResult)); } // // SQL.DataParameter // internal static Exception InvalidParameterTypeNameFormat() { return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterTypeNameFormat)); } internal static Exception InvalidParameterNameLength(string value) { return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterNameLength, value)); } internal static Exception PrecisionValueOutOfRange(byte precision) { return ADP.Argument(SR.GetString(SR.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture))); } internal static Exception ScaleValueOutOfRange(byte scale) { return ADP.Argument(SR.GetString(SR.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } internal static Exception TimeScaleValueOutOfRange(byte scale) { return ADP.Argument(SR.GetString(SR.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidSqlDbType(SqlDbType value) { return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int)value); } internal static Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) { return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnsupportedTVPOutputParameter, direction.ToString(), paramName)); } internal static Exception DBNullNotSupportedForTVPValues(string paramName) { return ADP.NotSupported(SR.GetString(SR.SqlParameter_DBNullNotSupportedForTVP, paramName)); } internal static Exception UnexpectedTypeNameForNonStructParams(string paramName) { return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnexpectedTypeNameForNonStruct, paramName)); } internal static Exception ParameterInvalidVariant(string paramName) { return ADP.InvalidOperation(SR.GetString(SR.SQL_ParameterInvalidVariant, paramName)); } internal static Exception MustSetTypeNameForParam(string paramType, string paramName) { return ADP.Argument(SR.GetString(SR.SQL_ParameterTypeNameRequired, paramType, paramName)); } internal static Exception NullSchemaTableDataTypeNotSupported(string columnName) { return ADP.Argument(SR.GetString(SR.NullSchemaTableDataTypeNotSupported, columnName)); } internal static Exception InvalidSchemaTableOrdinals() { return ADP.Argument(SR.GetString(SR.InvalidSchemaTableOrdinals)); } internal static Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) { return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber)); } internal static Exception EnumeratedRecordFieldCountChanged(int recordNumber) { return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordFieldCountChanged, recordNumber)); } // // SQL.SqlDataAdapter // // // SQL.TDSParser // internal static Exception InvalidTDSVersion() { return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidTDSVersion)); } internal static Exception ParsingError() { return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingError)); } internal static Exception MoneyOverflow(string moneyValue) { return ADP.Overflow(SR.GetString(SR.SQL_MoneyOverflow, moneyValue)); } internal static Exception SmallDateTimeOverflow(string datetime) { return ADP.Overflow(SR.GetString(SR.SQL_SmallDateTimeOverflow, datetime)); } internal static Exception SNIPacketAllocationFailure() { return ADP.InvalidOperation(SR.GetString(SR.SQL_SNIPacketAllocationFailure)); } internal static Exception TimeOverflow(string time) { return ADP.Overflow(SR.GetString(SR.SQL_TimeOverflow, time)); } // // SQL.SqlDataReader // internal static Exception InvalidRead() { return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidRead)); } internal static Exception NonBlobColumn(string columnName) { return ADP.InvalidCast(SR.GetString(SR.SQL_NonBlobColumn, columnName)); } internal static Exception NonCharColumn(string columnName) { return ADP.InvalidCast(SR.GetString(SR.SQL_NonCharColumn, columnName)); } internal static Exception StreamNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(SR.GetString(SR.SQL_StreamNotSupportOnColumnType, columnName)); } internal static Exception TextReaderNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(SR.GetString(SR.SQL_TextReaderNotSupportOnColumnType, columnName)); } internal static Exception XmlReaderNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(SR.GetString(SR.SQL_XmlReaderNotSupportOnColumnType, columnName)); } // // SQL.SqlDependency // internal static Exception SqlCommandHasExistingSqlNotificationRequest() { return ADP.InvalidOperation(SR.GetString(SR.SQLNotify_AlreadyHasCommand)); } internal static Exception SqlDepDefaultOptionsButNoStart() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DefaultOptionsButNoStart)); } internal static Exception SqlDependencyDatabaseBrokerDisabled() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DatabaseBrokerDisabled)); } internal static Exception SqlDependencyEventNoDuplicate() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_EventNoDuplicate)); } internal static Exception SqlDependencyDuplicateStart() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DuplicateStart)); } internal static Exception SqlDependencyIdMismatch() { // do not include the id because it may require SecurityPermission(Infrastructure) permission return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_IdMismatch)); } internal static Exception SqlDependencyNoMatchingServerStart() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerStart)); } internal static Exception SqlDependencyNoMatchingServerDatabaseStart() { return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerDatabaseStart)); } // // SQL.SqlDelegatedTransaction // internal static TransactionPromotionException PromotionFailed(Exception inner) { TransactionPromotionException e = new TransactionPromotionException(SR.GetString(SR.SqlDelegatedTransaction_PromotionFailed), inner); ADP.TraceExceptionAsReturnValue(e); return e; } //Failure while attempting to promote transaction. // // SQL.SqlMetaData // internal static Exception InvalidSqlDbTypeForConstructor(SqlDbType type) { return ADP.Argument(SR.GetString(SR.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString())); } internal static Exception NameTooLong(string parameterName) { return ADP.Argument(SR.GetString(SR.SqlMetaData_NameTooLong), parameterName); } internal static Exception InvalidSortOrder(SortOrder order) { return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order); } internal static Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) { return ADP.InvalidOperation(SR.GetString(SR.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal)); } internal static Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) { return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnType, columnName, typeName)); } internal static Exception InvalidColumnMaxLength(string columnName, long maxLength) { return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength)); } internal static Exception InvalidColumnPrecScale() { return ADP.Argument(SR.GetString(SR.SqlMisc_InvalidPrecScaleMessage)); } internal static Exception NotEnoughColumnsInStructuredType() { return ADP.Argument(SR.GetString(SR.SqlProvider_NotEnoughColumnsInStructuredType)); } internal static Exception DuplicateSortOrdinal(int sortOrdinal) { return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_DuplicateSortOrdinal, sortOrdinal)); } internal static Exception MissingSortOrdinal(int sortOrdinal) { return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_MissingSortOrdinal, sortOrdinal)); } internal static Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) { return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal)); } internal static Exception IEnumerableOfSqlDataRecordHasNoRows() { return ADP.Argument(SR.GetString(SR.IEnumerableOfSqlDataRecordHasNoRows)); } // // SQL.BulkLoad // internal static Exception BulkLoadMappingInaccessible() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingInaccessible)); } internal static Exception BulkLoadMappingsNamesOrOrdinalsOnly() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingsNamesOrOrdinalsOnly)); } internal static Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e) { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e); } internal static Exception BulkLoadNonMatchingColumnMapping() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnMapping)); } internal static Exception BulkLoadNonMatchingColumnName(string columnName) { return BulkLoadNonMatchingColumnName(columnName, null); } internal static Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnName, columnName), e); } internal static Exception BulkLoadStringTooLong() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadStringTooLong)); } internal static Exception BulkLoadInvalidVariantValue() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidVariantValue)); } internal static Exception BulkLoadInvalidTimeout(int timeout) { return ADP.Argument(SR.GetString(SR.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture))); } internal static Exception BulkLoadExistingTransaction() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadExistingTransaction)); } internal static Exception BulkLoadNoCollation() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNoCollation)); } internal static Exception BulkLoadConflictingTransactionOption() { return ADP.Argument(SR.GetString(SR.SQL_BulkLoadConflictingTransactionOption)); } internal static Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName) { return ADP.InvalidOperation(SR.GetString(SR.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName)); } internal static Exception InvalidOperationInsideEvent() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidOperationInsideEvent)); } internal static Exception BulkLoadMissingDestinationTable() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMissingDestinationTable)); } internal static Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidDestinationTable, tableName), inner); } internal static Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNotAllowDBNull, columnName)); } internal static Exception BulkLoadPendingOperation() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadPendingOperation)); } internal static Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision) { return ADP.InvalidOperation(SR.GetString(SR.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision)); } // // transactions. // internal static Exception ConnectionDoomed() { return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionDoomed)); } internal static Exception OpenResultCountExceeded() { return ADP.InvalidOperation(SR.GetString(SR.SQL_OpenResultCountExceeded)); } internal static Exception UnsupportedSysTxForGlobalTransactions() { return ADP.InvalidOperation(SR.GetString(SR.SQL_UnsupportedSysTxVersion)); } internal static readonly byte[] AttentionHeader = new byte[] { TdsEnums.MT_ATTN, // Message Type TdsEnums.ST_EOM, // Status TdsEnums.HEADER_LEN >> 8, // length - upper byte TdsEnums.HEADER_LEN & 0xff, // length - lower byte 0, // spid 0, // spid 0, // packet (out of band) 0 // window }; // // MultiSubnetFailover // /// <summary> /// used to block two scenarios if MultiSubnetFailover is true: /// * server-provided failover partner - raising SqlException in this case /// * connection string with failover partner and MultiSubnetFailover=true - raising argument one in this case with the same message /// </summary> internal static Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection) { string msg = SR.GetString(SR.SQLMSF_FailoverPartnerNotSupported); if (serverProvidedFailoverPartner) { // Replacing InvalidOperation with SQL exception SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; // disable open retry logic on this error return exc; } else { return ADP.Argument(msg); } } internal static Exception MultiSubnetFailoverWithMoreThan64IPs() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs); return ADP.InvalidOperation(msg); } internal static Exception MultiSubnetFailoverWithInstanceSpecified() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified); return ADP.Argument(msg); } internal static Exception MultiSubnetFailoverWithNonTcpProtocol() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol); return ADP.Argument(msg); } // // Read-only routing // internal static Exception ROR_FailoverNotSupportedConnString() { return ADP.Argument(SR.GetString(SR.SQLROR_FailoverNotSupported)); } internal static Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_FailoverNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } internal static Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_RecursiveRoutingNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } internal static Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_UnexpectedRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } internal static Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_InvalidRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } internal static Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_TimeoutAfterRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } // // Connection resiliency // internal static SqlException CR_ReconnectTimeout() { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT)); SqlException exc = SqlException.CreateException(errors, ""); return exc; } internal static SqlException CR_ReconnectionCancelled() { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0)); SqlException exc = SqlException.CreateException(errors, ""); return exc; } internal static Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } internal static Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_EncryptionChanged), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } internal static SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_AllAttemptsFailed), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } internal static SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NoCRAckAtReconnection), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } internal static SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_TDSVestionNotPreserved), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } internal static SqlException CR_UnrecoverableServer(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableServer), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } internal static SqlException CR_UnrecoverableClient(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableClient), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } internal static Exception StreamWriteNotSupported() { return ADP.NotSupported(SR.GetString(SR.SQL_StreamWriteNotSupported)); } internal static Exception StreamReadNotSupported() { return ADP.NotSupported(SR.GetString(SR.SQL_StreamReadNotSupported)); } internal static Exception StreamSeekNotSupported() { return ADP.NotSupported(SR.GetString(SR.SQL_StreamSeekNotSupported)); } internal static System.Data.SqlTypes.SqlNullValueException SqlNullValue() { System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException(); return e; } internal static Exception SubclassMustOverride() { return ADP.InvalidOperation(SR.GetString(SR.SqlMisc_SubclassMustOverride)); } // ProjectK\CoreCLR specific errors internal static Exception UnsupportedKeyword(string keyword) { return ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedKeyword, keyword)); } internal static Exception NetworkLibraryKeywordNotSupported() { return ADP.NotSupported(SR.GetString(SR.SQL_NetworkLibraryNotSupported)); } internal static Exception UnsupportedFeatureAndToken(SqlInternalConnectionTds internalConnection, string token) { var innerException = ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedToken, token)); SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQL_UnsupportedFeature), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection, innerException); return exc; } internal static Exception BatchedUpdatesNotAvailableOnContextConnection() { return ADP.InvalidOperation(SR.GetString(SR.SQL_BatchedUpdatesNotAvailableOnContextConnection)); } /// <summary> /// gets a message for SNI error (sniError must be valid, non-zero error code) /// </summary> internal static string GetSNIErrorMessage(int sniError) { Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range"); string errorMessageId = String.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError); return SR.GetResourceString(errorMessageId, errorMessageId); } // Default values for SqlDependency and SqlNotificationRequest internal const int SqlDependencyTimeoutDefault = 0; internal const int SqlDependencyServerTimeout = 5 * 24 * 3600; // 5 days - used to compute default TTL of the dependency internal const string SqlNotificationServiceDefault = "SqlQueryNotificationService"; internal const string SqlNotificationStoredProcedureDefault = "SqlQueryNotificationStoredProcedure"; } sealed internal class SQLMessage { private SQLMessage() { /* prevent utility class from being instantiated*/ } // The class SQLMessage defines the error messages that are specific to the SqlDataAdapter // that are caused by a netlib error. The functions will be called and then return the // appropriate error message from the resource Framework.txt. The SqlDataAdapter will then // take the error message and then create a SqlError for the message and then place // that into a SqlException that is either thrown to the user or cached for throwing at // a later time. This class is used so that there will be compile time checking of error // messages. The resource Framework.txt will ensure proper string text based on the appropriate // locale. internal static string CultureIdError() { return SR.GetString(SR.SQL_CultureIdError); } internal static string EncryptionNotSupportedByClient() { return SR.GetString(SR.SQL_EncryptionNotSupportedByClient); } internal static string EncryptionNotSupportedByServer() { return SR.GetString(SR.SQL_EncryptionNotSupportedByServer); } internal static string OperationCancelled() { return SR.GetString(SR.SQL_OperationCancelled); } internal static string SevereError() { return SR.GetString(SR.SQL_SevereError); } internal static string SSPIInitializeError() { return SR.GetString(SR.SQL_SSPIInitializeError); } internal static string SSPIGenerateError() { return SR.GetString(SR.SQL_SSPIGenerateError); } internal static string SqlServerBrowserNotAccessible() { return SR.GetString(SR.SQL_SqlServerBrowserNotAccessible); } internal static string KerberosTicketMissingError() { return SR.GetString(SR.SQL_KerberosTicketMissingError); } internal static string Timeout() { return SR.GetString(SR.SQL_Timeout); } internal static string Timeout_PreLogin_Begin() { return SR.GetString(SR.SQL_Timeout_PreLogin_Begin); } internal static string Timeout_PreLogin_InitializeConnection() { return SR.GetString(SR.SQL_Timeout_PreLogin_InitializeConnection); } internal static string Timeout_PreLogin_SendHandshake() { return SR.GetString(SR.SQL_Timeout_PreLogin_SendHandshake); } internal static string Timeout_PreLogin_ConsumeHandshake() { return SR.GetString(SR.SQL_Timeout_PreLogin_ConsumeHandshake); } internal static string Timeout_Login_Begin() { return SR.GetString(SR.SQL_Timeout_Login_Begin); } internal static string Timeout_Login_ProcessConnectionAuth() { return SR.GetString(SR.SQL_Timeout_Login_ProcessConnectionAuth); } internal static string Timeout_PostLogin() { return SR.GetString(SR.SQL_Timeout_PostLogin); } internal static string Timeout_FailoverInfo() { return SR.GetString(SR.SQL_Timeout_FailoverInfo); } internal static string Timeout_RoutingDestination() { return SR.GetString(SR.SQL_Timeout_RoutingDestinationInfo); } internal static string Duration_PreLogin_Begin(long PreLoginBeginDuration) { return SR.GetString(SR.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration); } internal static string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) { return SR.GetString(SR.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration); } internal static string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration) { return SR.GetString(SR.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration); } internal static string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration) { return SR.GetString(SR.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration); } internal static string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration) { return SR.GetString(SR.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration); } internal static string UserInstanceFailure() { return SR.GetString(SR.SQL_UserInstanceFailure); } internal static string PreloginError() { return SR.GetString(SR.Snix_PreLogin); } internal static string ExClientConnectionId() { return SR.GetString(SR.SQL_ExClientConnectionId); } internal static string ExErrorNumberStateClass() { return SR.GetString(SR.SQL_ExErrorNumberStateClass); } internal static string ExOriginalClientConnectionId() { return SR.GetString(SR.SQL_ExOriginalClientConnectionId); } internal static string ExRoutingDestination() { return SR.GetString(SR.SQL_ExRoutingDestination); } } /// <summary> /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names /// </summary> internal static class SqlServerEscapeHelper { /// <summary> /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier. /// </summary> /// <param name="name">name of the identifier, in unescaped form</param> /// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns> internal static string EscapeIdentifier(string name) { Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed"); return "[" + name.Replace("]", "]]") + "]"; } /// <summary> /// Same as above EscapeIdentifier, except that output is written into StringBuilder /// </summary> internal static void EscapeIdentifier(StringBuilder builder, string name) { Debug.Assert(builder != null, "builder cannot be null"); Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed"); builder.Append("["); builder.Append(name.Replace("]", "]]")); builder.Append("]"); } /// <summary> /// Escape a string to be used inside TSQL literal, such as N'somename' or 'somename' /// </summary> internal static string EscapeStringAsLiteral(string input) { Debug.Assert(input != null, "input string cannot be null"); return input.Replace("'", "''"); } /// <summary> /// Escape a string as a TSQL literal, wrapping it around with single quotes. /// Use this method to escape input strings to prevent SQL injection /// and to get correct behavior for embedded quotes. /// </summary> /// <param name="input">unescaped string</param> /// <returns>escaped and quoted literal string</returns> internal static string MakeStringLiteral(string input) { if (string.IsNullOrEmpty(input)) { return "''"; } else { return "'" + EscapeStringAsLiteral(input) + "'"; } } } /// <summary> /// This class holds methods invoked on System.Transactions through reflection for Global Transactions /// </summary> static internal class SysTxForGlobalTransactions { private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() => typeof(Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) })); private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() => typeof(Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) })); private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() => typeof(Transaction).GetMethod("GetPromotedToken")); /// <summary> /// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction /// </summary> /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns> public static MethodInfo EnlistPromotableSinglePhase { get { return _enlistPromotableSinglePhase.Value; } } /// <summary> /// Sets the given DistributedTransactionIdentifier for a Transaction instance. /// Needs to be invoked when using a Non-MSDTC Promoter type /// </summary> /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns> public static MethodInfo SetDistributedTransactionIdentifier { get { return _setDistributedTransactionIdentifier.Value; } } /// <summary> /// Gets the Promoted Token for a Transaction /// </summary> /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns> public static MethodInfo GetPromotedToken { get { return _getPromotedToken.Value; } } } }//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; using System.Runtime.InteropServices; internal partial class Interop { internal partial class NtDll { // https://msdn.microsoft.com/en-us/library/bb432380.aspx // https://msdn.microsoft.com/en-us/library/windows/hardware/ff566424.aspx [DllImport(Libraries.NtDll, CharSet = CharSet.Unicode, ExactSpelling = true)] private unsafe static extern int NtCreateFile( out IntPtr FileHandle, DesiredAccess DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, out IO_STATUS_BLOCK IoStatusBlock, long* AllocationSize, System.IO.FileAttributes FileAttributes, System.IO.FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength); internal unsafe static (int status, IntPtr handle) CreateFile( ReadOnlySpan<char> path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.FILE_GENERIC_READ | DesiredAccess.SYNCHRONIZE, System.IO.FileShare shareAccess = System.IO.FileShare.ReadWrite | System.IO.FileShare.Delete, System.IO.FileAttributes fileAttributes = 0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = ObjectAttributes.OBJ_CASE_INSENSITIVE, void* eaBuffer = null, uint eaLength = 0) { fixed (char* c = &MemoryMarshal.GetReference(path)) { UNICODE_STRING name = new UNICODE_STRING { Length = checked((ushort)(path.Length * sizeof(char))), MaximumLength = checked((ushort)(path.Length * sizeof(char))), Buffer = (IntPtr)c }; OBJECT_ATTRIBUTES attributes = new OBJECT_ATTRIBUTES( &name, objectAttributes, rootDirectory); int status = NtCreateFile( out IntPtr handle, desiredAccess, ref attributes, out IO_STATUS_BLOCK statusBlock, AllocationSize: null, fileAttributes, shareAccess, createDisposition, createOptions, eaBuffer, eaLength); return (status, handle); } } /// <summary> /// File creation disposition when calling directly to NT APIs. /// </summary> public enum CreateDisposition : uint { /// <summary> /// Default. Replace or create. Deletes existing file instead of overwriting. /// </summary> /// <remarks> /// As this potentially deletes it requires that DesiredAccess must include Delete. /// This has no equivalent in CreateFile. /// </remarks> FILE_SUPERSEDE = 0, /// <summary> /// Open if exists or fail if doesn't exist. Equivalent to OPEN_EXISTING or /// <see cref="System.IO.FileMode.Open"/>. /// </summary> /// <remarks> /// TruncateExisting also uses Open and then manually truncates the file /// by calling NtSetInformationFile with FileAllocationInformation and an /// allocation size of 0. /// </remarks> FILE_OPEN = 1, /// <summary> /// Create if doesn't exist or fail if does exist. Equivalent to CREATE_NEW /// or <see cref="System.IO.FileMode.CreateNew"/>. /// </summary> FILE_CREATE = 2, /// <summary> /// Open if exists or create if doesn't exist. Equivalent to OPEN_ALWAYS or /// <see cref="System.IO.FileMode.OpenOrCreate"/>. /// </summary> FILE_OPEN_IF = 3, /// <summary> /// Open and overwrite if exists or fail if doesn't exist. Equivalent to /// TRUNCATE_EXISTING or <see cref="System.IO.FileMode.Truncate"/>. /// </summary> FILE_OVERWRITE = 4, /// <summary> /// Open and overwrite if exists or create if doesn't exist. Equivalent to /// CREATE_ALWAYS or <see cref="System.IO.FileMode.Create"/>. /// </summary> FILE_OVERWRITE_IF = 5 } /// <summary> /// Options for creating/opening files with NtCreateFile. /// </summary> public enum CreateOptions : uint { /// <summary> /// File being created or opened must be a directory file. Disposition must be FILE_CREATE, FILE_OPEN, /// or FILE_OPEN_IF. /// </summary> /// <remarks> /// Can only be used with FILE_SYNCHRONOUS_IO_ALERT/NONALERT, FILE_WRITE_THROUGH, FILE_OPEN_FOR_BACKUP_INTENT, /// and FILE_OPEN_BY_FILE_ID flags. /// </remarks> FILE_DIRECTORY_FILE = 0x00000001, /// <summary> /// Applications that write data to the file must actually transfer the data into /// the file before any requested write operation is considered complete. This flag /// is set automatically if FILE_NO_INTERMEDIATE_BUFFERING is set. /// </summary> FILE_WRITE_THROUGH = 0x00000002, /// <summary> /// All accesses to the file are sequential. /// </summary> FILE_SEQUENTIAL_ONLY = 0x00000004, /// <summary> /// File cannot be cached in driver buffers. Cannot use with AppendData desired access. /// </summary> FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008, /// <summary> /// All operations are performed synchronously. Any wait on behalf of the caller is /// subject to premature termination from alerts. /// </summary> /// <remarks> /// Cannot be used with FILE_SYNCHRONOUS_IO_NONALERT. /// Synchronous DesiredAccess flag is required. I/O system will maintain file position context. /// </remarks> FILE_SYNCHRONOUS_IO_ALERT = 0x00000010, /// <summary> /// All operations are performed synchronously. Waits in the system to synchronize I/O queuing /// and completion are not subject to alerts. /// </summary> /// <remarks> /// Cannot be used with FILE_SYNCHRONOUS_IO_ALERT. /// Synchronous DesiredAccess flag is required. I/O system will maintain file position context. /// </remarks> FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020, /// <summary> /// File being created or opened must not be a directory file. Can be a data file, device, /// or volume. /// </summary> FILE_NON_DIRECTORY_FILE = 0x00000040, /// <summary> /// Create a tree connection for this file in order to open it over the network. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_CREATE_TREE_CONNECTION = 0x00000080, /// <summary> /// Complete the operation immediately with a success code of STATUS_OPLOCK_BREAK_IN_PROGRESS if /// the target file is oplocked. /// </summary> /// <remarks> /// Not compatible with ReserveOpfilter or OpenRequiringOplock. /// Not used by device and intermediate drivers. /// </remarks> FILE_COMPLETE_IF_OPLOCKED = 0x00000100, /// <summary> /// If the extended attributes on an existing file being opened indicate that the caller must /// understand extended attributes to properly interpret the file, fail the request. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_NO_EA_KNOWLEDGE = 0x00000200, // Behavior undocumented, defined in headers // FILE_OPEN_REMOTE_INSTANCE = 0x00000400, /// <summary> /// Accesses to the file can be random, so no sequential read-ahead operations should be performed /// on the file by FSDs or the system. /// </summary> FILE_RANDOM_ACCESS = 0x00000800, /// <summary> /// Delete the file when the last handle to it is passed to NtClose. Requires Delete flag in /// DesiredAccess parameter. /// </summary> FILE_DELETE_ON_CLOSE = 0x00001000, /// <summary> /// Open the file by reference number or object ID. The file name that is specified by the ObjectAttributes /// name parameter includes the 8 or 16 byte file reference number or ID for the file in the ObjectAttributes /// name field. The device name can optionally be prefixed. /// </summary> /// <remarks> /// NTFS supports both reference numbers and object IDs. 16 byte reference numbers are 8 byte numbers padded /// with zeros. ReFS only supports reference numbers (not object IDs). 8 byte and 16 byte reference numbers /// are not related. Note that as the UNICODE_STRING will contain raw byte data, it may not be a "valid" string. /// Not used by device and intermediate drivers. /// </remarks> /// <example> /// \??\C:\{8 bytes of binary FileID} /// \device\HardDiskVolume1\{16 bytes of binary ObjectID} /// {8 bytes of binary FileID} /// </example> FILE_OPEN_BY_FILE_ID = 0x00002000, /// <summary> /// The file is being opened for backup intent. Therefore, the system should check for certain access rights /// and grant the caller the appropriate access to the file before checking the DesiredAccess parameter /// against the file's security descriptor. /// </summary> /// <remarks> /// Not used by device and intermediate drivers. /// </remarks> FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000, /// <summary> /// When creating a file, specifies that it should not inherit the compression bit from the parent directory. /// </summary> FILE_NO_COMPRESSION = 0x00008000, /// <summary> /// The file is being opened and an opportunistic lock (oplock) on the file is being requested as a single atomic /// operation. /// </summary> /// <remarks> /// The file system checks for oplocks before it performs the create operation and will fail the create with a /// return code of STATUS_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock. /// Not compatible with CompleteIfOplocked or ReserveOpFilter. Windows 7 and up. /// </remarks> FILE_OPEN_REQUIRING_OPLOCK = 0x00010000, /// <summary> /// CreateFile2 uses this flag to prevent opening a file that you don't have access to without specifying /// FILE_SHARE_READ. (Preventing users that can only read a file from denying access to other readers.) /// </summary> /// <remarks> /// Windows 7 and up. /// </remarks> FILE_DISALLOW_EXCLUSIVE = 0x00020000, /// <summary> /// The client opening the file or device is session aware and per session access is validated if necessary. /// </summary> /// <remarks> /// Windows 8 and up. /// </remarks> FILE_SESSION_AWARE = 0x00040000, /// <summary> /// This flag allows an application to request a filter opportunistic lock (oplock) to prevent other applications /// from getting share violations. /// </summary> /// <remarks> /// Not compatible with CompleteIfOplocked or OpenRequiringOplock. /// If there are already open handles, the create request will fail with STATUS_OPLOCK_NOT_GRANTED. /// </remarks> FILE_RESERVE_OPFILTER = 0x00100000, /// <summary> /// Open a file with a reparse point attribute, bypassing the normal reparse point processing. /// </summary> FILE_OPEN_REPARSE_POINT = 0x00200000, /// <summary> /// Causes files that are marked with the Offline attribute not to be recalled from remote storage. /// </summary> /// <remarks> /// More details can be found in Remote Storage documentation (see Basic Concepts). /// https://technet.microsoft.com/en-us/library/cc938459.aspx /// </remarks> FILE_OPEN_NO_RECALL = 0x00400000 // Behavior undocumented, defined in headers // FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000 } /// <summary> /// System.IO.FileAccess looks up these values when creating handles /// </summary> /// <remarks> /// File Security and Access Rights /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399.aspx /// </remarks> [Flags] public enum DesiredAccess : uint { // File Access Rights Constants // https://msdn.microsoft.com/en-us/library/windows/desktop/gg258116.aspx /// <summary> /// For a file, the right to read data from the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_LIST_DIRECTORY"/>. /// </remarks> FILE_READ_DATA = 0x0001, /// <summary> /// For a directory, the right to list the contents. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_READ_DATA"/>. /// </remarks> FILE_LIST_DIRECTORY = 0x0001, /// <summary> /// For a file, the right to write data to the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_ADD_FILE"/>. /// </remarks> FILE_WRITE_DATA = 0x0002, /// <summary> /// For a directory, the right to create a file in a directory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_WRITE_DATA"/>. /// </remarks> FILE_ADD_FILE = 0x0002, /// <summary> /// For a file, the right to append data to a file. <see cref="FILE_WRITE_DATA"/> is needed /// to overwrite existing data. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_ADD_SUBDIRECTORY"/>. /// </remarks> FILE_APPEND_DATA = 0x0004, /// <summary> /// For a directory, the right to create a subdirectory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_APPEND_DATA"/>. /// </remarks> FILE_ADD_SUBDIRECTORY = 0x0004, /// <summary> /// For a named pipe, the right to create a pipe instance. /// </summary> FILE_CREATE_PIPE_INSTANCE = 0x0004, /// <summary> /// The right to read extended attributes. /// </summary> FILE_READ_EA = 0x0008, /// <summary> /// The right to write extended attributes. /// </summary> FILE_WRITE_EA = 0x0010, /// <summary> /// The right to execute the file. /// </summary> /// <remarks> /// Directory version of this flag is <see cref="FILE_TRAVERSE"/>. /// </remarks> FILE_EXECUTE = 0x0020, /// <summary> /// For a directory, the right to traverse the directory. /// </summary> /// <remarks> /// File version of this flag is <see cref="FILE_EXECUTE"/>. /// </remarks> FILE_TRAVERSE = 0x0020, /// <summary> /// For a directory, the right to delete a directory and all /// the files it contains, including read-only files. /// </summary> FILE_DELETE_CHILD = 0x0040, /// <summary> /// The right to read attributes. /// </summary> FILE_READ_ATTRIBUTES = 0x0080, /// <summary> /// The right to write attributes. /// </summary> FILE_WRITE_ATTRIBUTES = 0x0100, /// <summary> /// All standard and specific rights. [FILE_ALL_ACCESS] /// </summary> FILE_ALL_ACCESS = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER | 0x1FF, /// <summary> /// The right to delete the object. /// </summary> DELETE = 0x00010000, /// <summary> /// The right to read the information in the object's security descriptor. /// Doesn't include system access control list info (SACL). /// </summary> READ_CONTROL = 0x00020000, /// <summary> /// The right to modify the discretionary access control list (DACL) in the /// object's security descriptor. /// </summary> WRITE_DAC = 0x00040000, /// <summary> /// The right to change the owner in the object's security descriptor. /// </summary> WRITE_OWNER = 0x00080000, /// <summary> /// The right to use the object for synchronization. Enables a thread to wait until the object /// is in the signaled state. This is required if opening a synchronous handle. /// </summary> SYNCHRONIZE = 0x00100000, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_READ = READ_CONTROL, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_WRITE = READ_CONTROL, /// <summary> /// Same as READ_CONTROL. /// </summary> STANDARD_RIGHTS_EXECUTE = READ_CONTROL, /// <summary> /// Maps internally to <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="FILE_READ_DATA"/> | <see cref="FILE_READ_EA"/> /// | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="FILE_LIST_DIRECTORY"/> | <see cref="FILE_READ_EA"/> /// | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_READ = 0x80000000, // GENERIC_READ /// <summary> /// Maps internally to <see cref="FILE_APPEND_DATA"/> | <see cref="FILE_WRITE_ATTRIBUTES"/> | <see cref="FILE_WRITE_DATA"/> /// | <see cref="FILE_WRITE_EA"/> | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_ADD_SUBDIRECTORY"/> | <see cref="FILE_WRITE_ATTRIBUTES"/> | <see cref="FILE_ADD_FILE"/> AddFile /// | <see cref="FILE_WRITE_EA"/> | <see cref="STANDARD_RIGHTS_READ"/> | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_WRITE = 0x40000000, // GENERIC WRITE /// <summary> /// Maps internally to <see cref="FILE_EXECUTE"/> | <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="STANDARD_RIGHTS_EXECUTE"/> /// | <see cref="SYNCHRONIZE"/>. /// (For directories, <see cref="FILE_DELETE_CHILD"/> | <see cref="FILE_READ_ATTRIBUTES"/> | <see cref="STANDARD_RIGHTS_EXECUTE"/> /// | <see cref="SYNCHRONIZE"/>.) /// </summary> FILE_GENERIC_EXECUTE = 0x20000000 // GENERIC_EXECUTE } } }
using Android.Content; using Android.OS; using Android.Support.V7.Widget; using Android.Util; using Android.Views; using Java.Lang; namespace ObservableScrollView { public class ObservableRecyclerView : RecyclerView, IScrollable { private static int _recyclerViewLibraryVersion = 22; // Fields that should be saved onSaveInstanceState private int _mPrevFirstVisiblePosition; private int _mPrevFirstVisibleChildHeight = -1; private int _mPrevScrolledChildrenHeight; private int _mPrevScrollY; private int _mScrollY; private SparseIntArray _mChildrenHeights; // Fields that don't need to be saved onSaveInstanceState private IObservableScrollViewCallbacks _mCallbacks; private ObservableScrollState _mScrollState; private bool _mFirstScroll; private bool _mDragging; private bool _mIntercepted; private MotionEvent _mPrevMoveEvent; private ViewGroup _mTouchInterceptionViewGroup; public ObservableRecyclerView(Context context) : base(context) { Init(); } public ObservableRecyclerView(Context context, IAttributeSet attrs) : base(context, attrs) { Init(); } public ObservableRecyclerView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { Init(); } protected override void OnRestoreInstanceState(IParcelable state) { ObservableListSavedState ss = (ObservableListSavedState) state; _mPrevFirstVisiblePosition = ss.PrevFirstVisiblePosition; _mPrevFirstVisibleChildHeight = ss.PrevFirstVisibleChildHeight; _mPrevScrolledChildrenHeight = ss.PrevScrolledChildrenHeight; _mPrevScrollY = ss.PrevScrollY; _mScrollY = ss.ScrollY; _mChildrenHeights = ss.ChildrenHeights; base.OnRestoreInstanceState(ss.SuperState); } protected override IParcelable OnSaveInstanceState() { IParcelable superState = base.OnSaveInstanceState(); ObservableListSavedState ss = new ObservableListSavedState(superState) { PrevFirstVisiblePosition = _mPrevFirstVisiblePosition, PrevFirstVisibleChildHeight = _mPrevFirstVisibleChildHeight, PrevScrolledChildrenHeight = _mPrevScrolledChildrenHeight, PrevScrollY = _mPrevScrollY, ScrollY = _mScrollY, ChildrenHeights = _mChildrenHeights }; return ss; } protected override void OnScrollChanged(int l, int t, int oldl, int oldt) { base.OnScrollChanged(l, t, oldl, oldt); if (_mCallbacks != null) { if (ChildCount > 0) { int firstVisiblePosition = GetChildAdapterPosition(GetChildAt(0)); int lastVisiblePosition = GetChildAdapterPosition(GetChildAt(ChildCount - 1)); for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) { int childHeight = 0; View child = GetChildAt(j); if (child != null) { if (_mChildrenHeights.IndexOfKey(i) < 0 || (child.Height != _mChildrenHeights.Get(i))) { childHeight = child.Height; } } _mChildrenHeights.Put(i, childHeight); } View firstVisibleChild = GetChildAt(0); if (firstVisibleChild != null) { if (_mPrevFirstVisiblePosition < firstVisiblePosition) { // scroll down int skippedChildrenHeight = 0; if (firstVisiblePosition - _mPrevFirstVisiblePosition != 1) { for (int i = firstVisiblePosition - 1; i > _mPrevFirstVisiblePosition; i--) { if (0 < _mChildrenHeights.IndexOfKey(i)) { skippedChildrenHeight += _mChildrenHeights.Get(i); } else { // Approximate each item's height to the first visible child. // It may be incorrect, but without this, scrollY will be broken // when scrolling from the bottom. skippedChildrenHeight += firstVisibleChild.Height; } } } _mPrevScrolledChildrenHeight += _mPrevFirstVisibleChildHeight + skippedChildrenHeight; _mPrevFirstVisibleChildHeight = firstVisibleChild.Height; } else if (firstVisiblePosition < _mPrevFirstVisiblePosition) { // scroll up int skippedChildrenHeight = 0; if (_mPrevFirstVisiblePosition - firstVisiblePosition != 1) { for (int i = _mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--) { if (0 < _mChildrenHeights.IndexOfKey(i)) { skippedChildrenHeight += _mChildrenHeights.Get(i); } else { // Approximate each item's height to the first visible child. // It may be incorrect, but without this, scrollY will be broken // when scrolling from the bottom. skippedChildrenHeight += firstVisibleChild.Height; } } } _mPrevScrolledChildrenHeight -= firstVisibleChild.Height + skippedChildrenHeight; _mPrevFirstVisibleChildHeight = firstVisibleChild.Height; } else if (firstVisiblePosition == 0) { _mPrevFirstVisibleChildHeight = firstVisibleChild.Height; _mPrevScrolledChildrenHeight = 0; } if (_mPrevFirstVisibleChildHeight < 0) { _mPrevFirstVisibleChildHeight = 0; } _mScrollY = _mPrevScrolledChildrenHeight - firstVisibleChild.Top; _mPrevFirstVisiblePosition = firstVisiblePosition; _mCallbacks.OnScrollChanged(_mScrollY, _mFirstScroll, _mDragging); if (_mFirstScroll) { _mFirstScroll = false; } if (_mPrevScrollY < _mScrollY) { //down _mScrollState = ObservableScrollState.Up; } else if (_mScrollY < _mPrevScrollY) { //up _mScrollState = ObservableScrollState.Down; } else { _mScrollState = ObservableScrollState.Stop; } _mPrevScrollY = _mScrollY; } } } } public override bool OnInterceptTouchEvent(MotionEvent ev) { if (_mCallbacks != null) { switch (ev.ActionMasked) { case MotionEventActions.Down: // Whether or not motion events are consumed by children, // flag initializations which are related to ACTION_DOWN events should be executed. // Because if the ACTION_DOWN is consumed by children and only ACTION_MOVEs are // passed to parent (this view), the flags will be invalid. // Also, applications might implement initialization codes to onDownMotionEvent, // so call it here. _mFirstScroll = _mDragging = true; _mCallbacks.OnDownMotionEvent(); break; } } return base.OnInterceptTouchEvent(ev); } public override bool OnTouchEvent(MotionEvent ev) { if (_mCallbacks != null) { switch (ev.ActionMasked) { case MotionEventActions.Up: case MotionEventActions.Cancel: _mIntercepted = false; _mDragging = false; _mCallbacks.OnUpOrCancelMotionEvent(_mScrollState); break; case MotionEventActions.Move: if (_mPrevMoveEvent == null) { _mPrevMoveEvent = ev; } float diffY = ev.GetY() - _mPrevMoveEvent.GetY(); _mPrevMoveEvent = MotionEvent.ObtainNoHistory(ev); if (GetCurrentScrollY() - diffY <= 0) { // Can't scroll anymore. if (_mIntercepted) { // Already dispatched ACTION_DOWN event to parents, so stop here. return false; } // Apps can set the interception target other than the direct parent. ViewGroup parent; if (_mTouchInterceptionViewGroup == null) { parent = (ViewGroup) Parent; } else { parent = _mTouchInterceptionViewGroup; } // Get offset to parents. If the parent is not the direct parent, // we should aggregate offsets from all of the parents. float offsetX = 0; float offsetY = 0; for (View v = this; v != null && v != parent; v = (View) v.Parent) { offsetX += v.Left - v.ScrollX; offsetY += v.Top - v.ScrollY; } MotionEvent event2 = MotionEvent.ObtainNoHistory(ev); event2.OffsetLocation(offsetX, offsetY); if (parent.OnInterceptTouchEvent(event2)) { _mIntercepted = true; // If the parent wants to intercept ACTION_MOVE events, // we pass ACTION_DOWN event to the parent // as if these touch events just have began now. event2.Action = MotionEventActions.Down; // Return this onTouchEvent() first and set ACTION_DOWN event for parent // to the queue, to keep events sequence. Post(() => parent.DispatchTouchEvent(event2)); return false; } // Even when this can't be scrolled anymore, // simply returning false here may cause subView's click, // so delegate it to base. return base.OnTouchEvent(ev); } break; } } return base.OnTouchEvent(ev); } public void SetScrollViewCallbacks(IObservableScrollViewCallbacks listener) { _mCallbacks = listener; } public void SetTouchInterceptionViewGroup(ViewGroup viewGroup) { _mTouchInterceptionViewGroup = viewGroup; } public void ScrollVerticallyTo(int y) { View firstVisibleChild = GetChildAt(0); if (firstVisibleChild != null) { int baseHeight = firstVisibleChild.Height; int position = y / baseHeight; ScrollVerticallyToPosition(position); } } /** * <p>Same as {@linkplain #scrollToPosition(int)} but it scrolls to the position not only make * the position visible.</p> * <p>It depends on {@code LayoutManager} how {@linkplain #scrollToPosition(int)} works, * and currently we know that {@linkplain LinearLayoutManager#scrollToPosition(int)} just * make the position visible.</p> * <p>In LinearLayoutManager, scrollToPositionWithOffset() is provided for scrolling to the position. * This method checks which LayoutManager is set, * and handles which method should be called for scrolling.</p> * <p>Other know classes (StaggeredGridLayoutManager and GridLayoutManager) are not tested.</p> * * @param position position to scroll */ public void ScrollVerticallyToPosition(int position) { LayoutManager lm = GetLayoutManager(); LinearLayoutManager manager = lm as LinearLayoutManager; if (manager != null) { manager.ScrollToPositionWithOffset(position, 0); } else { ScrollToPosition(position); } } public int GetCurrentScrollY() { return _mScrollY; } public override int GetChildAdapterPosition(View child) { if (22 <= _recyclerViewLibraryVersion) { return base.GetChildAdapterPosition(child); } #pragma warning disable 618 return GetChildPosition(child); #pragma warning restore 618 } private void Init() { _mChildrenHeights = new SparseIntArray(); CheckLibraryVersion(); } private void CheckLibraryVersion() { try { base.GetChildAdapterPosition(null); } catch (NoSuchMethodError) { _recyclerViewLibraryVersion = 21; } } } }
using NUnit.Framework; using System.IO; using System.Linq; using SecureBanana.Console.Abstractions; using Moq; namespace SecureBanana.Console.ServiceImplementations { [TestFixture] public class EncryptorImplementationTests { #region Test Dependencies public class DummyEncryptor : System.Security.Cryptography.ICryptoTransform { public System.Func<byte, byte> ByteTransform { get; private set; } public int BlockSize { get; private set; } public DummyEncryptor(System.Func<byte, byte> byteTransform, int blockSize) { ByteTransform = byteTransform; BlockSize = blockSize; } #region ICryptoTransform Members public bool CanReuseTransform { get { return true; } } public bool CanTransformMultipleBlocks { get { return true; } } public int InputBlockSize { get { return BlockSize; } } public int OutputBlockSize { get { return BlockSize; } } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { int i = 0; for (i = 0; i < inputCount; i++) { outputBuffer[i + outputOffset] = ByteTransform(inputBuffer[i + inputOffset]); } return i; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] result = new byte[inputCount]; TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); return result; } #endregion #region IDisposable Members public void Dispose() { } #endregion } public class DummyStream : MemoryStream { public DummyStream() : base() { } public DummyStream(byte[] bytes) : base(bytes) { } public override void Close() { } protected override void Dispose(bool disposing) { } public void BaseClose() { base.Close(); } public void BaseDispose(bool disposing) { base.Dispose(disposing); } } #endregion [Test] public void Constructor_NullAlgorithm() { try { new EncryptorImplementation(null, Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Assert.Fail("An ArgumentNulLException was expected."); } catch (System.ArgumentNullException) { } } [Test] public void Constructor_NullHashAlgorithm() { try { new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), null, Mock.Of<IFile>()); Assert.Fail("An ArgumentNulLException was expected."); } catch (System.ArgumentNullException) { } } [Test] public void Constructor_NullFileSystem() { try { new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), null); Assert.Fail("An ArgumentNulLException was expected."); } catch (System.ArgumentNullException) { } } [Test] public void Constructor_AlgorithmSet() { var algorithm = Mock.Of<IAESAlgorithm>(); var target = new EncryptorImplementation(algorithm, Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Assert.AreEqual(algorithm, target.Algorithm); } [Test] public void Constructor_HashAlgorithmSet() { var hashAlgorithm = Mock.Of<IHashAlgorithm>(); var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), hashAlgorithm, Mock.Of<IFile>()); Assert.AreEqual(hashAlgorithm, target.HashAlgorithm); } [Test] public void Constructor_FileSystemSet() { var fileSystem = Mock.Of<IFile>(); var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), fileSystem); Assert.AreEqual(fileSystem, target.FileSystem); } [Test] public void EncryptTest_NullInput() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Encrypt(null, Mock.Of<System.IO.Stream>(), "TestPassword"); Assert.Fail("An ArgumentNullException was expected."); } catch(System.ArgumentNullException) { } } [Test] public void EncryptTest_NullOutput() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Encrypt(Mock.Of<System.IO.Stream>(), null, "TestPassword"); Assert.Fail("An ArgumentNullException was expected."); } catch(System.ArgumentNullException) { } } [Test] public void EncryptTest_NullPassword() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Encrypt(Mock.Of<System.IO.Stream>(), Mock.Of<System.IO.Stream>(), null); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void EncryptTest_EmptyPassword() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Encrypt(Mock.Of<System.IO.Stream>(), Mock.Of<System.IO.Stream>(), string.Empty); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void EncryptTest() { byte[] bytesToEncrypt = new byte[] { 1, 2, 3, 4, 5, 6 }; byte[] expectedEncryptedBytes = new byte[] { 2, 4, 6, 8, 10, 12 }; byte[] hashedPasswordBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 7, 1, 2, 3, 4, 5, 6, 7, 6, 1, 2, 3, 4, 5, 6, 7, 5, 1, 2, 3, 4, 5, 6, 7, 4, 1, 2, 3, 4, 5, 6, 7, 3, 1, 2, 3, 4, 5, 6, 7, 2, 1, 2, 3, 4, 5, 6, 7, 1, }; string password = "TestRandomPassword"; System.Func<byte, byte> transformMethod = (a) => { if(a >= 127) return System.Byte.MaxValue; return (byte)(a * 2); }; MemoryStream streamToEncrypt = new MemoryStream(bytesToEncrypt); MemoryStream outputStream = new MemoryStream(); Mock<IHashAlgorithm> hashMock = new Mock<IHashAlgorithm>(); Mock<IAESAlgorithm> aesMock = new Mock<IAESAlgorithm>(); DummyEncryptor transform = new DummyEncryptor(transformMethod, 16); hashMock.Setup(a => a.ComputeHash(It.IsAny<byte[]>())).Returns(hashedPasswordBytes); aesMock.Setup(a => a.CreateEncryptor(It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(transform); EncryptorImplementation encryptor = new EncryptorImplementation(aesMock.Object, hashMock.Object, Mock.Of<IFile>()); encryptor.Encrypt(streamToEncrypt, outputStream, password); outputStream.Position = 0; CollectionAssert.AreEqual(expectedEncryptedBytes, outputStream.ToArray()); } [Test] public void DecryptTest_NullOutput() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Decrypt(Mock.Of<System.IO.Stream>(), null, "TestPassword"); Assert.Fail("An ArgumentNullException was expected."); } catch(System.ArgumentNullException) { } } [Test] public void DecryptTest_NullPassword() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Decrypt(Mock.Of<System.IO.Stream>(), Mock.Of<System.IO.Stream>(), null); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void DecryptTest_EmptyPassword() { try { var target = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); target.Decrypt(Mock.Of<System.IO.Stream>(), Mock.Of<System.IO.Stream>(), string.Empty); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void DecryptTest() { byte[] bytesToDecrypt = new byte[] { 1, 2, 3, 4, 5, 6 }; byte[] expectedDecryptedBytes = new byte[] { 2, 4, 6, 8, 10, 12 }; byte[] hashedPasswordBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 7, 1, 2, 3, 4, 5, 6, 7, 6, 1, 2, 3, 4, 5, 6, 7, 5, 1, 2, 3, 4, 5, 6, 7, 4, 1, 2, 3, 4, 5, 6, 7, 3, 1, 2, 3, 4, 5, 6, 7, 2, 1, 2, 3, 4, 5, 6, 7, 1, }; string password = "TestRandomPassword"; System.Func<byte, byte> transformMethod = (a) => { if(a >= 127) return System.Byte.MaxValue; return (byte)(a * 2); }; MemoryStream streamToDecrypt = new MemoryStream(bytesToDecrypt); MemoryStream outputStream = new MemoryStream(); Mock<IHashAlgorithm> hashMock = new Mock<IHashAlgorithm>(); Mock<IAESAlgorithm> aesMock = new Mock<IAESAlgorithm>(); DummyEncryptor transform = new DummyEncryptor(transformMethod, 16); hashMock.Setup(a => a.ComputeHash(It.IsAny<byte[]>())).Returns(hashedPasswordBytes); aesMock.Setup(a => a.CreateDecryptor(It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(transform); EncryptorImplementation Encryptor = new EncryptorImplementation(aesMock.Object, hashMock.Object, Mock.Of<IFile>()); Encryptor.Decrypt(streamToDecrypt, outputStream, password); outputStream.Position = 0; CollectionAssert.AreEqual(expectedDecryptedBytes, outputStream.ToArray()); } [Test] public void Encrypt_File_NullInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt(null, "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_EmptyInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt(string.Empty, "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_WhiteSpaceInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("\t", "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_NullOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", null, "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_EmptyOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", string.Empty, "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_WhiteSpaceOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", "\t", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_NullPassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", "TestOutput", null); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_EmptyPassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", "TestOutput", string.Empty); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File_WhiteSpacePassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Encrypt("TestInput", "TestOutput", "\t"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Encrypt_File() { byte[] bytesToEncrypt = new byte[] { 1, 2, 3, 4, 5, 6 }; byte[] expectedEncryptedBytes = new byte[] { 2, 4, 6, 8, 10, 12 }; byte[] hashedPasswordBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 7, 1, 2, 3, 4, 5, 6, 7, 6, 1, 2, 3, 4, 5, 6, 7, 5, 1, 2, 3, 4, 5, 6, 7, 4, 1, 2, 3, 4, 5, 6, 7, 3, 1, 2, 3, 4, 5, 6, 7, 2, 1, 2, 3, 4, 5, 6, 7, 1, }; string inputFilePath = "TestInputFilePath"; string outputFilePath = "TestOutputFilePath"; string password = "TestRandomPassword"; System.Func<byte, byte> transformMethod = (a) => { if(a >= 127) return System.Byte.MaxValue; return (byte)(a * 2); }; DummyStream streamToEncrypt = new DummyStream(bytesToEncrypt); DummyStream outputStream = new DummyStream(); Mock<IHashAlgorithm> hashMock = new Mock<IHashAlgorithm>(); Mock<IAESAlgorithm> aesMock = new Mock<IAESAlgorithm>(); Mock<IFile> fileMock = new Mock<IFile>(); DummyEncryptor transform = new DummyEncryptor(transformMethod, 16); hashMock.Setup(a => a.ComputeHash(It.IsAny<byte[]>())).Returns(hashedPasswordBytes); aesMock.Setup(a => a.CreateEncryptor(It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(transform); fileMock.Setup(a => a.Exists(inputFilePath)).Returns(true); fileMock.Setup(a => a.Exists(outputFilePath)).Returns(false); fileMock.Setup(a => a.OpenRead(inputFilePath)).Returns(streamToEncrypt); fileMock.Setup(a => a.OpenWrite(outputFilePath)).Returns(outputStream); EncryptorImplementation encryptor = new EncryptorImplementation(aesMock.Object, hashMock.Object, fileMock.Object); encryptor.Encrypt(inputFilePath, outputFilePath, password); outputStream.Position = 0; CollectionAssert.AreEqual(expectedEncryptedBytes, outputStream.ToArray()); } [Test] public void Decrypt_File_NullInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt(null, "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_EmptyInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt(string.Empty, "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_WhiteSpaceInput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("\t", "TestOutput", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_NullOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", null, "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_EmptyOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", string.Empty, "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_WhiteSpaceOutput() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", "\t", "TestPassword"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_NullPassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", "TestOutput", null); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_EmptyPassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", "TestOutput", string.Empty); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File_WhiteSpacePassword() { try { EncryptorImplementation Encryptor = new EncryptorImplementation(Mock.Of<IAESAlgorithm>(), Mock.Of<IHashAlgorithm>(), Mock.Of<IFile>()); Encryptor.Decrypt("TestInput", "TestOutput", "\t"); Assert.Fail("An ArgumentException was expected."); } catch(System.ArgumentException) { } } [Test] public void Decrypt_File() { byte[] bytesToDecrypt = new byte[] { 1, 2, 3, 4, 5, 6 }; byte[] expectedDecryptedBytes = new byte[] { 2, 4, 6, 8, 10, 12 }; byte[] hashedPasswordBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 7, 1, 2, 3, 4, 5, 6, 7, 6, 1, 2, 3, 4, 5, 6, 7, 5, 1, 2, 3, 4, 5, 6, 7, 4, 1, 2, 3, 4, 5, 6, 7, 3, 1, 2, 3, 4, 5, 6, 7, 2, 1, 2, 3, 4, 5, 6, 7, 1, }; string inputFilePath = "TestInputFilePath"; string outputFilePath = "TestOutputFilePath"; string password = "TestRandomPassword"; System.Func<byte, byte> transformMethod = (a) => { if(a >= 127) return System.Byte.MaxValue; return (byte)(a * 2); }; DummyStream streamToDecrypt = new DummyStream(bytesToDecrypt); DummyStream outputStream = new DummyStream(); Mock<IHashAlgorithm> hashMock = new Mock<IHashAlgorithm>(); Mock<IAESAlgorithm> aesMock = new Mock<IAESAlgorithm>(); Mock<IFile> fileMock = new Mock<IFile>(); DummyEncryptor transform = new DummyEncryptor(transformMethod, 16); hashMock.Setup(a => a.ComputeHash(It.IsAny<byte[]>())).Returns(hashedPasswordBytes); aesMock.Setup(a => a.CreateDecryptor(It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(transform); fileMock.Setup(a => a.Exists(inputFilePath)).Returns(true); fileMock.Setup(a => a.Exists(outputFilePath)).Returns(false); fileMock.Setup(a => a.OpenRead(inputFilePath)).Returns(streamToDecrypt); fileMock.Setup(a => a.OpenWrite(outputFilePath)).Returns(outputStream); EncryptorImplementation Encryptor = new EncryptorImplementation(aesMock.Object, hashMock.Object, fileMock.Object); Encryptor.Decrypt(inputFilePath, outputFilePath, password); outputStream.Position = 0; CollectionAssert.AreEqual(expectedDecryptedBytes, outputStream.ToArray()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Collections; using System.Threading.Tasks; using System.Globalization; using System.Runtime.InteropServices; namespace MICore { public class PipeTransport : StreamTransport { private Process _process; private StreamReader _stdErrReader; private int _remainingReaders; private ManualResetEvent _allReadersDone = new ManualResetEvent(false); private bool _killOnClose; private bool _filterStderr; private int _debuggerPid = -1; private string _pipePath; private string _cmdArgs; public PipeTransport(bool killOnClose = false, bool filterStderr = false, bool filterStdout = false) : base(filterStdout) { _killOnClose = killOnClose; _filterStderr = filterStderr; } public bool Interrupt(int pid) { if (_cmdArgs == null) { return false; } string killCmd = string.Format(CultureInfo.InvariantCulture, "kill -2 {0}", pid); return WrappedExecuteSyncCommand(MICoreResources.Info_KillingPipeProcess, killCmd, Timeout.Infinite) == 0; } protected override string GetThreadName() { return "MI.PipeTransport"; } /// <summary> /// The value of this property reflects the pid for the debugger running /// locally. /// </summary> public override int DebuggerPid { get { return _debuggerPid; } } protected virtual void InitProcess(Process proc, out StreamReader stdout, out StreamWriter stdin) { _process = proc; _process.EnableRaisingEvents = true; _process.Exited += OnProcessExit; _process.StartInfo.RedirectStandardInput = true; _process.StartInfo.RedirectStandardOutput = true; _process.StartInfo.RedirectStandardError = true; _process.StartInfo.UseShellExecute = false; _process.StartInfo.CreateNoWindow = true; lock (_process) { this.Callback.AppendToInitializationLog(string.Format(CultureInfo.InvariantCulture, "Starting: \"{0}\" {1}", _process.StartInfo.FileName, _process.StartInfo.Arguments)); try { _process.Start(); } catch (Exception e) { throw new Exception(String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_PipeProgramStart, _process.StartInfo.FileName, e.Message)); } _debuggerPid = _process.Id; stdout = _process.StandardOutput; stdin = _process.StandardInput; _stdErrReader = _process.StandardError; _remainingReaders = 2; AsyncReadFromStdError(); } } public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer) { PipeLaunchOptions pipeOptions = (PipeLaunchOptions)options; string workingDirectory = pipeOptions.PipeCwd; if (!string.IsNullOrWhiteSpace(workingDirectory)) { if (!LocalLaunchOptions.CheckDirectoryPath(workingDirectory)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_InvalidLocalDirectoryPath, workingDirectory)); } } else { workingDirectory = Path.GetDirectoryName(pipeOptions.PipePath); if (!LocalLaunchOptions.CheckDirectoryPath(workingDirectory)) { // If provided PipeCwd is not an absolute path, the working directory will be set to null. workingDirectory = null; } } if (string.IsNullOrWhiteSpace(pipeOptions.PipePath)) { throw new ArgumentException(MICoreResources.Error_EmptyPipePath); } _cmdArgs = pipeOptions.PipeCommandArguments; Process proc = new Process(); _pipePath = pipeOptions.PipePath; proc.StartInfo.FileName = pipeOptions.PipePath; proc.StartInfo.Arguments = pipeOptions.PipeArguments; proc.StartInfo.WorkingDirectory = workingDirectory; foreach (EnvironmentEntry entry in pipeOptions.PipeEnvironment) { proc.StartInfo.SetEnvironmentVariable(entry.Name, entry.Value); } InitProcess(proc, out reader, out writer); } /// <summary> /// Kills the pipe process and its child processes. /// It maybe the debugger itself it is local. /// </summary> /// <param name="p">Process to kill.</param> private void KillPipeProcessAndChildren(Process p) { UnixUtilities.KillProcessTree(p); if (!p.HasExited) { p.Kill(); } } public override void Close() { if (_writer != null) { try { Echo("logout"); } catch (Exception) { // Ignore errors if logout couldn't be written } } base.Close(); if (_stdErrReader != null) { _stdErrReader.Dispose(); } _allReadersDone.Set(); if (_process != null) { _process.EnableRaisingEvents = false; _process.Exited -= OnProcessExit; if (_killOnClose && !_process.HasExited) { try { KillPipeProcessAndChildren(_process); } catch { } } _process.Dispose(); } } protected override void OnReadStreamAborted() { DecrementReaders(); try { if (_process.WaitForExit(1000)) { // If the pipe process has already exited, or is just about to exit, we want to send the abort event from OnProcessExit // instead of from here since that will have access to stderr return; } } catch (InvalidOperationException) { Debug.Assert(IsClosed); return; // already closed } base.OnReadStreamAborted(); } private async void AsyncReadFromStream(StreamReader stream, Action<string> lineHandler) { try { while (true) { string line = await stream.ReadLineAsync(); if (line == null) break; lineHandler(line); } } catch (Exception) { // If anything goes wrong, don't crash VS } } private async void AsyncReadFromStdError() { try { while (true) { string line = await _stdErrReader.ReadLineAsync(); if (line == null) break; if (_filterStderr) { line = FilterLine(line); } if (!string.IsNullOrWhiteSpace(line)) { this.Callback.OnStdErrorLine(line); } } } catch (Exception) { // If anything goes wrong, don't crash VS } DecrementReaders(); } /// <summary> /// Called when either the stderr or the stdout reader exits. Used to synchronize between obtaining stderr/stdout content and the target process exiting. /// </summary> private void DecrementReaders() { if (Interlocked.Decrement(ref _remainingReaders) == 0) { _allReadersDone.Set(); } } private void OnProcessExit(object sender, EventArgs e) { // Wait until 'Init' gets a chance to set m_Reader/m_Writer before sending up the debugger exit event if (_reader == null || _writer == null) { lock (_process) { if (_reader == null || _writer == null) { return; // something went wrong and these are still null, ignore process exit } } } // Wait for a bit to get all the stderr/stdout text. We can't wait too long on this since it is possble that // this pipe might still be arround if the the process we started kicked off other processes that still have // our pipe. _allReadersDone.WaitOne(100); // We are sometimes seeing m_process throw InvalidOperationExceptions by the time we get here. // Attempt to get the real exit code, if we can't, still log the message with unknown exit code. string exitCode = null; try { exitCode = string.Format(CultureInfo.InvariantCulture, "{0} (0x{0:X})", _process.ExitCode); } catch (InvalidOperationException) { } this.Callback.AppendToInitializationLog(string.Format(CultureInfo.InvariantCulture, "\"{0}\" exited with code {1}.", _process.StartInfo.FileName, exitCode ?? "???")); try { this.Callback.OnDebuggerProcessExit(exitCode); } catch { // We have no exception back stop here, and we are trying to report failures. But if something goes wrong, // lets not crash VS } } private int WrappedExecuteSyncCommand(string commandDescription, string commandText, int timeout) { int exitCode = -1; string output = null; string error = null; string pipeArgs = PipeLaunchOptions.ReplaceDebuggerCommandToken(_cmdArgs, commandText, true); string fullCommand = string.Format(CultureInfo.InvariantCulture, "{0} {1}", _pipePath, pipeArgs); try { exitCode = ExecuteSyncCommand(commandDescription, commandText, timeout, out output, out error); if (exitCode != 0) { this.Callback.OnStdErrorLine(string.Format(CultureInfo.InvariantCulture, MICoreResources.Warn_ProcessExit, fullCommand, exitCode)); } } catch (Exception e) { this.Callback.OnStdErrorLine(string.Format(CultureInfo.InvariantCulture, MICoreResources.Warn_ProcessException, fullCommand, e.Message)); } return exitCode; } public override int ExecuteSyncCommand(string commandDescription, string commandText, int timeout, out string output, out string error) { output = null; error = null; int exitCode = -1; Process proc = new Process(); proc.StartInfo.FileName = _pipePath; proc.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, _cmdArgs, commandText); proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(_pipePath); proc.EnableRaisingEvents = false; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(timeout); exitCode = proc.ExitCode; output = proc.StandardOutput.ReadToEnd(); error = proc.StandardError.ReadToEnd(); return exitCode; } public override bool CanExecuteCommand() { return true; } } }
using System; using Raksha.Asn1.X509; namespace Raksha.Asn1.Cms { public class AuthenticatedData : Asn1Encodable { private DerInteger version; private OriginatorInfo originatorInfo; private Asn1Set recipientInfos; private AlgorithmIdentifier macAlgorithm; private AlgorithmIdentifier digestAlgorithm; private ContentInfo encapsulatedContentInfo; private Asn1Set authAttrs; private Asn1OctetString mac; private Asn1Set unauthAttrs; public AuthenticatedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, AlgorithmIdentifier macAlgorithm, AlgorithmIdentifier digestAlgorithm, ContentInfo encapsulatedContent, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { if (digestAlgorithm != null || authAttrs != null) { if (digestAlgorithm == null || authAttrs == null) { throw new ArgumentException("digestAlgorithm and authAttrs must be set together"); } } version = new DerInteger(CalculateVersion(originatorInfo)); this.originatorInfo = originatorInfo; this.macAlgorithm = macAlgorithm; this.digestAlgorithm = digestAlgorithm; this.recipientInfos = recipientInfos; this.encapsulatedContentInfo = encapsulatedContent; this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; } private AuthenticatedData( Asn1Sequence seq) { int index = 0; version = (DerInteger)seq[index++]; Asn1Encodable tmp = seq[index++]; if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } recipientInfos = Asn1Set.GetInstance(tmp); macAlgorithm = AlgorithmIdentifier.GetInstance(seq[index++]); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { digestAlgorithm = AlgorithmIdentifier.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } encapsulatedContentInfo = ContentInfo.GetInstance(tmp); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)seq[index], false); } } /** * return an AuthenticatedData object from a tagged object. * * @param obj the tagged object holding the object we want. * @param isExplicit true if the object is meant to be explicitly * tagged false otherwise. * @throws ArgumentException if the object held by the * tagged object cannot be converted. */ public static AuthenticatedData GetInstance( Asn1TaggedObject obj, bool isExplicit) { return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); } /** * return an AuthenticatedData object from the given object. * * @param obj the object we want converted. * @throws ArgumentException if the object cannot be converted. */ public static AuthenticatedData GetInstance( object obj) { if (obj == null || obj is AuthenticatedData) { return (AuthenticatedData)obj; } if (obj is Asn1Sequence) { return new AuthenticatedData((Asn1Sequence)obj); } throw new ArgumentException("Invalid AuthenticatedData: " + obj.GetType().Name); } public DerInteger Version { get { return version; } } public OriginatorInfo OriginatorInfo { get { return originatorInfo; } } public Asn1Set RecipientInfos { get { return recipientInfos; } } public AlgorithmIdentifier MacAlgorithm { get { return macAlgorithm; } } public AlgorithmIdentifier DigestAlgorithm { get { return digestAlgorithm; } } public ContentInfo EncapsulatedContentInfo { get { return encapsulatedContentInfo; } } public Asn1Set AuthAttrs { get { return authAttrs; } } public Asn1OctetString Mac { get { return mac; } } public Asn1Set UnauthAttrs { get { return unauthAttrs; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * AuthenticatedData ::= SEQUENCE { * version CMSVersion, * originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL, * recipientInfos RecipientInfos, * macAlgorithm MessageAuthenticationCodeAlgorithm, * digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL, * encapContentInfo EncapsulatedContentInfo, * authAttrs [2] IMPLICIT AuthAttributes OPTIONAL, * mac MessageAuthenticationCode, * unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL } * * AuthAttributes ::= SET SIZE (1..MAX) OF Attribute * * UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute * * MessageAuthenticationCode ::= OCTET STRING * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(version); if (originatorInfo != null) { v.Add(new DerTaggedObject(false, 0, originatorInfo)); } v.Add(recipientInfos, macAlgorithm); if (digestAlgorithm != null) { v.Add(new DerTaggedObject(false, 1, digestAlgorithm)); } v.Add(encapsulatedContentInfo); if (authAttrs != null) { v.Add(new DerTaggedObject(false, 2, authAttrs)); } v.Add(mac); if (unauthAttrs != null) { v.Add(new DerTaggedObject(false, 3, unauthAttrs)); } return new BerSequence(v); } public static int CalculateVersion(OriginatorInfo origInfo) { if (origInfo == null) return 0; int ver = 0; foreach (object obj in origInfo.Certificates) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tag = (Asn1TaggedObject)obj; if (tag.TagNo == 2) { ver = 1; } else if (tag.TagNo == 3) { ver = 3; break; } } } foreach (object obj in origInfo.Crls) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tag = (Asn1TaggedObject)obj; if (tag.TagNo == 1) { ver = 3; break; } } } return ver; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// The header section of the page. /// </summary> public class WPHeader_Core : TypeCore, IWebPageElement { public WPHeader_Core() { this._TypeId = 290; this._Id = "WPHeader"; this._Schema_Org_Url = "http://schema.org/WPHeader"; string label = ""; GetLabel(out label, "WPHeader", typeof(WPHeader_Core)); this._Label = label; this._Ancestors = new int[]{266,78,294}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{294}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
/*************************************************************************** Copyright (c) Microsoft Corporation 2012-2015. This code is licensed using the Microsoft Public License (Ms-PL). The text of the license can be found here: http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx Published at http://OpenXmlDeveloper.org Resource Center and Documentation: http://openxmldeveloper.org/wiki/w/wiki/powertools-for-open-xml.aspx Developer: Eric White Blog: http://www.ericwhite.com Twitter: @EricWhiteDev Email: eric@ericwhite.com ***************************************************************************/ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using OpenXmlPowerTools; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using SSW = OpenXmlPowerTools; namespace OpenXmlPowerTools.Commands { [Cmdlet(VerbsData.Out, "Xlsx", SupportsShouldProcess = true)] [OutputType("OpenXmlPowerToolsDocument")] public class OutXlsxCmdlet : PowerToolsCreateCmdlet { #region Parameters private const string DefaultSheetName = "Sheet1"; private PSObject[] pipeObjects; private Collection<PSObject> processedObjects = new Collection<PSObject>(); string fileName; bool openWithExcel; string sheetName; string tableName; /// <summary> /// FileName parameter /// </summary> [Parameter( Position = 0, Mandatory = true, ValueFromPipeline = false, HelpMessage = "Path of file in which to store results") ] public string FileName { get { return fileName; } set { fileName = Path.Combine(SessionState.Path.CurrentLocation.Path, value); } } /// <summary> /// InputObject parameter /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = true, HelpMessage = "Objects passed by pipe to be included in spreadsheet") ] public PSObject[] InputObject { get { return pipeObjects; } set { pipeObjects = value; } } /// <summary> /// SheetName parameter /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false, HelpMessage = "Specify the sheet name") ] public string SheetName { get { return sheetName; } set { sheetName = value; } } /// <summary> /// TableName parameter /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false, HelpMessage = "Specify the table name") ] public string TableName { get { return tableName; } set { tableName = value; } } /// <summary> /// OpenWithExcel parameter /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false, HelpMessage = "Open with Excel") ] public SwitchParameter OpenWithExcel { get { return openWithExcel; } set { openWithExcel = value; } } #endregion # region Fields List<Type> typeCollection = new List<Type>(); List<SSW.CellDfn> columnHeadings = new List<SSW.CellDfn>(); Types type = Types.none; string[][] result; #endregion #region Cmdlet Overrides protected override void ProcessRecord() { if (pipeObjects != null) { foreach (PSObject pipeObject in pipeObjects) processedObjects.Add(pipeObject); } } protected override void EndProcessing() { ValidateSheetName(fileName, sheetName); if (tableName != null) { ValidateTableName(tableName); } FileInfo fi = new FileInfo(fileName); if (fi.Extension.ToLower() != ".xlsx") fi = new FileInfo(Path.Combine(fi.DirectoryName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length) + ".xlsx")); fileName = fi.FullName; if (!File.Exists(fileName) || ShouldProcess(fileName, "Out-Xlsx")) { if (!File.Exists(fileName)) { using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument()) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { if (processedObjects.Count > 0) { GetPSObjectType(); CreateColumns(); FillValues(); } GenerateNewSpreadSheetDocument(document, sheetName, tableName); } } } else OverWriteSpreadSheetDocument(fileName); if (openWithExcel) { FileInfo file = new FileInfo(fileName); if (file.Exists) System.Diagnostics.Process.Start(fileName); } } } private void GenerateNewSpreadSheetDocument(SpreadsheetDocument document, string sheetName, string tableName) { List<SSW.RowDfn> rowCollection = GetRowCollection(result); // Create new work sheet to te document List<SSW.WorksheetDfn> workSheetCollection = new List<SSW.WorksheetDfn>(); SSW.WorksheetDfn workSheet = new SSW.WorksheetDfn(); if (string.IsNullOrEmpty(sheetName)) workSheet.Name = DefaultSheetName; else workSheet.Name = this.sheetName; workSheet.TableName = tableName; workSheet.ColumnHeadings = columnHeadings; workSheet.Rows = rowCollection; workSheetCollection.Add(workSheet); // Create work book SSW.WorkbookDfn workBook = new SSW.WorkbookDfn(); workBook.Worksheets = workSheetCollection; // Create Excel File SSW.SpreadsheetWriter.Write(fileName, workBook); } private void OverWriteSpreadSheetDocument(string fileName) { using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(fileName, true)) { if (processedObjects.Count > 0) { GetPSObjectType(); CreateColumns(); FillValues(); List<SSW.RowDfn> rowCollection = GetRowCollection(result); //Add work sheet to existing document SSW.WorksheetDfn workSheet = new SSW.WorksheetDfn(); workSheet.Name = this.sheetName; workSheet.TableName = tableName; workSheet.ColumnHeadings = columnHeadings; workSheet.Rows = rowCollection; SSW.SpreadsheetWriter.AddWorksheet(sDoc, workSheet); } } } private List<SSW.RowDfn> GetRowCollection(string[][] result) { List<SSW.RowDfn> rowCollection = new List<SSW.RowDfn>(); for (int i = 0; i < result.Count(); i++) { string[] dataRow = result[i]; SSW.RowDfn row = new SSW.RowDfn(); List<SSW.CellDfn> cellCollection = new List<SSW.CellDfn>(); for (int j = 0; j < dataRow.Count(); j++) { SSW.CellDfn dataCell = new SSW.CellDfn(); dataCell.Value = dataRow[j]; dataCell.HorizontalCellAlignment = SSW.HorizontalCellAlignment.Left; dataCell.CellDataType = CellDataType.String; cellCollection.Add(dataCell); } row.Cells = cellCollection; rowCollection.Add(row); } return rowCollection; } private void CreateColumns() { switch (type) { case Types.ReferenceType: { foreach (PSObject obj in processedObjects) { if (!typeCollection.Contains(obj.BaseObject.GetType())) { typeCollection.Add(obj.BaseObject.GetType()); CreateColumnHeadings(obj); } } break; } case Types.ScalarType: { SSW.CellDfn columnHeading = new SSW.CellDfn(); columnHeading.Value = processedObjects.First().BaseObject.GetType().FullName; columnHeadings.Add(columnHeading); break; } case Types.ScalarTypes: { SSW.CellDfn indexColumnHeading = new SSW.CellDfn(); indexColumnHeading.Value = "Index"; columnHeadings.Add(indexColumnHeading); SSW.CellDfn valueColumnHeading = new SSW.CellDfn(); valueColumnHeading.Value = "Value"; columnHeadings.Add(valueColumnHeading); SSW.CellDfn typeColumnHeading = new SSW.CellDfn(); typeColumnHeading.Value = "Type"; columnHeadings.Add(typeColumnHeading); break; } default: { break; } } } private void CreateColumnHeadings(PSObject obj) { foreach (PSPropertyInfo property in obj.Properties) { if (columnHeadings.Count == 0) { SSW.CellDfn columnHeading = new SSW.CellDfn(); columnHeading.Value = property.Name; columnHeadings.Add(columnHeading); } else if (!columnHeadings.Exists(e => e.Value.Equals(property.Name))) { SSW.CellDfn columnHeading = new SSW.CellDfn(); columnHeading.Value = property.Name; columnHeadings.Add(columnHeading); } } } private void FillValues() { result = new string[processedObjects.Count][]; switch (type) { case Types.ReferenceType: { for (int i = 0; i < processedObjects.Count; i++) { PSObject obj = processedObjects[i]; result[i] = new string[columnHeadings.Count]; for (int j = 0; j < columnHeadings.Count; j++) { string propertyName = Convert.ToString(columnHeadings[j].Value); try { if (obj.Properties[propertyName] != null) { string value = Convert.ToString(obj.Properties[propertyName].Value); if (!string.IsNullOrEmpty(value)) { result[i][j] = value; } } } catch (GetValueInvocationException e) { WriteDebug(string.Format(CultureInfo.InvariantCulture, "Exception ({0}) ", e.Message)); } } } break; } case Types.ScalarType: { for (int i = 0; i < processedObjects.Count; i++) { result[i] = new string[1]; result[i][0] = Convert.ToString(processedObjects[i]); } break; } case Types.ScalarTypes: { for (int i = 0; i < processedObjects.Count; i++) { result[i] = new string[3]; result[i][0] = Convert.ToString(i); result[i][1] = Convert.ToString(processedObjects[i]); result[i][2] = processedObjects[i].BaseObject.GetType().FullName; } break; } default: { break; } } } private void GetPSObjectType() { if (!DefaultScalarTypes.IsTypeInList(processedObjects[0].TypeNames)) { type = Types.ReferenceType; return; } string firstType = processedObjects[0].BaseObject.GetType().FullName; for (int i = 1; i < processedObjects.Count && processedObjects.Count > 1; i++) { if (firstType != processedObjects[i].BaseObject.GetType().FullName) { type = Types.ScalarTypes; return; } } type = Types.ScalarType; } private void ValidateSheetName(string fileName, string sheetName) { if (File.Exists(fileName)) { if (string.IsNullOrEmpty(sheetName)) throw new Exception("Sheet name is missing. Specify a sheet name."); } } public static void ValidateTableName(string tableName) { if (tableName.Contains(' ')) throw new Exception("Table name contains a space."); if (tableName.Length > 255) throw new Exception("Table name length exceeds 255."); char first = tableName[0]; char last = tableName[tableName.Length - 1]; if (!(char.IsLetter(first) || first == '_')) throw new Exception("Table name does not start with a letter or underscore."); if (char.IsLetter(last) || last == '_') return; if (char.IsDigit(last)) { char[] anyOf = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; int firstDigit = tableName.IndexOfAny(anyOf); if (firstDigit <= 3) throw new Exception("Invalid table name."); } } #endregion } public enum Types { ReferenceType, ScalarType, ScalarTypes, none } }
// 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 Internal.IL.Stubs; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace Internal.IL { /// <summary> /// Represents a delegate and provides access to compiler-generated methods on the delegate type. /// </summary> public class DelegateInfo { private TypeDesc _delegateType; private MethodSignature _signature; private MethodDesc _getThunkMethod; private DelegateThunkCollection _thunks; /// <summary> /// Gets the Delegate.GetThunk override implementation for this delegate type. /// </summary> public MethodDesc GetThunkMethod { get { if (_getThunkMethod == null) { Interlocked.CompareExchange(ref _getThunkMethod, new DelegateGetThunkMethodOverride(this), null); } return _getThunkMethod; } } /// <summary> /// Gets the collection of delegate invocation thunks. /// </summary> public DelegateThunkCollection Thunks { get { if (_thunks == null) { Interlocked.CompareExchange(ref _thunks, new DelegateThunkCollection(this), null); } return _thunks; } } /// <summary> /// Gets the signature of the delegate type. /// </summary> public MethodSignature Signature { get { if (_signature == null) { _signature = _delegateType.GetKnownMethod("Invoke", null).Signature; } return _signature; } } /// <summary> /// Gets the type of the delegate. /// </summary> public TypeDesc Type { get { return _delegateType; } } public DelegateInfo(TypeDesc delegateType) { Debug.Assert(delegateType.IsDelegate); Debug.Assert(delegateType.IsTypeDefinition); _delegateType = delegateType; } } /// <summary> /// Represents a collection of delegate invocation thunks. /// </summary> public class DelegateThunkCollection { private MethodDesc _openStaticThunk; private MethodDesc _multicastThunk; private MethodDesc _closedStaticThunk; private MethodDesc _invokeThunk; private MethodDesc _closedInstanceOverGeneric; private MethodDesc _reversePInvokeThunk; private MethodDesc _invokeObjectArrayThunk; private MethodDesc _openInstanceThunk; internal DelegateThunkCollection(DelegateInfo owningDelegate) { _openStaticThunk = new DelegateInvokeOpenStaticThunk(owningDelegate); _multicastThunk = new DelegateInvokeMulticastThunk(owningDelegate); _closedStaticThunk = new DelegateInvokeClosedStaticThunk(owningDelegate); _invokeThunk = new DelegateDynamicInvokeThunk(owningDelegate); _closedInstanceOverGeneric = new DelegateInvokeInstanceClosedOverGenericMethodThunk(owningDelegate); _invokeObjectArrayThunk = new DelegateInvokeObjectArrayThunk(owningDelegate); if (!owningDelegate.Type.HasInstantiation && IsNativeCallingConventionCompatible(owningDelegate.Signature)) _reversePInvokeThunk = new DelegateReversePInvokeThunk(owningDelegate); MethodSignature delegateSignature = owningDelegate.Signature; if (delegateSignature.Length > 0) { TypeDesc firstParam = delegateSignature[0]; bool generateOpenInstanceMethod; switch (firstParam.Category) { case TypeFlags.Pointer: case TypeFlags.FunctionPointer: generateOpenInstanceMethod = false; break; case TypeFlags.ByRef: firstParam = ((ByRefType)firstParam).ParameterType; generateOpenInstanceMethod = firstParam.IsSignatureVariable || firstParam.IsValueType; break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.SignatureTypeVariable: generateOpenInstanceMethod = true; break; default: Debug.Assert(firstParam.IsDefType); generateOpenInstanceMethod = !firstParam.IsValueType; break; } if (generateOpenInstanceMethod) { _openInstanceThunk = new DelegateInvokeOpenInstanceThunk(owningDelegate); } } } #region Temporary interop logic // TODO: interop should provide a way to query this private static bool IsNativeCallingConventionCompatible(MethodSignature delegateSignature) { if (!IsNativeCallingConventionCompatible(delegateSignature.ReturnType)) return false; else { for (int i = 0; i < delegateSignature.Length; i++) { if (!IsNativeCallingConventionCompatible(delegateSignature[i])) { return false; } } } return true; } private static bool IsNativeCallingConventionCompatible(TypeDesc type) { if (type.IsPointer || type.IsByRef) return IsNativeCallingConventionCompatible(((ParameterizedType)type).ParameterType); if (!type.IsValueType) return false; if (type.IsPrimitive) { if (type.IsWellKnownType(WellKnownType.Boolean)) return false; return true; } foreach (FieldDesc field in type.GetFields()) { if (!field.IsStatic && !IsNativeCallingConventionCompatible(field.FieldType)) return false; } return true; } #endregion public MethodDesc this[DelegateThunkKind kind] { get { switch (kind) { case DelegateThunkKind.OpenStaticThunk: return _openStaticThunk; case DelegateThunkKind.MulticastThunk: return _multicastThunk; case DelegateThunkKind.ClosedStaticThunk: return _closedStaticThunk; case DelegateThunkKind.DelegateInvokeThunk: return _invokeThunk; case DelegateThunkKind.ClosedInstanceThunkOverGenericMethod: return _closedInstanceOverGeneric; case DelegateThunkKind.ReversePinvokeThunk: return _reversePInvokeThunk; case DelegateThunkKind.ObjectArrayThunk: return _invokeObjectArrayThunk; case DelegateThunkKind.OpenInstanceThunk: return _openInstanceThunk; default: return null; } } } } // TODO: Unify with the consts used in Delegate.cs within the class library. public enum DelegateThunkKind { MulticastThunk = 0, ClosedStaticThunk = 1, OpenStaticThunk = 2, ClosedInstanceThunkOverGenericMethod = 3, // This may not exist DelegateInvokeThunk = 4, OpenInstanceThunk = 5, // This may not exist ReversePinvokeThunk = 6, // This may not exist ObjectArrayThunk = 7, // This may not exist } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Collections; using System.IO; using System.Text; using System.Xml; namespace System.Data { public class DataViewManager : MarshalByValueComponent, IBindingList, System.ComponentModel.ITypedList { private DataViewSettingCollection _dataViewSettingsCollection; private DataSet _dataSet; private readonly DataViewManagerListItemTypeDescriptor _item; private readonly bool _locked; internal int _nViews = 0; private static readonly NotSupportedException s_notSupported = new NotSupportedException(); public DataViewManager() : this(null, false) { } public DataViewManager(DataSet dataSet) : this(dataSet, false) { } internal DataViewManager(DataSet dataSet, bool locked) { GC.SuppressFinalize(this); _dataSet = dataSet; if (_dataSet != null) { _dataSet.Tables.CollectionChanged += new CollectionChangeEventHandler(TableCollectionChanged); _dataSet.Relations.CollectionChanged += new CollectionChangeEventHandler(RelationCollectionChanged); } _locked = locked; _item = new DataViewManagerListItemTypeDescriptor(this); _dataViewSettingsCollection = new DataViewSettingCollection(this); } [DefaultValue(null)] public DataSet DataSet { get { return _dataSet; } set { if (value == null) { throw ExceptionBuilder.SetFailed("DataSet to null"); } if (_locked) { throw ExceptionBuilder.SetDataSetFailed(); } if (_dataSet != null) { if (_nViews > 0) { throw ExceptionBuilder.CanNotSetDataSet(); } _dataSet.Tables.CollectionChanged -= new CollectionChangeEventHandler(TableCollectionChanged); _dataSet.Relations.CollectionChanged -= new CollectionChangeEventHandler(RelationCollectionChanged); } _dataSet = value; _dataSet.Tables.CollectionChanged += new CollectionChangeEventHandler(TableCollectionChanged); _dataSet.Relations.CollectionChanged += new CollectionChangeEventHandler(RelationCollectionChanged); _dataViewSettingsCollection = new DataViewSettingCollection(this); _item.Reset(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DataViewSettingCollection DataViewSettings => _dataViewSettingsCollection; public string DataViewSettingCollectionString { get { if (_dataSet == null) { return string.Empty; } var builder = new StringBuilder(); builder.Append("<DataViewSettingCollectionString>"); foreach (DataTable dt in _dataSet.Tables) { DataViewSetting ds = _dataViewSettingsCollection[dt]; builder.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "<{0} Sort=\"{1}\" RowFilter=\"{2}\" RowStateFilter=\"{3}\"/>", dt.EncodedTableName, ds.Sort, ds.RowFilter, ds.RowStateFilter); } builder.Append("</DataViewSettingCollectionString>"); return builder.ToString(); } set { if (string.IsNullOrEmpty(value)) { return; } var r = new XmlTextReader(new StringReader(value)); r.WhitespaceHandling = WhitespaceHandling.None; r.Read(); if (r.Name != "DataViewSettingCollectionString") { throw ExceptionBuilder.SetFailed(nameof(DataViewSettingCollectionString)); } while (r.Read()) { if (r.NodeType != XmlNodeType.Element) { continue; } string table = XmlConvert.DecodeName(r.LocalName); if (r.MoveToAttribute("Sort")) { _dataViewSettingsCollection[table].Sort = r.Value; } if (r.MoveToAttribute("RowFilter")) { _dataViewSettingsCollection[table].RowFilter = r.Value; } if (r.MoveToAttribute("RowStateFilter")) { _dataViewSettingsCollection[table].RowStateFilter = (DataViewRowState)Enum.Parse(typeof(DataViewRowState), r.Value); } } } } IEnumerator IEnumerable.GetEnumerator() { var items = new DataViewManagerListItemTypeDescriptor[1]; ((ICollection)this).CopyTo(items, 0); return items.GetEnumerator(); } int ICollection.Count => 1; object ICollection.SyncRoot => this; bool ICollection.IsSynchronized => false; bool IList.IsReadOnly => true; bool IList.IsFixedSize => true; void ICollection.CopyTo(Array array, int index) { array.SetValue(new DataViewManagerListItemTypeDescriptor(this), index); } object IList.this[int index] { get { return _item; } set { throw ExceptionBuilder.CannotModifyCollection(); } } int IList.Add(object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.Clear() { throw ExceptionBuilder.CannotModifyCollection(); } bool IList.Contains(object value) => (value == _item); int IList.IndexOf(object value) => (value == _item) ? 1 : -1; void IList.Insert(int index, object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.Remove(object value) { throw ExceptionBuilder.CannotModifyCollection(); } void IList.RemoveAt(int index) { throw ExceptionBuilder.CannotModifyCollection(); } // ------------- IBindingList: --------------------------- bool IBindingList.AllowNew => false; object IBindingList.AddNew() { throw s_notSupported; } bool IBindingList.AllowEdit => false; bool IBindingList.AllowRemove => false; bool IBindingList.SupportsChangeNotification => true; bool IBindingList.SupportsSearching => false; bool IBindingList.SupportsSorting => false; bool IBindingList.IsSorted { get { throw s_notSupported; } } PropertyDescriptor IBindingList.SortProperty { get { throw s_notSupported; } } ListSortDirection IBindingList.SortDirection { get { throw s_notSupported; } } public event System.ComponentModel.ListChangedEventHandler ListChanged; void IBindingList.AddIndex(PropertyDescriptor property) { // no operation } void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) { throw s_notSupported; } int IBindingList.Find(PropertyDescriptor property, object key) { throw s_notSupported; } void IBindingList.RemoveIndex(PropertyDescriptor property) { // no operation } void IBindingList.RemoveSort() { throw s_notSupported; } // SDUB: GetListName and GetItemProperties almost the same in DataView and DataViewManager string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { DataSet dataSet = DataSet; if (dataSet == null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } if (listAccessors == null || listAccessors.Length == 0) { return dataSet.DataSetName; } else { DataTable table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.TableName; } } return string.Empty; } PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { DataSet dataSet = DataSet; if (dataSet == null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } if (listAccessors == null || listAccessors.Length == 0) { return ((ICustomTypeDescriptor)(new DataViewManagerListItemTypeDescriptor(this))).GetProperties(); } else { DataTable table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.GetPropertyDescriptorCollection(null); } } return new PropertyDescriptorCollection(null); } public DataView CreateDataView(DataTable table) { if (_dataSet == null) { throw ExceptionBuilder.CanNotUseDataViewManager(); } DataView dataView = new DataView(table); dataView.SetDataViewManager(this); return dataView; } protected virtual void OnListChanged(ListChangedEventArgs e) { try { ListChanged?.Invoke(this, e); } catch (Exception f) when (Common.ADP.IsCatchableExceptionType(f)) { ExceptionBuilder.TraceExceptionWithoutRethrow(f); // ignore the exception } } protected virtual void TableCollectionChanged(object sender, CollectionChangeEventArgs e) { PropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : /*default*/ null ); } protected virtual void RelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataRelationPropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : /*default*/ null ); } } }
//------------------------------------------------------------------------------ // <copyright file="cookiecontainer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.Threading; using System.Globalization; using System.Net.NetworkInformation; using System.Text; internal struct HeaderVariantInfo { string m_name; CookieVariant m_variant; internal HeaderVariantInfo(string name, CookieVariant variant) { m_name = name; m_variant = variant; } internal string Name { get { return m_name; } } internal CookieVariant Variant { get { return m_variant; } } } // // CookieContainer // // Manage cookies for a user (implicit). Based on RFC 2965 // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Serializable] public class CookieContainer { public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public const int DefaultCookieLengthLimit = 4096; static readonly HeaderVariantInfo [] HeaderInfo = { new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109), new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965) }; // fields Hashtable m_domainTable = new Hashtable(); int m_maxCookieSize = DefaultCookieLengthLimit; int m_maxCookies = DefaultCookieLimit; int m_maxCookiesPerDomain = DefaultPerDomainCookieLimit; int m_count = 0; string m_fqdnMyDomain = String.Empty; // constructors /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public CookieContainer() { string domain = IPGlobalProperties.InternalGetIPGlobalProperties().DomainName; if (domain != null && domain.Length > 1) { m_fqdnMyDomain = '.' + domain; } //Otherwise it will remain string.Empty } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public CookieContainer(int capacity) : this(){ if (capacity <= 0) { throw new ArgumentException(SR.GetString(SR.net_toosmall), "Capacity"); } m_maxCookies = capacity; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity) { if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity)) { throw new ArgumentOutOfRangeException("perDomainCapacity", SR.GetString(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity)); } m_maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { throw new ArgumentException(SR.GetString(SR.net_toosmall), "MaxCookieSize"); } m_maxCookieSize = maxCookieSize; } // properties /// <devdoc> /// <para>Note that after shrinking the capacity Count can become greater than Capacity.</para> /// </devdoc> public int Capacity { get { return m_maxCookies; } set { if (value <= 0 || (value < m_maxCookiesPerDomain && m_maxCookiesPerDomain != Int32.MaxValue)) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_cookie_capacity_range, "Capacity", 0, m_maxCookiesPerDomain)); } if (value < m_maxCookies) { m_maxCookies = value; AgeCookies(null); } m_maxCookies = value; } } /// <devdoc> /// <para>returns the total number of cookies in the container.</para> /// </devdoc> public int Count { get { return m_count; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int MaxCookieSize { get { return m_maxCookieSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("value"); } m_maxCookieSize = value; } } /// <devdoc> /// <para>After shrinking domain capacity each domain will less hold than new domain capacity</para> /// </devdoc> public int PerDomainCapacity { get { return m_maxCookiesPerDomain; } set { if (value <= 0 || (value > m_maxCookies && value != Int32.MaxValue)) { throw new ArgumentOutOfRangeException("value"); } if (value < m_maxCookiesPerDomain) { m_maxCookiesPerDomain = value; AgeCookies(null); } m_maxCookiesPerDomain = value; } } // methods /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> //This method will construct faked URI, Domain property is required for param. public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException("cookie"); } if (cookie.Domain.Length == 0) { throw new ArgumentException(SR.GetString(SR.net_emptystringcall), "cookie.Domain"); } Uri uri; StringBuilder uriSb = new StringBuilder(); // We cannot add an invalid cookie into the container. // Trying to prepare Uri for the cookie verification uriSb.Append(cookie.Secure ? Uri.UriSchemeHttps : Uri.UriSchemeHttp).Append(Uri.SchemeDelimiter); // If the original cookie has an explicitly set domain, copy it over // to the new cookie if (!cookie.DomainImplicit) { if (cookie.Domain[0] == '.') { uriSb.Append("0"); // Uri cctor should eat this, faked host. } } uriSb.Append(cookie.Domain); // Either keep Port as implici or set it according to original cookie if (cookie.PortList != null) { uriSb.Append(":").Append(cookie.PortList[0]); } // Path must be present, set to root by default uriSb.Append(cookie.Path); if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri)) throw new CookieException(SR.GetString(SR.net_cookie_attribute, "Domain", cookie.Domain)); // We don't know cookie verification status -> re-create cookie and verify it Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); Add(new_cookie, true); } private void AddRemoveDomain(string key, PathList value) { // Hashtable support multiple readers and one writer // Synchronize writers lock (m_domainTable.SyncRoot) { if (value == null) { m_domainTable.Remove(key); } else { m_domainTable[key] = value; } } } // This method is called *only* when cookie verification is done, // so unlike with public Add(Cookie cookie) the cookie is in sane condition internal void Add(Cookie cookie, bool throwOnError) { PathList pathList; if (cookie.Value.Length > m_maxCookieSize) { if (throwOnError) { throw new CookieException(SR.GetString(SR.net_cookie_size, cookie.ToString(), m_maxCookieSize)); } return; } try { lock (m_domainTable.SyncRoot) { pathList = (PathList)m_domainTable[cookie.DomainKey]; if (pathList == null) { pathList = new PathList(); AddRemoveDomain(cookie.DomainKey, pathList); } } int domain_count = pathList.GetCookiesCount(); CookieCollection cookies; lock (pathList.SyncRoot) { cookies = (CookieCollection)pathList[cookie.Path]; if (cookies == null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; } } if(cookie.Expired) { //Explicit removal command (Max-Age == 0) lock (cookies) { int idx = cookies.IndexOf(cookie); if (idx != -1) { cookies.RemoveAt(idx); --m_count; } } } else { //This is about real cookie adding, check Capacity first if (domain_count >= m_maxCookiesPerDomain && !AgeCookies(cookie.DomainKey)) { return; //cannot age -> reject new cookie } else if (this.m_count >= m_maxCookies && !AgeCookies(null)) { return; //cannot age -> reject new cookie } //about to change the collection lock (cookies) { m_count += cookies.InternalAdd(cookie, true); } } } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (throwOnError) { throw new CookieException(SR.GetString(SR.net_container_add_cookie), e); } } } // // This function, once called, must delete at least one cookie // If there are expired cookies in given scope they are cleaned up // If nothing found the least used Collection will be found and removed // from the container. // // Also note that expired cookies are also removed during request preparation // (this.GetCookies method) // // Param. 'domain' == null means to age in the whole container // private bool AgeCookies(string domain) { // border case => shrinked to zero if(m_maxCookies == 0 || m_maxCookiesPerDomain == 0) { m_domainTable = new Hashtable(); m_count = 0; return false; } int removed = 0; DateTime oldUsed = DateTime.MaxValue; DateTime tempUsed; CookieCollection lruCc = null; string lruDomain = null; string tempDomain = null; PathList pathList; int domain_count = 0; int itemp = 0; float remainingFraction = 1.0F; // the container was shrinked, might need additional cleanup for each domain if (m_count > m_maxCookies) { // Means the fraction of the container to be left // Each domain will be cut accordingly remainingFraction = (float)m_maxCookies/(float)m_count; } lock (m_domainTable.SyncRoot) { foreach (DictionaryEntry entry in m_domainTable) { if (domain == null) { tempDomain = (string) entry.Key; pathList = (PathList) entry.Value; //aliasing to trick foreach } else { tempDomain = domain; pathList = (PathList) m_domainTable[domain]; } domain_count = 0; // cookies in the domain lock (pathList.SyncRoot) { foreach (CookieCollection cc in pathList.Values) { itemp = ExpireCollection(cc); removed += itemp; m_count -= itemp; //update this container count; domain_count += cc.Count; // we also find the least used cookie collection in ENTIRE container // we count the collection as LRU only if it holds 1+ elements if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed) { lruDomain = tempDomain; lruCc = cc; oldUsed = tempUsed; } } } // Check if we have reduced to the limit of the domain by expiration only int min_count = Math.Min((int)(domain_count*remainingFraction), Math.Min(m_maxCookiesPerDomain, m_maxCookies)-1); if (domain_count > min_count) { //That case require sorting all domain collections by timestamp Array cookies; Array stamps; lock (pathList.SyncRoot) { cookies = Array.CreateInstance(typeof(CookieCollection), pathList.Count); stamps = Array.CreateInstance(typeof(DateTime), pathList.Count); foreach (CookieCollection cc in pathList.Values) { stamps.SetValue(cc.TimeStamp(CookieCollection.Stamp.Check), itemp); cookies.SetValue(cc, itemp); ++itemp; } } Array.Sort(stamps, cookies); itemp = 0; for (int i = 0; i < cookies.Length; ++i) { CookieCollection cc = (CookieCollection)cookies.GetValue(i); lock (cc) { while (domain_count > min_count && cc.Count > 0) { cc.RemoveAt(0); --domain_count; --m_count; ++removed; } } if (domain_count <= min_count ) { break; } } if (domain_count > min_count && domain != null) { //cannot complete aging of explicit domain (no cookie adding allowed) return false; } } } } // we have completed aging of specific domain if (domain != null) { return true; } // The rest is for entire container aging // We must get at least one free slot. //Don't need to appy LRU if we already cleaned something if (removed != 0) { return true; } if (oldUsed == DateTime.MaxValue) { //Something strange. Either capacity is 0 or all collections are locked with cc.Used return false; } // Remove oldest cookies from the least used collection lock (lruCc) { while (m_count >= m_maxCookies && lruCc.Count > 0) { lruCc.RemoveAt(0); --m_count; } } return true; } //return number of cookies removed from the collection private int ExpireCollection(CookieCollection cc) { lock (cc) { int oldCount = cc.Count; int idx = oldCount-1; //Cannot use enumerator as we are going to alter collection while (idx >= 0) { Cookie cookie = cc[idx]; if (cookie.Expired) { cc.RemoveAt(idx); } --idx; } return oldCount - cc.Count; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // < public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException("cookies"); } foreach (Cookie c in cookies) { Add(c); } } // // This will try (if needed) get the full domain name of the host given the Uri // NEVER call this function from internal methods with 'fqdnRemote' == NULL // Since this method counts security issue for DNS and hence will slow // the performance // internal bool IsLocalDomain(string host) { int dot = host.IndexOf('.'); if (dot == -1) { // No choice but to treat it as a host on the local domain // This also covers 'localhost' and 'loopback' return true; } // quick test for usual case - loopback addresses for IPv4 and IPv6 if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1")) { return true; } // test domain membership if (string.Compare(m_fqdnMyDomain, 0, host, dot, m_fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase ) == 0) { return true; } // test for "127.###.###.###" without using regex string[] ipParts = host.Split('.'); if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < 4; i++) { switch (ipParts[i].Length) { case 3: if (ipParts[i][2] < '0' || ipParts[i][2] > '9') { break; } goto case 2; case 2: if (ipParts[i][1] < '0' || ipParts[i][1] > '9') { break; } goto case 1; case 1: if (ipParts[i][0] < '0' || ipParts[i][0] > '9') { break; } continue; } break; } if (i == 4) { return true; } } return false; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Add(Uri uri, Cookie cookie) { if (uri == null) { throw new ArgumentNullException("uri"); } if(cookie == null) { throw new ArgumentNullException("cookie"); } Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); Add(new_cookie, true); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Add(Uri uri, CookieCollection cookies) { if (uri == null) { throw new ArgumentNullException("uri"); } if(cookies == null) { throw new ArgumentNullException("cookies"); } bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { Cookie new_cookie = c.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, m_fqdnMyDomain, true, true); Add(new_cookie, true); } } internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow); CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else for (int i = 0; i < HeaderInfo.Length; ++i) { if ((String.Compare(headerName, HeaderInfo[i].Name, StringComparison.OrdinalIgnoreCase ) == 0)) { variant = HeaderInfo[i].Variant; } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + ValidationHelper.ToString(cookie)); if (cookie == null) { break; } //Parser marks invalid cookies this way if (ValidationHelper.IsBlankString(cookie.Name)) { if(isThrow) { throw new CookieException(SR.GetString(SR.net_cookie_format)); } //Otherwise, ignore (reject) cookie continue; } // this will set the default values from the response URI // AND will check for cookie validity if(!cookie.VerifySetDefaults(variant, uri, isLocalDomain, m_fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if(isThrow) { throw new CookieException(SR.GetString(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return cookies; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public CookieCollection GetCookies(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } return InternalGetCookies(uri); } internal CookieCollection InternalGetCookies(Uri uri) { bool isSecure = (uri.Scheme == Uri.UriSchemeHttps); int port = uri.Port; CookieCollection cookies = new CookieCollection(); ArrayList nameKeys = new ArrayList(); int firstCompatibleVersion0SpecKey = 0; string fqdnRemote = uri.Host; int dot = fqdnRemote.IndexOf('.'); if (dot == -1) { // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. nameKeys.Add(fqdnRemote); // add a preceding dot (null host) nameKeys.Add("." + fqdnRemote); // grab long name from the local domain if (m_fqdnMyDomain != null && m_fqdnMyDomain.Length != 0) { nameKeys.Add(fqdnRemote + m_fqdnMyDomain); // grab the local domain itself nameKeys.Add(m_fqdnMyDomain); firstCompatibleVersion0SpecKey = 3; } else { firstCompatibleVersion0SpecKey = 1; } } else { // grab the host itself nameKeys.Add(fqdnRemote); // add a preceding dot (null host) nameKeys.Add("." + fqdnRemote); // grab the host domain nameKeys.Add(fqdnRemote.Substring(dot)); firstCompatibleVersion0SpecKey = 2; // The following block is only for compatibility with Version0 spec. // Still, we'll add only Plain-Variant cookies if found under below keys if (fqdnRemote.Length > 2) { // We ignore the '.' at the end on the name int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length-2); //AND keys with <2 dots inside. if (last > 0) { last = fqdnRemote.LastIndexOf('.', last-1); } if (last != -1) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot+1)) != -1) { nameKeys.Add(fqdnRemote.Substring(dot)); } } } } foreach (string key in nameKeys) { bool found = false; bool defaultAdded = false; PathList pathList; lock (m_domainTable.SyncRoot) { pathList = (PathList)m_domainTable[key]; } --firstCompatibleVersion0SpecKey; if (pathList == null) { continue; } lock (pathList.SyncRoot) { foreach (DictionaryEntry entry in pathList) { string path = (string)entry.Key; if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) { found = true; CookieCollection cc = (CookieCollection)entry.Value; cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(cookies, cc, port, isSecure, (firstCompatibleVersion0SpecKey<0)); if (path == "/") { defaultAdded = true; } } else if (found) { break; } } } if (!defaultAdded) { CookieCollection cc = (CookieCollection)pathList["/"]; if (cc != null) { cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(cookies, cc, port, isSecure, (firstCompatibleVersion0SpecKey<0)); } } // Remove unused domain // (This is the only place that does domain removal) if(pathList.Count == 0) { AddRemoveDomain(key, null); } } return cookies; } private void MergeUpdateCollections(CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly) { // we may change it lock (source) { //cannot use foreach as we going update 'source' for (int idx = 0 ; idx < source.Count; ++idx) { bool to_add = false; Cookie cookie = source[idx]; if (cookie.Expired) { //If expired, remove from container and don't add to the destination source.RemoveAt(idx); --m_count; --idx; } else { //Add only if port does match to this request URI //or was not present in the original response if(isPlainOnly && cookie.Variant != CookieVariant.Plain) { ;//don;t add } else if(cookie.PortList != null) { foreach (int p in cookie.PortList) { if(p == port) { to_add = true; break; } } } else { //it was implicit Port, always OK to add to_add = true; } //refuse adding secure cookie into 'unsecure' destination if (cookie.Secure && !isSecure) { to_add = false; } if (to_add) { // In 'source' are already orederd. // If two same cookies come from dif 'source' then they // will follow (not replace) each other. destination.InternalAdd(cookie, false); } } } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string GetCookieHeader(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } string dummy; return GetCookieHeader(uri, out dummy); } internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection cookies = InternalGetCookies(uri); string cookieString = String.Empty; string delimiter = String.Empty; foreach (Cookie cookie in cookies) { cookieString += delimiter + cookie.ToString(); delimiter = "; "; } optCookie2 = cookies.IsOtherVersionSeen ? (Cookie.SpecialAttributeLiteral + Cookie.VersionAttributeName + Cookie.EqualsLiteral + Cookie.MaxSupportedVersion.ToString(NumberFormatInfo.InvariantInfo)) : String.Empty; return cookieString; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> //< public void SetCookies(Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException("uri"); } if(cookieHeader == null) { throw new ArgumentNullException("cookieHeader"); } CookieCutter(uri, null, cookieHeader, true); //will throw on error } } [Serializable] internal class PathList { SortedList m_list = (SortedList.Synchronized(new SortedList(PathListComparer.StaticInstance))); public PathList() { } public int Count { get { return m_list.Count; } } public int GetCookiesCount() { int count = 0; lock (SyncRoot) { foreach (CookieCollection cc in m_list.Values) { count += cc.Count; } } return count; } public ICollection Values { get { return m_list.Values; } } public object this[string s] { get { return m_list[s]; } set { lock (SyncRoot) { m_list[s] = value; } } } public IEnumerator GetEnumerator() { return m_list.GetEnumerator(); } public object SyncRoot { get { return m_list.SyncRoot; } } [Serializable] class PathListComparer : IComparer { internal static readonly PathListComparer StaticInstance = new PathListComparer(); int IComparer.Compare(object ol, object or) { string pathLeft = CookieParser.CheckQuoted((string)ol); string pathRight = CookieParser.CheckQuoted((string)or); int ll = pathLeft.Length; int lr = pathRight.Length; int length = Math.Min(ll, lr); for (int i = 0; i < length; ++i) { if (pathLeft[i] != pathRight[i]) { return pathLeft[i] - pathRight[i]; } } return lr - ll; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Finance.Server.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests.heaps { using CollectionOfInt = IntervalHeap<int>; [TestFixture] public class GenericTesters { [Test] public void TestEvents() { Fun<CollectionOfInt> factory = delegate() { return new CollectionOfInt(TenEqualityComparer.Default); }; new C5UnitTests.Templates.Events.PriorityQueueTester<CollectionOfInt>().Test(factory); } [Test] public void Extensible() { C5UnitTests.Templates.Extensible.Clone.Tester<CollectionOfInt>(); C5UnitTests.Templates.Extensible.Serialization.Tester<CollectionOfInt>(); } } [TestFixture] public class Events { IPriorityQueue<int> queue; ArrayList<KeyValuePair<Acts, int>> events; [SetUp] public void Init() { queue = new IntervalHeap<int>(); events = new ArrayList<KeyValuePair<Acts, int>>(); } [TearDown] public void Dispose() { queue = null; events = null; } [Test] public void Listenable() { Assert.AreEqual(EventTypeEnum.Basic, queue.ListenableEvents); } enum Acts { Add, Remove, Changed } [Test] public void Direct() { CollectionChangedHandler<int> cch; ItemsAddedHandler<int> iah; ItemsRemovedHandler<int> irh; Assert.AreEqual(EventTypeEnum.None, queue.ActiveEvents); queue.CollectionChanged += (cch = new CollectionChangedHandler<int>(queue_CollectionChanged)); Assert.AreEqual(EventTypeEnum.Changed, queue.ActiveEvents); queue.ItemsAdded += (iah = new ItemsAddedHandler<int>(queue_ItemAdded)); Assert.AreEqual(EventTypeEnum.Changed | EventTypeEnum.Added, queue.ActiveEvents); queue.ItemsRemoved += (irh = new ItemsRemovedHandler<int>(queue_ItemRemoved)); Assert.AreEqual(EventTypeEnum.Changed | EventTypeEnum.Added | EventTypeEnum.Removed, queue.ActiveEvents); queue.Add(34); queue.Add(56); queue.AddAll<int>(new int[] { }); queue.Add(34); queue.Add(12); queue.DeleteMax(); queue.DeleteMin(); queue.AddAll<int>(new int[] { 4, 5, 6, 2 }); Assert.AreEqual(17, events.Count); int[] vals = { 34, 0, 56, 0, 34, 0, 12, 0, 56, 0, 12, 0, 4, 5, 6, 2, 0 }; Acts[] acts = { Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Add, Acts.Add, Acts.Add, Acts.Add, Acts.Changed }; for (int i = 0; i < vals.Length; i++) { //Console.WriteLine("{0}", events[cell]); Assert.AreEqual(acts[i], events[i].Key, "Action " + i); Assert.AreEqual(vals[i], events[i].Value, "Value " + i); } queue.CollectionChanged -= cch; Assert.AreEqual(EventTypeEnum.Added | EventTypeEnum.Removed, queue.ActiveEvents); queue.ItemsAdded -= iah; Assert.AreEqual(EventTypeEnum.Removed, queue.ActiveEvents); queue.ItemsRemoved -= irh; Assert.AreEqual(EventTypeEnum.None, queue.ActiveEvents); } [Test] public void Guarded() { ICollectionValue<int> guarded = new GuardedCollectionValue<int>(queue); guarded.CollectionChanged += new CollectionChangedHandler<int>(queue_CollectionChanged); guarded.ItemsAdded += new ItemsAddedHandler<int>(queue_ItemAdded); guarded.ItemsRemoved += new ItemsRemovedHandler<int>(queue_ItemRemoved); queue.Add(34); queue.Add(56); queue.Add(34); queue.Add(12); queue.DeleteMax(); queue.DeleteMin(); queue.AddAll<int>(new int[] { 4, 5, 6, 2 }); Assert.AreEqual(17, events.Count); int[] vals = { 34, 0, 56, 0, 34, 0, 12, 0, 56, 0, 12, 0, 4, 5, 6, 2, 0 }; Acts[] acts = { Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Add, Acts.Add, Acts.Add, Acts.Add, Acts.Changed }; for (int i = 0; i < vals.Length; i++) { //Console.WriteLine("{0}", events[cell]); Assert.AreEqual(vals[i], events[i].Value); Assert.AreEqual(acts[i], events[i].Key); } } void queue_CollectionChanged(object sender) { events.Add(new KeyValuePair<Acts, int>(Acts.Changed, 0)); } void queue_ItemAdded(object sender, ItemCountEventArgs<int> e) { events.Add(new KeyValuePair<Acts, int>(Acts.Add, e.Item)); } void queue_ItemRemoved(object sender, ItemCountEventArgs<int> e) { events.Add(new KeyValuePair<Acts, int>(Acts.Remove, e.Item)); } } [TestFixture] public class Formatting { IntervalHeap<int> coll; IFormatProvider rad16; [SetUp] public void Init() { coll = new IntervalHeap<int>(); rad16 = new RadixFormatProvider(16); } [TearDown] public void Dispose() { coll = null; rad16 = null; } [Test] public void Format() { Assert.AreEqual("{ }", coll.ToString()); coll.AddAll<int>(new int[] { -4, 28, 129, 65530 }); Assert.AreEqual("{ -4, 65530, 28, 129 }", coll.ToString()); Assert.AreEqual("{ -4, FFFA, 1C, 81 }", coll.ToString(null, rad16)); Assert.AreEqual("{ -4, 65530, ... }", coll.ToString("L14", null)); Assert.AreEqual("{ -4, FFFA, ... }", coll.ToString("L14", rad16)); } } [TestFixture] public class IntervalHeapTests { IPriorityQueue<int> queue; [SetUp] public void Init() { queue = new IntervalHeap<int>(); } [TearDown] public void Dispose() { queue = null; } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor1() { new IntervalHeap<int>(null); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor2() { new IntervalHeap<int>(5, null); } [Test] public void Handles() { IPriorityQueueHandle<int>[] handles = new IPriorityQueueHandle<int>[10]; queue.Add(ref handles[0], 7); Assert.IsTrue(queue.Check()); queue.Add(ref handles[1], 72); Assert.IsTrue(queue.Check()); queue.Add(ref handles[2], 27); Assert.IsTrue(queue.Check()); queue.Add(ref handles[3], 17); Assert.IsTrue(queue.Check()); queue.Add(ref handles[4], 70); Assert.IsTrue(queue.Check()); queue.Add(ref handles[5], 1); Assert.IsTrue(queue.Check()); queue.Add(ref handles[6], 2); Assert.IsTrue(queue.Check()); queue.Add(ref handles[7], 7); Assert.IsTrue(queue.Check()); queue.Add(ref handles[8], 8); Assert.IsTrue(queue.Check()); queue.Add(ref handles[9], 9); Assert.IsTrue(queue.Check()); queue.Delete(handles[2]); Assert.IsTrue(queue.Check()); queue.Delete(handles[0]); Assert.IsTrue(queue.Check()); queue.Delete(handles[8]); Assert.IsTrue(queue.Check()); queue.Delete(handles[4]); Assert.IsTrue(queue.Check()); queue.Delete(handles[6]); Assert.IsTrue(queue.Check()); Assert.AreEqual(5, queue.Count); } [Test] public void Replace() { IPriorityQueueHandle<int> handle = null; queue.Add(6); queue.Add(10); queue.Add(ref handle, 7); queue.Add(21); Assert.AreEqual(7, queue.Replace(handle, 12)); Assert.AreEqual(21, queue.FindMax()); Assert.AreEqual(12, queue.Replace(handle, 34)); Assert.AreEqual(34, queue.FindMax()); Assert.IsTrue(queue.Check()); //replace max Assert.AreEqual(34, queue.Replace(handle, 60)); Assert.AreEqual(60, queue.FindMax()); Assert.AreEqual(60, queue.Replace(handle, queue[handle] + 80)); Assert.AreEqual(140, queue.FindMax()); Assert.IsTrue(queue.Check()); } [Test] public void Replace2() { IPriorityQueueHandle<int> handle = null; queue.Add(6); queue.Add(10); queue.Add(ref handle, 7); //Replace last item in queue with something large Assert.AreEqual(7, queue.Replace(handle, 12)); Assert.IsTrue(queue.Check()); } /// <summary> /// Bug by Viet Yen Nguyen <v.y.nguyen@alumnus.utwente.nl> /// </summary> [Test] public void Replace3() { IPriorityQueueHandle<int> handle = null; queue.Add(ref handle, 10); Assert.AreEqual(10, queue.Replace(handle, 12)); Assert.IsTrue(queue.Check()); } [Test] public void ReuseHandle() { IPriorityQueueHandle<int> handle = null; queue.Add(ref handle, 7); queue.Delete(handle); queue.Add(ref handle, 8); } [Test] [ExpectedException(typeof(InvalidPriorityQueueHandleException))] public void ErrorAddValidHandle() { IPriorityQueueHandle<int> handle = null; queue.Add(ref handle, 7); queue.Add(ref handle, 8); } [Test] [ExpectedException(typeof(InvalidPriorityQueueHandleException))] public void ErrorDeleteInvalidHandle() { IPriorityQueueHandle<int> handle = null; queue.Add(ref handle, 7); queue.Delete(handle); queue.Delete(handle); } [Test] [ExpectedException(typeof(InvalidPriorityQueueHandleException))] public void ErrorReplaceInvalidHandle() { IPriorityQueueHandle<int> handle = null; queue.Add(ref handle, 7); queue.Delete(handle); queue.Replace(handle, 13); } [Test] public void Simple() { Assert.IsTrue(queue.AllowsDuplicates); Assert.AreEqual(0, queue.Count); queue.Add(8); queue.Add(18); queue.Add(8); queue.Add(3); Assert.AreEqual(4, queue.Count); Assert.AreEqual(18, queue.DeleteMax()); Assert.AreEqual(3, queue.Count); Assert.AreEqual(3, queue.DeleteMin()); Assert.AreEqual(2, queue.Count); Assert.AreEqual(8, queue.FindMax()); Assert.AreEqual(8, queue.DeleteMax()); Assert.AreEqual(8, queue.FindMax()); queue.Add(15); Assert.AreEqual(15, queue.FindMax()); Assert.AreEqual(8, queue.FindMin()); Assert.IsTrue(queue.Comparer.Compare(2, 3) < 0); Assert.IsTrue(queue.Comparer.Compare(4, 3) > 0); Assert.IsTrue(queue.Comparer.Compare(3, 3) == 0); } [Test] public void Enumerate() { int[] a = new int[4]; int siz = 0; foreach (int i in queue) siz++; Assert.AreEqual(0, siz); queue.Add(8); queue.Add(18); queue.Add(8); queue.Add(3); foreach (int i in queue) a[siz++] = i; Assert.AreEqual(4, siz); Array.Sort(a, 0, siz); Assert.AreEqual(3, a[0]); Assert.AreEqual(8, a[1]); Assert.AreEqual(8, a[2]); Assert.AreEqual(18, a[3]); siz = 0; Assert.AreEqual(18, queue.DeleteMax()); foreach (int i in queue) a[siz++] = i; Assert.AreEqual(3, siz); Array.Sort(a, 0, siz); Assert.AreEqual(3, a[0]); Assert.AreEqual(8, a[1]); Assert.AreEqual(8, a[2]); siz = 0; Assert.AreEqual(8, queue.DeleteMax()); foreach (int i in queue) a[siz++] = i; Assert.AreEqual(2, siz); Array.Sort(a, 0, siz); Assert.AreEqual(3, a[0]); Assert.AreEqual(8, a[1]); siz = 0; Assert.AreEqual(8, queue.DeleteMax()); foreach (int i in queue) a[siz++] = i; Assert.AreEqual(1, siz); Assert.AreEqual(3, a[0]); } [Test] public void Random() { int length = 1000; int[] a = new int[length]; Random ran = new Random(6754); for (int i = 0; i < length; i++) queue.Add(a[i] = ran.Next()); Assert.IsTrue(queue.Check()); Array.Sort(a); for (int i = 0; i < length / 2; i++) { Assert.AreEqual(a[length - i - 1], queue.DeleteMax()); Assert.IsTrue(queue.Check()); Assert.AreEqual(a[i], queue.DeleteMin()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.IsEmpty); } [Test] public void RandomWithHandles() { int length = 1000; int[] a = new int[length]; Random ran = new Random(6754); for (int i = 0; i < length; i++) { IPriorityQueueHandle<int> h = null; queue.Add(ref h, a[i] = ran.Next()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.Check()); Array.Sort(a); for (int i = 0; i < length / 2; i++) { Assert.AreEqual(a[length - i - 1], queue.DeleteMax()); Assert.IsTrue(queue.Check()); Assert.AreEqual(a[i], queue.DeleteMin()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.IsEmpty); } [Test] public void RandomWithDeleteHandles() { Random ran = new Random(6754); int length = 1000; int[] a = new int[length]; ArrayList<int> shuffle = new ArrayList<int>(length); IPriorityQueueHandle<int>[] h = new IPriorityQueueHandle<int>[length]; for (int i = 0; i < length; i++) { shuffle.Add(i); queue.Add(ref h[i], a[i] = ran.Next()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.Check()); shuffle.Shuffle(ran); for (int i = 0; i < length; i++) { int j = shuffle[i]; Assert.AreEqual(a[j], queue.Delete(h[j])); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.IsEmpty); } [Test] public void RandomIndexing() { Random ran = new Random(6754); int length = 1000; int[] a = new int[length]; int[] b = new int[length]; ArrayList<int> shuffle = new ArrayList<int>(length); IPriorityQueueHandle<int>[] h = new IPriorityQueueHandle<int>[length]; for (int i = 0; i < length; i++) { shuffle.Add(i); queue.Add(ref h[i], a[i] = ran.Next()); b[i] = ran.Next(); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.Check()); shuffle.Shuffle(ran); for (int i = 0; i < length; i++) { int j = shuffle[i]; Assert.AreEqual(a[j], queue[h[j]]); queue[h[j]] = b[j]; Assert.AreEqual(b[j], queue[h[j]]); Assert.IsTrue(queue.Check()); } } [Test] public void RandomDuplicates() { int length = 1000; int s; int[] a = new int[length]; Random ran = new Random(6754); for (int i = 0; i < length; i++) queue.Add(a[i] = ran.Next(3, 13)); Assert.IsTrue(queue.Check()); Array.Sort(a); for (int i = 0; i < length / 2; i++) { Assert.AreEqual(a[i], queue.DeleteMin()); Assert.IsTrue(queue.Check()); Assert.AreEqual(a[length - i - 1], s = queue.DeleteMax()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.IsEmpty); } [Test] public void AddAll() { int length = 1000; int[] a = new int[length]; Random ran = new Random(6754); LinkedList<int> lst = new LinkedList<int>(); for (int i = 0; i < length; i++) lst.Add(a[i] = ran.Next()); queue.AddAll(lst); Assert.IsTrue(queue.Check()); Array.Sort(a); for (int i = 0; i < length / 2; i++) { Assert.AreEqual(a[length - i - 1], queue.DeleteMax()); Assert.IsTrue(queue.Check()); Assert.AreEqual(a[i], queue.DeleteMin()); Assert.IsTrue(queue.Check()); } Assert.IsTrue(queue.IsEmpty); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Telegram.Bot.Args; using Telegram.Bot.Exceptions; using Telegram.Bot.Requests; using Telegram.Bot.Requests.Abstractions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InlineQueryResults; using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.Payments; using Telegram.Bot.Types.ReplyMarkups; using File = Telegram.Bot.Types.File; namespace Telegram.Bot { /// <summary> /// A client to use the Telegram Bot API /// </summary> public class TelegramBotClient : ITelegramBotClient { /// <inheritdoc/> public int BotId { get; } private static readonly Update[] EmptyUpdates = { }; private const string BaseUrl = "https://api.telegram.org/bot"; private const string BaseFileUrl = "https://api.telegram.org/file/bot"; private readonly string _baseRequestUrl; private readonly string _token; private readonly HttpClient _httpClient; #region Config Properties /// <summary> /// Timeout for requests /// </summary> public TimeSpan Timeout { get => _httpClient.Timeout; set => _httpClient.Timeout = value; } /// <summary> /// Indicates if receiving updates /// </summary> public bool IsReceiving { get; set; } private CancellationTokenSource _receivingCancellationTokenSource; /// <summary> /// The current message offset /// </summary> public int MessageOffset { get; set; } #endregion Config Properties #region Events /// <summary> /// Occurs before sending a request to API /// </summary> public event EventHandler<ApiRequestEventArgs> MakingApiRequest; /// <summary> /// Occurs after receiving the response to an API request /// </summary> public event EventHandler<ApiResponseEventArgs> ApiResponseReceived; /// <summary> /// Raises the <see cref="OnUpdate" />, <see cref="OnMessage"/>, <see cref="OnInlineQuery"/>, <see cref="OnInlineResultChosen"/> and <see cref="OnCallbackQuery"/> events. /// </summary> /// <param name="e">The <see cref="UpdateEventArgs"/> instance containing the event data.</param> protected virtual void OnUpdateReceived(UpdateEventArgs e) { OnUpdate?.Invoke(this, e); switch (e.Update.Type) { case UpdateType.Message: OnMessage?.Invoke(this, e); break; case UpdateType.InlineQuery: OnInlineQuery?.Invoke(this, e); break; case UpdateType.ChosenInlineResult: OnInlineResultChosen?.Invoke(this, e); break; case UpdateType.CallbackQuery: OnCallbackQuery?.Invoke(this, e); break; case UpdateType.EditedMessage: OnMessageEdited?.Invoke(this, e); break; } } /// <summary> /// Occurs when an <see cref="Update"/> is received. /// </summary> public event EventHandler<UpdateEventArgs> OnUpdate; /// <summary> /// Occurs when a <see cref="Message"/> is received. /// </summary> public event EventHandler<MessageEventArgs> OnMessage; /// <summary> /// Occurs when <see cref="Message"/> was edited. /// </summary> public event EventHandler<MessageEventArgs> OnMessageEdited; /// <summary> /// Occurs when an <see cref="InlineQuery"/> is received. /// </summary> public event EventHandler<InlineQueryEventArgs> OnInlineQuery; /// <summary> /// Occurs when a <see cref="ChosenInlineResult"/> is received. /// </summary> public event EventHandler<ChosenInlineResultEventArgs> OnInlineResultChosen; /// <summary> /// Occurs when an <see cref="CallbackQuery"/> is received /// </summary> public event EventHandler<CallbackQueryEventArgs> OnCallbackQuery; /// <summary> /// Occurs when an error occurs during the background update pooling. /// </summary> public event EventHandler<ReceiveErrorEventArgs> OnReceiveError; /// <summary> /// Occurs when an error occurs during the background update pooling. /// </summary> public event EventHandler<ReceiveGeneralErrorEventArgs> OnReceiveGeneralError; #endregion /// <summary> /// Create a new <see cref="TelegramBotClient"/> instance. /// </summary> /// <param name="token">API token</param> /// <param name="httpClient">A custom <see cref="HttpClient"/></param> /// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception> public TelegramBotClient(string token, HttpClient httpClient = null) { _token = token ?? throw new ArgumentNullException(nameof(token)); string[] parts = _token.Split(':'); if (parts.Length > 1 && int.TryParse(parts[0], out int id)) { BotId = id; } else { throw new ArgumentException( "Invalid format. A valid token looks like \"1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy\".", nameof(token) ); } _baseRequestUrl = $"{BaseUrl}{_token}/"; _httpClient = httpClient ?? new HttpClient(); } /// <summary> /// Create a new <see cref="TelegramBotClient"/> instance behind a proxy. /// </summary> /// <param name="token">API token</param> /// <param name="webProxy">Use this <see cref="IWebProxy"/> to connect to the API</param> /// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception> public TelegramBotClient(string token, IWebProxy webProxy) { _token = token ?? throw new ArgumentNullException(nameof(token)); string[] parts = _token.Split(':'); if (int.TryParse(parts[0], out int id)) { BotId = id; } else { throw new ArgumentException( "Invalid format. A valid token looks like \"1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy\".", nameof(token) ); } _baseRequestUrl = $"{BaseUrl}{_token}/"; var httpClientHander = new HttpClientHandler { Proxy = webProxy, UseProxy = true }; _httpClient = new HttpClient(httpClientHander); } #region Helpers /// <inheritdoc /> public async Task<TResponse> MakeRequestAsync<TResponse>( IRequest<TResponse> request, CancellationToken cancellationToken = default) { string url = _baseRequestUrl + request.MethodName; var httpRequest = new HttpRequestMessage(request.Method, url) { Content = request.ToHttpContent() }; var reqDataArgs = new ApiRequestEventArgs { MethodName = request.MethodName, HttpContent = httpRequest.Content, }; MakingApiRequest?.Invoke(this, reqDataArgs); HttpResponseMessage httpResponse; try { httpResponse = await _httpClient.SendAsync(httpRequest, cancellationToken) .ConfigureAwait(false); } catch (TaskCanceledException e) { if (cancellationToken.IsCancellationRequested) throw; throw new ApiRequestException("Request timed out", 408, e); } // required since user might be able to set new status code using following event arg var actualResponseStatusCode = httpResponse.StatusCode; string responseJson = await httpResponse.Content.ReadAsStringAsync() .ConfigureAwait(false); ApiResponseReceived?.Invoke(this, new ApiResponseEventArgs { ResponseMessage = httpResponse, ApiRequestEventArgs = reqDataArgs }); switch (actualResponseStatusCode) { case HttpStatusCode.OK: break; case HttpStatusCode.Unauthorized: case HttpStatusCode.BadRequest when !string.IsNullOrWhiteSpace(responseJson): case HttpStatusCode.Forbidden when !string.IsNullOrWhiteSpace(responseJson): case HttpStatusCode.Conflict when !string.IsNullOrWhiteSpace(responseJson): // Do NOT throw here, an ApiRequestException will be thrown next break; default: httpResponse.EnsureSuccessStatusCode(); break; } var apiResponse = JsonConvert.DeserializeObject<ApiResponse<TResponse>>(responseJson) ?? new ApiResponse<TResponse> // ToDo is required? unit test { Ok = false, Description = "No response received" }; if (!apiResponse.Ok) throw ApiExceptionParser.Parse(apiResponse); return apiResponse.Result; } /// <summary> /// Test the API token /// </summary> /// <returns><c>true</c> if token is valid</returns> public async Task<bool> TestApiAsync(CancellationToken cancellationToken = default) { try { await GetMeAsync(cancellationToken).ConfigureAwait(false); return true; } catch (ApiRequestException e) when (e.ErrorCode == 401) { return false; } } /// <summary> /// Start update receiving /// </summary> /// <param name="allowedUpdates">List the types of updates you want your bot to receive.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="ApiRequestException"> Thrown if token is invalid</exception> public void StartReceiving(UpdateType[] allowedUpdates = null, CancellationToken cancellationToken = default) { _receivingCancellationTokenSource = new CancellationTokenSource(); cancellationToken.Register(() => _receivingCancellationTokenSource.Cancel()); ReceiveAsync(allowedUpdates, _receivingCancellationTokenSource.Token); } #pragma warning disable AsyncFixer03 // Avoid fire & forget async void methods private async void ReceiveAsync( UpdateType[] allowedUpdates, CancellationToken cancellationToken = default) { IsReceiving = true; while (!cancellationToken.IsCancellationRequested) { var timeout = Convert.ToInt32(Timeout.TotalSeconds); var updates = EmptyUpdates; try { updates = await GetUpdatesAsync( MessageOffset, timeout: timeout, allowedUpdates: allowedUpdates, cancellationToken: cancellationToken ).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (ApiRequestException apiException) { OnReceiveError?.Invoke(this, apiException); } catch (Exception generalException) { OnReceiveGeneralError?.Invoke(this, generalException); } try { foreach (var update in updates) { OnUpdateReceived(new UpdateEventArgs(update)); MessageOffset = update.Id + 1; } } catch { IsReceiving = false; throw; } } IsReceiving = false; } #pragma warning restore AsyncFixer03 // Avoid fire & forget async void methods /// <summary> /// Stop update receiving /// </summary> public void StopReceiving() { try { _receivingCancellationTokenSource.Cancel(); } catch (WebException) { } catch (TaskCanceledException) { } } #endregion Helpers #region Getting updates /// <inheritdoc /> public Task<Update[]> GetUpdatesAsync( int offset = default, int limit = default, int timeout = default, IEnumerable<UpdateType> allowedUpdates = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetUpdatesRequest { Offset = offset, Limit = limit, Timeout = timeout, AllowedUpdates = allowedUpdates }, cancellationToken); /// <inheritdoc /> public Task SetWebhookAsync( string url, InputFileStream certificate = default, int maxConnections = default, IEnumerable<UpdateType> allowedUpdates = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetWebhookRequest(url, certificate) { MaxConnections = maxConnections, AllowedUpdates = allowedUpdates }, cancellationToken); /// <inheritdoc /> public Task DeleteWebhookAsync(CancellationToken cancellationToken = default) => MakeRequestAsync(new DeleteWebhookRequest(), cancellationToken); /// <inheritdoc /> public Task<WebhookInfo> GetWebhookInfoAsync(CancellationToken cancellationToken = default) => MakeRequestAsync(new GetWebhookInfoRequest(), cancellationToken); #endregion Getting updates #region Available methods /// <inheritdoc /> public Task<User> GetMeAsync(CancellationToken cancellationToken = default) => MakeRequestAsync(new GetMeRequest(), cancellationToken); /// <inheritdoc /> public Task<Message> SendTextMessageAsync( ChatId chatId, string text, ParseMode parseMode = default, bool disableWebPagePreview = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendMessageRequest(chatId, text) { ParseMode = parseMode, DisableWebPagePreview = disableWebPagePreview, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> ForwardMessageAsync( ChatId chatId, ChatId fromChatId, int messageId, bool disableNotification = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new ForwardMessageRequest(chatId, fromChatId, messageId) { DisableNotification = disableNotification }, cancellationToken); /// <inheritdoc /> public Task<Message> SendPhotoAsync( ChatId chatId, InputOnlineFile photo, string caption = default, ParseMode parseMode = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendPhotoRequest(chatId, photo) { Caption = caption, ParseMode = parseMode, ReplyToMessageId = replyToMessageId, DisableNotification = disableNotification, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendAudioAsync( ChatId chatId, InputOnlineFile audio, string caption = default, ParseMode parseMode = default, int duration = default, string performer = default, string title = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, InputMedia thumb = default ) => MakeRequestAsync(new SendAudioRequest(chatId, audio) { Caption = caption, ParseMode = parseMode, Duration = duration, Performer = performer, Title = title, Thumb = thumb, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendDocumentAsync( ChatId chatId, InputOnlineFile document, string caption = default, ParseMode parseMode = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, InputMedia thumb = default ) => MakeRequestAsync(new SendDocumentRequest(chatId, document) { Caption = caption, Thumb = thumb, ParseMode = parseMode, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendStickerAsync( ChatId chatId, InputOnlineFile sticker, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendStickerRequest(chatId, sticker) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendVideoAsync( ChatId chatId, InputOnlineFile video, int duration = default, int width = default, int height = default, string caption = default, ParseMode parseMode = default, bool supportsStreaming = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, InputMedia thumb = default ) => MakeRequestAsync(new SendVideoRequest(chatId, video) { Duration = duration, Width = width, Height = height, Thumb = thumb, Caption = caption, ParseMode = parseMode, SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendAnimationAsync( ChatId chatId, InputOnlineFile animation, int duration = default, int width = default, int height = default, InputMedia thumb = default, string caption = default, ParseMode parseMode = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendAnimationRequest(chatId, animation) { Duration = duration, Width = width, Height = height, Thumb = thumb, Caption = caption, ParseMode = parseMode, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup, }, cancellationToken); /// <inheritdoc /> public Task<Message> SendVoiceAsync( ChatId chatId, InputOnlineFile voice, string caption = default, ParseMode parseMode = default, int duration = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendVoiceRequest(chatId, voice) { Caption = caption, ParseMode = parseMode, Duration = duration, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendVideoNoteAsync( ChatId chatId, InputTelegramFile videoNote, int duration = default, int length = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, InputMedia thumb = default ) => MakeRequestAsync(new SendVideoNoteRequest(chatId, videoNote) { Duration = duration, Length = length, Thumb = thumb, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> [Obsolete("Use the other overload of this method instead. Only photo and video input types are allowed.")] public Task<Message[]> SendMediaGroupAsync( ChatId chatId, IEnumerable<InputMediaBase> media, bool disableNotification = default, int replyToMessageId = default, CancellationToken cancellationToken = default ) { var inputMedia = media .Select(m => m as IAlbumInputMedia) .Where(m => m != null) .ToArray(); return MakeRequestAsync(new SendMediaGroupRequest(chatId, inputMedia) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, }, cancellationToken); } /// <inheritdoc /> public Task<Message[]> SendMediaGroupAsync( IEnumerable<IAlbumInputMedia> inputMedia, ChatId chatId, bool disableNotification = default, int replyToMessageId = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendMediaGroupRequest(chatId, inputMedia) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, }, cancellationToken); /// <inheritdoc /> public Task<Message> SendLocationAsync( ChatId chatId, float latitude, float longitude, int livePeriod = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendLocationRequest(chatId, latitude, longitude) { LivePeriod = livePeriod, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendVenueAsync( ChatId chatId, float latitude, float longitude, string title, string address, string foursquareId = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, string foursquareType = default ) => MakeRequestAsync(new SendVenueRequest(chatId, latitude, longitude, title, address) { FoursquareId = foursquareId, FoursquareType = foursquareType, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendContactAsync( ChatId chatId, string phoneNumber, string firstName, string lastName = default, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, string vCard = default ) => MakeRequestAsync(new SendContactRequest(chatId, phoneNumber, firstName) { LastName = lastName, Vcard = vCard, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SendPollAsync( ChatId chatId, string question, IEnumerable<string> options, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, bool? isAnonymous = default, PollType? type = default, bool? allowsMultipleAnswers = default, int? correctOptionId = default, bool? isClosed = default, string explanation = default, ParseMode explanationParseMode = default, int? openPeriod = default, DateTime? closeDate = default ) => MakeRequestAsync(new SendPollRequest(chatId, question, options) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup, IsAnonymous = isAnonymous, Type = type, AllowsMultipleAnswers = allowsMultipleAnswers, CorrectOptionId = correctOptionId, IsClosed = isClosed, OpenPeriod = openPeriod, CloseDate = closeDate, Explanation = explanation, ExplanationParseMode = explanationParseMode }, cancellationToken); /// <inheritdoc /> public Task<Message> SendDiceAsync( ChatId chatId, bool disableNotification = default, int replyToMessageId = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default, Emoji? emoji = default) => MakeRequestAsync( new SendDiceRequest(chatId) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup, Emoji = emoji }, cancellationToken ); /// <inheritdoc /> public Task SendChatActionAsync( ChatId chatId, ChatAction chatAction, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendChatActionRequest(chatId, chatAction), cancellationToken); /// <inheritdoc /> public Task<UserProfilePhotos> GetUserProfilePhotosAsync( int userId, int offset = default, int limit = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetUserProfilePhotosRequest(userId) { Offset = offset, Limit = limit }, cancellationToken); /// <inheritdoc /> public Task<File> GetFileAsync( string fileId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetFileRequest(fileId), cancellationToken); /// <inheritdoc /> [Obsolete("This method will be removed in next major release. Use its overload instead.")] public async Task<Stream> DownloadFileAsync( string filePath, CancellationToken cancellationToken = default ) { var stream = new MemoryStream(); await DownloadFileAsync(filePath, stream, cancellationToken) .ConfigureAwait(false); return stream; } /// <inheritdoc /> public async Task DownloadFileAsync( string filePath, Stream destination, CancellationToken cancellationToken = default ) { if (string.IsNullOrWhiteSpace(filePath) || filePath.Length < 2) { throw new ArgumentException("Invalid file path", nameof(filePath)); } if (destination == null) { throw new ArgumentNullException(nameof(destination)); } var fileUri = new Uri($"{BaseFileUrl}{_token}/{filePath}"); var response = await _httpClient .GetAsync(fileUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); using (response) { await response.Content.CopyToAsync(destination) .ConfigureAwait(false); } } /// <inheritdoc /> public async Task<File> GetInfoAndDownloadFileAsync( string fileId, Stream destination, CancellationToken cancellationToken = default ) { var file = await GetFileAsync(fileId, cancellationToken) .ConfigureAwait(false); await DownloadFileAsync(file.FilePath, destination, cancellationToken) .ConfigureAwait(false); return file; } /// <inheritdoc /> public Task KickChatMemberAsync( ChatId chatId, int userId, DateTime untilDate = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new KickChatMemberRequest(chatId, userId) { UntilDate = untilDate }, cancellationToken); /// <inheritdoc /> public Task LeaveChatAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new LeaveChatRequest(chatId), cancellationToken); /// <inheritdoc /> public Task UnbanChatMemberAsync( ChatId chatId, int userId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new UnbanChatMemberRequest(chatId, userId), cancellationToken); /// <inheritdoc /> public Task<Chat> GetChatAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetChatRequest(chatId), cancellationToken); /// <inheritdoc /> public Task<ChatMember[]> GetChatAdministratorsAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetChatAdministratorsRequest(chatId), cancellationToken); /// <inheritdoc /> public Task<int> GetChatMembersCountAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetChatMembersCountRequest(chatId), cancellationToken); /// <inheritdoc /> public Task<ChatMember> GetChatMemberAsync( ChatId chatId, int userId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetChatMemberRequest(chatId, userId), cancellationToken); /// <inheritdoc /> public Task AnswerCallbackQueryAsync( string callbackQueryId, string text = default, bool showAlert = default, string url = default, int cacheTime = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerCallbackQueryRequest(callbackQueryId) { Text = text, ShowAlert = showAlert, Url = url, CacheTime = cacheTime }, cancellationToken); /// <inheritdoc /> public Task RestrictChatMemberAsync( ChatId chatId, int userId, ChatPermissions permissions, DateTime untilDate = default, CancellationToken cancellationToken = default ) => MakeRequestAsync( new RestrictChatMemberRequest(chatId, userId, permissions) { UntilDate = untilDate }, cancellationToken); /// <inheritdoc /> public Task PromoteChatMemberAsync( ChatId chatId, int userId, bool? canChangeInfo = default, bool? canPostMessages = default, bool? canEditMessages = default, bool? canDeleteMessages = default, bool? canInviteUsers = default, bool? canRestrictMembers = default, bool? canPinMessages = default, bool? canPromoteMembers = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new PromoteChatMemberRequest(chatId, userId) { CanChangeInfo = canChangeInfo, CanPostMessages = canPostMessages, CanEditMessages = canEditMessages, CanDeleteMessages = canDeleteMessages, CanInviteUsers = canInviteUsers, CanRestrictMembers = canRestrictMembers, CanPinMessages = canPinMessages, CanPromoteMembers = canPromoteMembers }, cancellationToken); /// <inheritdoc /> public Task SetChatAdministratorCustomTitleAsync( ChatId chatId, int userId, string customTitle, CancellationToken cancellationToken = default) => MakeRequestAsync( new SetChatAdministratorCustomTitleRequest(chatId, userId, customTitle), cancellationToken); /// <inheritdoc /> public Task SetChatPermissionsAsync( ChatId chatId, ChatPermissions permissions, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetChatPermissionsRequest(chatId, permissions), cancellationToken); /// <inheritdoc /> public Task<BotCommand[]> GetMyCommandsAsync(CancellationToken cancellationToken = default) => MakeRequestAsync(new GetMyCommandsRequest(), cancellationToken); /// <inheritdoc /> public Task SetMyCommandsAsync( IEnumerable<BotCommand> commands, CancellationToken cancellationToken = default) => MakeRequestAsync(new SetMyCommandsRequest(commands), cancellationToken); /// <inheritdoc /> public Task<Message> StopMessageLiveLocationAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new StopMessageLiveLocationRequest(chatId, messageId) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task StopMessageLiveLocationAsync( string inlineMessageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new StopInlineMessageLiveLocationRequest(inlineMessageId) { ReplyMarkup = replyMarkup }, cancellationToken); #endregion Available methods #region Updating messages /// <inheritdoc /> public Task<Message> EditMessageTextAsync( ChatId chatId, int messageId, string text, ParseMode parseMode = default, bool disableWebPagePreview = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditMessageTextRequest(chatId, messageId, text) { ParseMode = parseMode, DisableWebPagePreview = disableWebPagePreview, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task EditMessageTextAsync( string inlineMessageId, string text, ParseMode parseMode = default, bool disableWebPagePreview = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditInlineMessageTextRequest(inlineMessageId, text) { DisableWebPagePreview = disableWebPagePreview, ReplyMarkup = replyMarkup, ParseMode = parseMode }, cancellationToken); /// <inheritdoc /> public Task<Message> EditMessageCaptionAsync( ChatId chatId, int messageId, string caption, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default, ParseMode parseMode = default ) => MakeRequestAsync(new EditMessageCaptionRequest(chatId, messageId, caption) { ParseMode = parseMode, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task EditMessageCaptionAsync( string inlineMessageId, string caption, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default, ParseMode parseMode = default ) => MakeRequestAsync(new EditInlineMessageCaptionRequest(inlineMessageId, caption) { ParseMode = parseMode, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> EditMessageMediaAsync( ChatId chatId, int messageId, InputMediaBase media, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditMessageMediaRequest(chatId, messageId, media) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task EditMessageMediaAsync( string inlineMessageId, InputMediaBase media, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditInlineMessageMediaRequest(inlineMessageId, media) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> EditMessageReplyMarkupAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync( new EditMessageReplyMarkupRequest(chatId, messageId, replyMarkup), cancellationToken); /// <inheritdoc /> public Task EditMessageReplyMarkupAsync( string inlineMessageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync( new EditInlineMessageReplyMarkupRequest(inlineMessageId, replyMarkup), cancellationToken); /// <inheritdoc /> public Task<Message> EditMessageLiveLocationAsync( ChatId chatId, int messageId, float latitude, float longitude, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditMessageLiveLocationRequest(chatId, messageId, latitude, longitude) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task EditMessageLiveLocationAsync( string inlineMessageId, float latitude, float longitude, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new EditInlineMessageLiveLocationRequest(inlineMessageId, latitude, longitude) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Poll> StopPollAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new StopPollRequest(chatId, messageId) { ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task DeleteMessageAsync( ChatId chatId, int messageId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new DeleteMessageRequest(chatId, messageId), cancellationToken); #endregion Updating messages #region Inline mode /// <inheritdoc /> public Task AnswerInlineQueryAsync( string inlineQueryId, IEnumerable<InlineQueryResultBase> results, int? cacheTime = default, bool isPersonal = default, string nextOffset = default, string switchPmText = default, string switchPmParameter = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerInlineQueryRequest(inlineQueryId, results) { CacheTime = cacheTime, IsPersonal = isPersonal, NextOffset = nextOffset, SwitchPmText = switchPmText, SwitchPmParameter = switchPmParameter }, cancellationToken); # endregion Inline mode #region Payments /// <inheritdoc /> public Task<Message> SendInvoiceAsync( int chatId, string title, string description, string payload, string providerToken, string startParameter, string currency, IEnumerable<LabeledPrice> prices, string providerData = default, string photoUrl = default, int photoSize = default, int photoWidth = default, int photoHeight = default, bool needName = default, bool needPhoneNumber = default, bool needEmail = default, bool needShippingAddress = default, bool isFlexible = default, bool disableNotification = default, int replyToMessageId = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default, bool sendPhoneNumberToProvider = default, bool sendEmailToProvider = default ) => MakeRequestAsync(new SendInvoiceRequest( chatId, title, description, payload, providerToken, startParameter, currency, // ReSharper disable once PossibleMultipleEnumeration prices ) { ProviderData = providerData, PhotoUrl = photoUrl, PhotoSize = photoSize, PhotoWidth = photoWidth, PhotoHeight = photoHeight, NeedName = needName, NeedPhoneNumber = needPhoneNumber, NeedEmail = needEmail, NeedShippingAddress = needShippingAddress, SendPhoneNumberToProvider = sendPhoneNumberToProvider, SendEmailToProvider = sendEmailToProvider, IsFlexible = isFlexible, DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task AnswerShippingQueryAsync( string shippingQueryId, IEnumerable<ShippingOption> shippingOptions, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerShippingQueryRequest(shippingQueryId, shippingOptions), cancellationToken); /// <inheritdoc /> public Task AnswerShippingQueryAsync( string shippingQueryId, string errorMessage, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerShippingQueryRequest(shippingQueryId, errorMessage), cancellationToken); /// <inheritdoc /> public Task AnswerPreCheckoutQueryAsync( string preCheckoutQueryId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerPreCheckoutQueryRequest(preCheckoutQueryId), cancellationToken); /// <inheritdoc /> public Task AnswerPreCheckoutQueryAsync( string preCheckoutQueryId, string errorMessage, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AnswerPreCheckoutQueryRequest(preCheckoutQueryId, errorMessage), cancellationToken); #endregion Payments #region Games /// <inheritdoc /> public Task<Message> SendGameAsync( long chatId, string gameShortName, bool disableNotification = default, int replyToMessageId = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SendGameRequest(chatId, gameShortName) { DisableNotification = disableNotification, ReplyToMessageId = replyToMessageId, ReplyMarkup = replyMarkup }, cancellationToken); /// <inheritdoc /> public Task<Message> SetGameScoreAsync( int userId, int score, long chatId, int messageId, bool force = default, bool disableEditMessage = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetGameScoreRequest(userId, score, chatId, messageId) { Force = force, DisableEditMessage = disableEditMessage }, cancellationToken); /// <inheritdoc /> public Task SetGameScoreAsync( int userId, int score, string inlineMessageId, bool force = default, bool disableEditMessage = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetInlineGameScoreRequest(userId, score, inlineMessageId) { Force = force, DisableEditMessage = disableEditMessage }, cancellationToken); /// <inheritdoc /> public Task<GameHighScore[]> GetGameHighScoresAsync( int userId, long chatId, int messageId, CancellationToken cancellationToken = default ) => MakeRequestAsync( new GetGameHighScoresRequest(userId, chatId, messageId), cancellationToken); /// <inheritdoc /> public Task<GameHighScore[]> GetGameHighScoresAsync( int userId, string inlineMessageId, CancellationToken cancellationToken = default ) => MakeRequestAsync( new GetInlineGameHighScoresRequest(userId, inlineMessageId), cancellationToken); #endregion Games #region Group and channel management /// <inheritdoc /> public Task<string> ExportChatInviteLinkAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new ExportChatInviteLinkRequest(chatId), cancellationToken); /// <inheritdoc /> public Task SetChatPhotoAsync( ChatId chatId, InputFileStream photo, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetChatPhotoRequest(chatId, photo), cancellationToken); /// <inheritdoc /> public Task DeleteChatPhotoAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new DeleteChatPhotoRequest(chatId), cancellationToken); /// <inheritdoc /> public Task SetChatTitleAsync( ChatId chatId, string title, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetChatTitleRequest(chatId, title), cancellationToken); /// <inheritdoc /> public Task SetChatDescriptionAsync( ChatId chatId, string description = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetChatDescriptionRequest(chatId, description), cancellationToken); /// <inheritdoc /> public Task PinChatMessageAsync( ChatId chatId, int messageId, bool disableNotification = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new PinChatMessageRequest(chatId, messageId) { DisableNotification = disableNotification }, cancellationToken); /// <inheritdoc /> public Task UnpinChatMessageAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new UnpinChatMessageRequest(chatId), cancellationToken); /// <inheritdoc /> public Task SetChatStickerSetAsync( ChatId chatId, string stickerSetName, CancellationToken cancellationToken = default ) => MakeRequestAsync(new SetChatStickerSetRequest(chatId, stickerSetName), cancellationToken); /// <inheritdoc /> public Task DeleteChatStickerSetAsync( ChatId chatId, CancellationToken cancellationToken = default ) => MakeRequestAsync(new DeleteChatStickerSetRequest(chatId), cancellationToken); #endregion #region Stickers /// <inheritdoc /> public Task<StickerSet> GetStickerSetAsync( string name, CancellationToken cancellationToken = default ) => MakeRequestAsync(new GetStickerSetRequest(name), cancellationToken); /// <inheritdoc /> public Task<File> UploadStickerFileAsync( int userId, InputFileStream pngSticker, CancellationToken cancellationToken = default ) => MakeRequestAsync(new UploadStickerFileRequest(userId, pngSticker), cancellationToken); /// <inheritdoc /> public Task CreateNewStickerSetAsync( int userId, string name, string title, InputOnlineFile pngSticker, string emojis, bool isMasks = default, MaskPosition maskPosition = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new CreateNewStickerSetRequest(userId, name, title, pngSticker, emojis) { ContainsMasks = isMasks, MaskPosition = maskPosition }, cancellationToken); /// <inheritdoc /> public Task AddStickerToSetAsync( int userId, string name, InputOnlineFile pngSticker, string emojis, MaskPosition maskPosition = default, CancellationToken cancellationToken = default ) => MakeRequestAsync(new AddStickerToSetRequest(userId, name, pngSticker, emojis) { MaskPosition = maskPosition }, cancellationToken); /// <inheritdoc /> public Task CreateNewAnimatedStickerSetAsync( int userId, string name, string title, InputFileStream tgsSticker, string emojis, bool isMasks = default, MaskPosition maskPosition = default, CancellationToken cancellationToken = default) => MakeRequestAsync( new CreateNewAnimatedStickerSetRequest(userId, name, title, tgsSticker, emojis) { ContainsMasks = isMasks, MaskPosition = maskPosition }, cancellationToken ); /// <inheritdoc /> public Task AddAnimatedStickerToSetAsync( int userId, string name, InputFileStream tgsSticker, string emojis, MaskPosition maskPosition = default, CancellationToken cancellationToken = default) => MakeRequestAsync( new AddAnimatedStickerToSetRequest(userId, name, tgsSticker, emojis) { MaskPosition = maskPosition }, cancellationToken ); /// <inheritdoc /> public Task SetStickerPositionInSetAsync( string sticker, int position, CancellationToken cancellationToken = default) => MakeRequestAsync( new SetStickerPositionInSetRequest(sticker, position), cancellationToken ); /// <inheritdoc /> public Task DeleteStickerFromSetAsync( string sticker, CancellationToken cancellationToken = default ) => MakeRequestAsync(new DeleteStickerFromSetRequest(sticker), cancellationToken); /// <inheritdoc /> public Task SetStickerSetThumbAsync( string name, int userId, InputOnlineFile thumb = default, CancellationToken cancellationToken = default) => MakeRequestAsync( new SetStickerSetThumbRequest(name, userId, thumb), cancellationToken ); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace EzySlice { /** * Contains methods for slicing GameObjects */ public sealed class Slicer { /** * An internal class for storing internal submesh values */ internal class SlicedSubmesh { public readonly List<Triangle> upperHull = new List<Triangle>(); public readonly List<Triangle> lowerHull = new List<Triangle>(); /** * Check if the submesh has had any UV's added. * NOTE -> This should be supported properly */ public bool hasUV { get { // what is this abomination?? return upperHull.Count > 0 ? upperHull[0].hasUV : lowerHull.Count > 0 ? lowerHull[0].hasUV : false; } } /** * Check if the submesh has had any Normals added. * NOTE -> This should be supported properly */ public bool hasNormal { get { // what is this abomination?? return upperHull.Count > 0 ? upperHull[0].hasNormal : lowerHull.Count > 0 ? lowerHull[0].hasNormal : false; } } /** * Check if the submesh has had any Tangents added. * NOTE -> This should be supported properly */ public bool hasTangent { get { // what is this abomination?? return upperHull.Count > 0 ? upperHull[0].hasTangent : lowerHull.Count > 0 ? lowerHull[0].hasTangent : false; } } /** * Check if proper slicing has occured for this submesh. Slice occured if there * are triangles in both the upper and lower hulls */ public bool isValid { get { return upperHull.Count > 0 && lowerHull.Count > 0; } } } /** * Helper function to accept a gameobject which will transform the plane * approprietly before the slice occurs * See -> Slice(Mesh, Plane) for more info */ public static SlicedHull Slice(GameObject obj, Plane pl, TextureRegion crossRegion, Material crossMaterial) { MeshFilter filter = obj.GetComponent<MeshFilter>(); // cannot continue without a proper filter if (filter == null) { Debug.LogWarning("EzySlice::Slice -> Provided GameObject must have a MeshFilter Component."); return null; } MeshRenderer renderer = obj.GetComponent<MeshRenderer>(); // cannot continue without a proper renderer if (renderer == null) { Debug.LogWarning("EzySlice::Slice -> Provided GameObject must have a MeshRenderer Component."); return null; } Material[] materials = renderer.sharedMaterials; Mesh mesh = filter.sharedMesh; // cannot slice a mesh that doesn't exist if (mesh == null) { Debug.LogWarning("EzySlice::Slice -> Provided GameObject must have a Mesh that is not NULL."); return null; } int submeshCount = mesh.subMeshCount; // to make things straightforward, exit without slicing if the materials and mesh // array don't match. This shouldn't happen anyway if (materials.Length != submeshCount) { Debug.LogWarning("EzySlice::Slice -> Provided Material array must match the length of submeshes."); return null; } // we need to find the index of the material for the cross section. // default to the end of the array int crossIndex = materials.Length; // for cases where the sliced material is null, we will append the cross section to the end // of the submesh array, this is because the application may want to set/change the material // after slicing has occured, so we don't assume anything if (crossMaterial != null) { for (int i = 0; i < crossIndex; i++) { if (materials[i] == crossMaterial) { crossIndex = i; break; } } } return Slice(mesh, pl, crossRegion, crossIndex); } /** * Slice the gameobject mesh (if any) using the Plane, which will generate * a maximum of 2 other Meshes. * This function will recalculate new UV coordinates to ensure textures are applied * properly. * Returns null if no intersection has been found or the GameObject does not contain * a valid mesh to cut. */ public static SlicedHull Slice(Mesh sharedMesh, Plane pl, TextureRegion region, int crossIndex) { if (sharedMesh == null) { return null; } Vector3[] verts = sharedMesh.vertices; Vector2[] uv = sharedMesh.uv; Vector3[] norm = sharedMesh.normals; Vector4[] tan = sharedMesh.tangents; int submeshCount = sharedMesh.subMeshCount; // each submesh will be sliced and placed in its own array structure SlicedSubmesh[] slices = new SlicedSubmesh[submeshCount]; // the cross section hull is common across all submeshes List<Vector3> crossHull = new List<Vector3>(); // we reuse this object for all intersection tests IntersectionResult result = new IntersectionResult(); // see if we would like to split the mesh using uv, normals and tangents bool genUV = verts.Length == uv.Length; bool genNorm = verts.Length == norm.Length; bool genTan = verts.Length == tan.Length; // iterate over all the submeshes individually. vertices and indices // are all shared within the submesh for (int submesh = 0; submesh < submeshCount; submesh++) { int[] indices = sharedMesh.GetTriangles(submesh); int indicesCount = indices.Length; SlicedSubmesh mesh = new SlicedSubmesh(); // loop through all the mesh vertices, generating upper and lower hulls // and all intersection points for (int index = 0; index < indicesCount; index += 3) { int i0 = indices[index + 0]; int i1 = indices[index + 1]; int i2 = indices[index + 2]; Triangle newTri = new Triangle(verts[i0], verts[i1], verts[i2]); // generate UV if available if (genUV) { newTri.SetUV(uv[i0], uv[i1], uv[i2]); } // generate normals if available if (genNorm) { newTri.SetNormal(norm[i0], norm[i1], norm[i2]); } // generate tangents if available if (genTan) { newTri.SetTangent(tan[i0], tan[i1], tan[i2]); } // slice this particular triangle with the provided // plane if (newTri.Split(pl, result)) { int upperHullCount = result.upperHullCount; int lowerHullCount = result.lowerHullCount; int interHullCount = result.intersectionPointCount; for (int i = 0; i < upperHullCount; i++) { mesh.upperHull.Add(result.upperHull[i]); } for (int i = 0; i < lowerHullCount; i++) { mesh.lowerHull.Add(result.lowerHull[i]); } for (int i = 0; i < interHullCount; i++) { crossHull.Add(result.intersectionPoints[i]); } } else { SideOfPlane sa = pl.SideOf(verts[i0]); SideOfPlane sb = pl.SideOf(verts[i1]); SideOfPlane sc = pl.SideOf(verts[i2]); SideOfPlane side = SideOfPlane.ON; if (sa != SideOfPlane.ON) { side = sa; } if (sb != SideOfPlane.ON) { Debug.Assert(side == SideOfPlane.ON || side == sb); side = sb; } if (sc != SideOfPlane.ON) { Debug.Assert(side == SideOfPlane.ON || side == sc); side = sc; } if (side == SideOfPlane.UP || side == SideOfPlane.ON) { mesh.upperHull.Add(newTri); } else { mesh.lowerHull.Add(newTri); } } } // register into the index slices[submesh] = mesh; } // check if slicing actually occured for (int i = 0; i < slices.Length; i++) { // check if at least one of the submeshes was sliced. If so, stop checking // because we need to go through the generation step if (slices[i] != null && slices[i].isValid) { return CreateFrom(slices, CreateFrom(crossHull, pl.normal, region), crossIndex); } } // no slicing occured, just return null to signify return null; } /** * Generates a single SlicedHull from a set of cut submeshes */ private static SlicedHull CreateFrom(SlicedSubmesh[] meshes, List<Triangle> cross, int crossSectionIndex) { int submeshCount = meshes.Length; int upperHullCount = 0; int lowerHullCount = 0; // get the total amount of upper, lower and intersection counts for (int submesh = 0; submesh < submeshCount; submesh++) { upperHullCount += meshes[submesh].upperHull.Count; lowerHullCount += meshes[submesh].lowerHull.Count; } Mesh upperHull = CreateUpperHull(meshes, upperHullCount, cross, crossSectionIndex); Mesh lowerHull = CreateLowerHull(meshes, lowerHullCount, cross, crossSectionIndex); return new SlicedHull(upperHull, lowerHull); } private static Mesh CreateUpperHull(SlicedSubmesh[] mesh, int total, List<Triangle> crossSection, int crossSectionIndex) { return CreateHull(mesh, total, crossSection, crossSectionIndex, true); } private static Mesh CreateLowerHull(SlicedSubmesh[] mesh, int total, List<Triangle> crossSection, int crossSectionIndex) { return CreateHull(mesh, total, crossSection, crossSectionIndex, false); } /** * Generate a single Mesh HULL of either the UPPER or LOWER hulls. */ private static Mesh CreateHull(SlicedSubmesh[] meshes, int total, List<Triangle> crossSection, int crossIndex, bool isUpper) { if (total <= 0) { return null; } int submeshCount = meshes.Length; int crossCount = crossSection != null ? crossSection.Count : 0; Mesh newMesh = new Mesh(); newMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; int arrayLen = (total + crossCount) * 3; bool hasUV = meshes[0].hasUV; bool hasNormal = meshes[0].hasNormal; bool hasTangent = meshes[0].hasTangent; // vertices and uv's are common for all submeshes Vector3[] newVertices = new Vector3[arrayLen]; Vector2[] newUvs = hasUV ? new Vector2[arrayLen] : null; Vector3[] newNormals = hasNormal ? new Vector3[arrayLen] : null; Vector4[] newTangents = hasTangent ? new Vector4[arrayLen] : null; // each index refers to our submesh triangles List<int[]> triangles = new List<int[]>(submeshCount); int vIndex = 0; // first we generate all our vertices, uv's and triangles for (int submesh = 0; submesh < submeshCount; submesh++) { // pick the hull we will be playing around with List<Triangle> hull = isUpper ? meshes[submesh].upperHull : meshes[submesh].lowerHull; int hullCount = hull.Count; int[] indices = new int[hullCount * 3]; // fill our mesh arrays for (int i = 0, triIndex = 0; i < hullCount; i++, triIndex += 3) { Triangle newTri = hull[i]; int i0 = vIndex + 0; int i1 = vIndex + 1; int i2 = vIndex + 2; // add the vertices newVertices[i0] = newTri.positionA; newVertices[i1] = newTri.positionB; newVertices[i2] = newTri.positionC; // add the UV coordinates if any if (hasUV) { newUvs[i0] = newTri.uvA; newUvs[i1] = newTri.uvB; newUvs[i2] = newTri.uvC; } // add the Normals if any if (hasNormal) { newNormals[i0] = newTri.normalA; newNormals[i1] = newTri.normalB; newNormals[i2] = newTri.normalC; } // add the Tangents if any if (hasTangent) { newTangents[i0] = newTri.tangentA; newTangents[i1] = newTri.tangentB; newTangents[i2] = newTri.tangentC; } // triangles are returned in clocwise order from the // intersector, no need to sort these indices[triIndex] = i0; indices[triIndex + 1] = i1; indices[triIndex + 2] = i2; vIndex += 3; } // add triangles to the index for later generation triangles.Add(indices); } // generate the cross section required for this particular hull if (crossSection != null && crossCount > 0) { int[] crossIndices = new int[crossCount * 3]; for (int i = 0, triIndex = 0; i < crossCount; i++, triIndex += 3) { Triangle newTri = crossSection[i]; int i0 = vIndex + 0; int i1 = vIndex + 1; int i2 = vIndex + 2; // add the vertices newVertices[i0] = newTri.positionA; newVertices[i1] = newTri.positionB; newVertices[i2] = newTri.positionC; // add the UV coordinates if any if (hasUV) { newUvs[i0] = newTri.uvA; newUvs[i1] = newTri.uvB; newUvs[i2] = newTri.uvC; } // add the Normals if any if (hasNormal) { // invert the normals dependiong on upper or lower hull if (isUpper) { newNormals[i0] = -newTri.normalA; newNormals[i1] = -newTri.normalB; newNormals[i2] = -newTri.normalC; } else { newNormals[i0] = newTri.normalA; newNormals[i1] = newTri.normalB; newNormals[i2] = newTri.normalC; } } // add the Tangents if any if (hasTangent) { newTangents[i0] = newTri.tangentA; newTangents[i1] = newTri.tangentB; newTangents[i2] = newTri.tangentC; } // add triangles in clockwise for upper // and reversed for lower hulls, to ensure the mesh // is facing the right direction if (isUpper) { crossIndices[triIndex] = i0; crossIndices[triIndex + 1] = i1; crossIndices[triIndex + 2] = i2; } else { crossIndices[triIndex] = i0; crossIndices[triIndex + 1] = i2; crossIndices[triIndex + 2] = i1; } vIndex += 3; } // add triangles to the index for later generation if (triangles.Count <= crossIndex) { triangles.Add(crossIndices); } else { // otherwise, we need to merge the triangles for the provided subsection int[] prevTriangles = triangles[crossIndex]; int[] merged = new int[prevTriangles.Length + crossIndices.Length]; System.Array.Copy(prevTriangles, merged, prevTriangles.Length); System.Array.Copy(crossIndices, 0, merged, prevTriangles.Length, crossIndices.Length); // replace the previous array with the new merged array triangles[crossIndex] = merged; } } int totalTriangles = triangles.Count; newMesh.subMeshCount = totalTriangles; // fill the mesh structure newMesh.vertices = newVertices; if (hasUV) { newMesh.uv = newUvs; } if (hasNormal) { newMesh.normals = newNormals; } if (hasTangent) { newMesh.tangents = newTangents; } // add the submeshes for (int i = 0; i < totalTriangles; i++) { newMesh.SetTriangles(triangles[i], i, false); } return newMesh; } /** * Generate Two Meshes (an upper and lower) cross section from a set of intersection * points and a plane normal. Intersection Points do not have to be in order. */ private static List<Triangle> CreateFrom(List<Vector3> intPoints, Vector3 planeNormal, TextureRegion region) { List<Triangle> tris; if (Triangulator.MonotoneChain(intPoints, planeNormal, out tris, region)) { return tris; } return null; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubnetsOperations operations. /// </summary> internal partial class SubnetsOperations : IServiceOperations<NetworkClient>, ISubnetsOperations { /// <summary> /// Initializes a new instance of the SubnetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubnetsOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified subnet by virtual network and resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _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<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _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<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (subnetParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(subnetParameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _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<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _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<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void Permute2x128UInt642() { var test = new ImmBinaryOpTest__Permute2x128UInt642(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__Permute2x128UInt642 { private struct TestStruct { public Vector256<UInt64> _fld1; public Vector256<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128UInt642 testClass) { var result = Avx2.Permute2x128(_fld1, _fld2, 2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable; static ImmBinaryOpTest__Permute2x128UInt642() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public ImmBinaryOpTest__Permute2x128UInt642() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Permute2x128( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Permute2x128( Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Permute2x128( Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Permute2x128( _clsVar1, _clsVar2, 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Avx2.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__Permute2x128UInt642(); var result = Avx2.Permute2x128(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Permute2x128(_fld1, _fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Permute2x128(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (i > 1 ? (result[i] != left[i - 2]) : (result[i] != right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Permute2x128)}<UInt64>(Vector256<UInt64>.2, Vector256<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using EPiServer.Commerce.Order; using EPiServer.Logging; using EPiServer.ServiceLocation; using Mediachase.Commerce.InventoryService; using Mediachase.Commerce.InventoryService.BusinessLogic; using Mediachase.Commerce.Orders; using Mediachase.Commerce.Orders.Managers; using Mediachase.Commerce.WorkflowCompatibility; using Mediachase.MetaDataPlus; using System; using System.Collections.Generic; using System.Linq; namespace Mediachase.Commerce.Workflow.Cart { public class AdjustInventoryActivity : CartActivityBase { [NonSerialized] private readonly ILogger _logger = LogManager.GetLogger(typeof(AdjustInventoryActivity)); private Injected<IInventoryService> _inventoryService; private Injected<OperationKeySerializer> _operationKeySerializer; private readonly static object _lockObject = new object(); /// <summary> /// Get inventory requests for shipment /// </summary> /// <param name="shipment">The shipment</param> /// <param name="itemIndexStart">The start index</param> /// <param name="type">The inventory request type</param> /// <returns>List inventory request item of a shipment</returns> private IEnumerable<InventoryRequestItem> GetRequestInventory(Shipment shipment, int itemIndexStart, InventoryRequestType type) { return shipment.OperationKeysMap.SelectMany(c => c.Value).Select(key => new InventoryRequestItem() { ItemIndex = itemIndexStart++, OperationKey = key, RequestType = type }); } /// <summary> /// Get inventory request for the line item. /// </summary> /// <param name="shipment">The shipment</param> /// <param name="lineItemIndex">The line item index</param> /// <param name="itemIndexStart">The start index for request item</param> /// <param name="type">The inventory request type</param> /// <returns>List inventory request item for a line item</returns> private IEnumerable<InventoryRequestItem> GetLineItemRequestInventory(Shipment shipment, int lineItemIndex, int itemIndexStart, InventoryRequestType type) { return shipment.OperationKeysMap.Where(c => c.Key == lineItemIndex).SelectMany(c => c.Value).Select(key => new InventoryRequestItem() { ItemIndex = itemIndexStart++, OperationKey = key, RequestType = type }); } /// <summary> /// Called by the workflow runtime to execute an activity. /// </summary> /// <param name="executionContext">The <see cref="T:Mediachase.Commerce.WorkflowCompatibility.ActivityExecutionContext"/> to associate with this <see cref="T:Mediachase.Commerce.WorkflowCompatibility.Activity"/> and execution.</param> /// <returns> /// The <see cref="T:Mediachase.Commerce.WorkflowCompatibility.ActivityExecutionStatus"/> of the run task, which determines whether the activity remains in the executing state, or transitions to the closed state. /// </returns> protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // Check for multiple warehouses. In the default, we simply reject processing an order if the application has // multiple warehouses. Any corresponding fulfillment process is the responsibility of the client. CheckMultiWarehouse(); // Validate the properties at runtime ValidateRuntime(); // Return close status if order group is Payment Plan if (OrderGroup is PaymentPlan) { return ActivityExecutionStatus.Closed; } var orderGroupStatus = OrderStatusManager.GetOrderGroupStatus(OrderGroup); var orderForms = OrderGroup.OrderForms.Where(o => !OrderForm.IsReturnOrderForm(o)); var inventoryRequests = new List<InventoryRequestItem>(); foreach (OrderForm orderForm in orderForms) { foreach (Shipment shipment in orderForm.Shipments) { if (!ValidateShipment(orderForm, shipment)) { continue; } var shipmentStatus = OrderStatusManager.GetOrderShipmentStatus(shipment); bool completingOrder = orderGroupStatus == OrderStatus.Completed || shipmentStatus == OrderShipmentStatus.Shipped; bool cancellingOrder = orderGroupStatus == OrderStatus.Cancelled || shipmentStatus == OrderShipmentStatus.Cancelled; _logger.Debug(string.Format("Adjusting inventory, got orderGroupStatus as {0} and shipmentStatus as {1}. completingOrder as {2} and cancellingOrder as {3}.", orderGroupStatus, shipmentStatus, completingOrder, cancellingOrder)); // When completing/cancelling an order or a shipment if (completingOrder || cancellingOrder) { var requestType = completingOrder ? InventoryRequestType.Complete : InventoryRequestType.Cancel; inventoryRequests.AddRange(GetRequestInventory(shipment, inventoryRequests.Count, requestType)); // When processed request, need to clear all operation keys from the shipment shipment.ClearOperationKeys(); } // When release a shipment, check if shipment contain a BackOrder then need to complete that BackOrder. else if (shipmentStatus == OrderShipmentStatus.Released) { foreach (LineItem lineItem in Shipment.GetShipmentLineItems(shipment)) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); var completeBackOrderRequest = new List<InventoryRequestItem>(); var lineItemRequest = GetLineItemRequestInventory(shipment, lineItemIndex, 0, InventoryRequestType.Complete); // Only need to process complete BackOrder request type foreach (var request in lineItemRequest) { InventoryRequestType requestType; InventoryChange change; _operationKeySerializer.Service.TryDeserialize(request.OperationKey, out requestType, out change); if (requestType == InventoryRequestType.Backorder) { // Add BackOrder request to request list completeBackOrderRequest.Add(request); // Then remove BackOrder request operation key from shipment's operation key map shipment.RemoveOperationKey(lineItemIndex, request.OperationKey); } } // Storage the response operation keys from complete BackOrder mapping with line item index if (completeBackOrderRequest.Count > 0) { InventoryResponse response = _inventoryService.Service.Request(new InventoryRequest(DateTime.UtcNow, completeBackOrderRequest, null)); if (response != null && response.IsSuccess) { shipment.InsertOperationKeys(lineItemIndex, response.Items.Select(c => c.OperationKey)); } } } } else if (orderGroupStatus == OrderStatus.InProgress || orderGroupStatus == OrderStatus.AwaitingExchange) { // When placing an order or creating an exchange order bool placingOrder = shipmentStatus == OrderShipmentStatus.AwaitingInventory || shipmentStatus == OrderShipmentStatus.InventoryAssigned; if (placingOrder) { var lineItems = Shipment.GetShipmentLineItems(shipment); CancelOperationKeys(shipment); foreach (LineItem lineItem in lineItems) { RequestInventory(orderForm, shipment, lineItem); } } } } } if (inventoryRequests.Any()) { _inventoryService.Service.Request(new InventoryRequest(DateTime.UtcNow, inventoryRequests, null)); } // Retun the closed status indicating that this activity is complete. return ActivityExecutionStatus.Closed; } private void RequestInventory(OrderForm orderForm, Shipment shipment, LineItem lineItem) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); InventoryRequest request; InventoryResponse response = null; // If item is out of stock then delete item. if (GetNewLineItemQty(lineItem, new List<string>(), shipment) <= 0) { Warnings.Add("LineItemRemoved-" + lineItem.LineItemId.ToString(), string.Format("Item \"{0}\" has been removed from the cart because there is not enough available quantity.", lineItem.DisplayName)); PurchaseOrderManager.RemoveLineItemFromShipment(orderForm.Parent, lineItem.LineItemId, shipment); ValidateShipment(orderForm, shipment); return; } // Else try to allocate quantity request = AdjustStockItemQuantity(shipment, lineItem); if (request != null) { response = _inventoryService.Service.Request(request); } if (response != null && response.IsSuccess) { lineItem.IsInventoryAllocated = true; // Store operation keys to Shipment for each line item, to use later for complete request var existedIndex = shipment.OperationKeysMap.ContainsKey(lineItemIndex); var operationKeys = response.Items.Select(c => c.OperationKey); if (!existedIndex) { shipment.AddInventoryOperationKey(lineItemIndex, operationKeys); } else { shipment.InsertOperationKeys(lineItemIndex, operationKeys); } } } /// <summary> /// Verifies whether a shipment is empty. /// If the shipment is empty, its operation keys will be canceled. /// </summary> /// <param name="orderForm">The order form.</param> /// <param name="shipment">The shipment.</param> /// <remarks>The shipment will be deleted if the order has more than one shipment, /// so that it always keep at least one shipment in the order form. /// </remarks> /// <returns><c>False</c> if the shipment does not have any line item, otherwise <c>True</c>.</returns> private bool ValidateShipment(OrderForm orderForm, Shipment shipment) { if (shipment.LineItemIndexes.Length == 0) { CancelOperationKeys(shipment); if (orderForm.Shipments.Count > 1) { shipment.Delete(); shipment.AcceptChanges(); } return false; } return true; } } }
// The MIT License (MIT) // // Copyright (c) 2015, Unity Technologies & Google, 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 UnityEngine; using UnityEngine.EventSystems; /// This script provides an implemention of Unity's `BaseInputModule` class, so /// that Canvas-based (_uGUI_) UI elements can be selected by looking at them and /// pulling the viewer's trigger or touching the screen. /// This uses the player's gaze and the trigger as a raycast generator. /// /// To use, attach to the scene's **EventSystem** object. Be sure to move it above the /// other modules, such as _TouchInputModule_ and _StandaloneInputModule_, in order /// for the user's gaze to take priority in the event system. /// /// Next, set the **Canvas** object's _Render Mode_ to **World Space**, and set its _Event Camera_ /// to a (mono) camera that is controlled by a GvrHead. If you'd like gaze to work /// with 3D scene objects, add a _PhysicsRaycaster_ to the gazing camera, and add a /// component that implements one of the _Event_ interfaces (_EventTrigger_ will work nicely). /// The objects must have colliders too. /// /// GazeInputModule emits the following events: _Enter_, _Exit_, _Down_, _Up_, _Click_, _Select_, /// _Deselect_, and _UpdateSelected_. Scroll, move, and submit/cancel events are not emitted. [AddComponentMenu("GoogleVR/GazeInputModule")] public class GazeInputModule : BaseInputModule { /// Determines whether gaze input is active in VR Mode only (`true`), or all of the /// time (`false`). Set to false if you plan to use direct screen taps or other /// input when not in VR Mode. [Tooltip("Whether gaze input is active in VR Mode only (true), or all the time (false).")] public bool vrModeOnly = false; /// Time in seconds between the pointer down and up events sent by a trigger. /// Allows time for the UI elements to make their state transitions. [HideInInspector] public float clickTime = 0.1f; // Based on default time for a button to animate to Pressed. /// The pixel through which to cast rays, in viewport coordinates. Generally, the center /// pixel is best, assuming a monoscopic camera is selected as the `Canvas`' event camera. [HideInInspector] public Vector2 hotspot = new Vector2(0.5f, 0.5f); private PointerEventData pointerData; private Vector2 lastHeadPose; /// The IGvrGazePointer which will be responding to gaze events. public static IGvrGazePointer gazePointer; // Active state private bool isActive = false; /// @cond public override bool ShouldActivateModule() { bool activeState = base.ShouldActivateModule(); activeState = activeState && (GvrViewer.Instance.VRModeEnabled || !vrModeOnly); if (activeState != isActive) { isActive = activeState; // Activate gaze pointer if (gazePointer != null) { if (isActive) { gazePointer.OnGazeEnabled(); } } } return activeState; } /// @endcond public override void DeactivateModule() { DisableGazePointer(); base.DeactivateModule(); if (pointerData != null) { HandlePendingClick(); HandlePointerExitAndEnter(pointerData, null); pointerData = null; } eventSystem.SetSelectedGameObject(null, GetBaseEventData()); } public override bool IsPointerOverGameObject(int pointerId) { return pointerData != null && pointerData.pointerEnter != null; } public override void Process() { // Save the previous Game Object GameObject gazeObjectPrevious = GetCurrentGameObject(); CastRayFromGaze(); UpdateCurrentObject(); UpdateReticle(gazeObjectPrevious); // Handle input if (!Input.GetMouseButtonDown(0) && Input.GetMouseButton(0)) { HandleDrag(); } else if (Time.unscaledTime - pointerData.clickTime < clickTime) { // Delay new events until clickTime has passed. } else if (!pointerData.eligibleForClick && (GvrViewer.Instance.Triggered || Input.GetMouseButtonDown(0) || GvrController.ClickButtonDown)) { // New trigger action. HandleTrigger(); } else if (!GvrViewer.Instance.Triggered && !Input.GetMouseButton(0) && !GvrController.ClickButton) { // Check if there is a pending click to handle. HandlePendingClick(); } } /// @endcond private void CastRayFromGaze() { Vector2 headPose = NormalizedCartesianToSpherical(GvrViewer.Instance.HeadPose.Orientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Cast a ray into the scene pointerData.Reset(); pointerData.position = new Vector2(hotspot.x * Screen.width, hotspot.y * Screen.height); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); pointerData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache); m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; } private void UpdateCurrentObject() { // Send enter events and update the highlight. var go = pointerData.pointerCurrentRaycast.gameObject; HandlePointerExitAndEnter(pointerData, go); // Update the current selection, or clear if it is no longer the current object. var selected = ExecuteEvents.GetEventHandler<ISelectHandler>(go); if (selected == eventSystem.currentSelectedGameObject) { ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, GetBaseEventData(), ExecuteEvents.updateSelectedHandler); } else { eventSystem.SetSelectedGameObject(null, pointerData); } } void UpdateReticle(GameObject previousGazedObject) { if (gazePointer == null) { return; } Camera camera = pointerData.enterEventCamera; // Get the camera GameObject gazeObject = GetCurrentGameObject(); // Get the gaze target Vector3 intersectionPosition = GetIntersectionPosition(); bool isInteractive = pointerData.pointerPress != null || ExecuteEvents.GetEventHandler<IPointerClickHandler>(gazeObject) != null; if (gazeObject == previousGazedObject) { if (gazeObject != null) { gazePointer.OnGazeStay(camera, gazeObject, intersectionPosition, isInteractive); } } else { if (previousGazedObject != null) { gazePointer.OnGazeExit(camera, previousGazedObject); } if (gazeObject != null) { gazePointer.OnGazeStart(camera, gazeObject, intersectionPosition, isInteractive); } } } private void HandleDrag() { bool moving = pointerData.IsPointerMoving(); if (moving && pointerData.pointerDrag != null && !pointerData.dragging) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.beginDragHandler); pointerData.dragging = true; } // Drag notification if (pointerData.dragging && moving && pointerData.pointerDrag != null) { // Before doing drag we should cancel any pointer down state // And clear selection! if (pointerData.pointerPress != pointerData.pointerDrag) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); pointerData.eligibleForClick = false; pointerData.pointerPress = null; pointerData.rawPointerPress = null; } ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.dragHandler); } } private void HandlePendingClick() { if (!pointerData.eligibleForClick && !pointerData.dragging) { return; } if (gazePointer != null) { Camera camera = pointerData.enterEventCamera; gazePointer.OnGazeTriggerEnd(camera); } var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer up and click events. ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); if (pointerData.eligibleForClick) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerClickHandler); } else if (pointerData.dragging) { ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.dropHandler); ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.endDragHandler); } // Clear the click state. pointerData.pointerPress = null; pointerData.rawPointerPress = null; pointerData.eligibleForClick = false; pointerData.clickCount = 0; pointerData.clickTime = 0; pointerData.pointerDrag = null; pointerData.dragging = false; } private void HandleTrigger() { var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer down event. pointerData.pressPosition = pointerData.position; pointerData.pointerPressRaycast = pointerData.pointerCurrentRaycast; pointerData.pointerPress = ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.pointerDownHandler) ?? ExecuteEvents.GetEventHandler<IPointerClickHandler>(go); // Save the drag handler as well pointerData.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(go); if (pointerData.pointerDrag != null) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.initializePotentialDrag); } // Save the pending click state. pointerData.rawPointerPress = go; pointerData.eligibleForClick = true; pointerData.delta = Vector2.zero; pointerData.dragging = false; pointerData.useDragThreshold = true; pointerData.clickCount = 1; pointerData.clickTime = Time.unscaledTime; if (gazePointer != null) { gazePointer.OnGazeTriggerStart(pointerData.enterEventCamera); } } private Vector2 NormalizedCartesianToSpherical(Vector3 cartCoords) { cartCoords.Normalize(); if (cartCoords.x == 0) cartCoords.x = Mathf.Epsilon; float outPolar = Mathf.Atan(cartCoords.z / cartCoords.x); if (cartCoords.x < 0) outPolar += Mathf.PI; float outElevation = Mathf.Asin(cartCoords.y); return new Vector2(outPolar, outElevation); } GameObject GetCurrentGameObject() { if (pointerData != null && pointerData.enterEventCamera != null) { return pointerData.pointerCurrentRaycast.gameObject; } return null; } Vector3 GetIntersectionPosition() { // Check for camera Camera cam = pointerData.enterEventCamera; if (cam == null) { return Vector3.zero; } float intersectionDistance = pointerData.pointerCurrentRaycast.distance + cam.nearClipPlane; Vector3 intersectionPosition = cam.transform.position + cam.transform.forward * intersectionDistance; return intersectionPosition; } void DisableGazePointer() { if (gazePointer == null) { return; } GameObject currentGameObject = GetCurrentGameObject(); if (currentGameObject) { Camera camera = pointerData.enterEventCamera; gazePointer.OnGazeExit(camera, currentGameObject); } gazePointer.OnGazeDisabled(); } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using SQLite.Net.Cipher.Interfaces; using SQLite.Net.Cipher.Model; using SQLite.Net.Cipher.Security; using SQLite.Net.Cipher.Utility; using SQLite.Net.Interop; using System; namespace SQLite.Net.Cipher.Data { /// <summary> /// This is the main entiry in this library. Extend this class to get the benefits of this library. /// You will need to implement the abstract method CreateTables(); /// </summary> public abstract class SecureDatabase : SQLiteConnection, ISecureDatabase { private ICryptoService _cryptoService; /// <summary> /// Construct a new instance of SecureDatabase. /// </summary> /// <param name="platform">The platform specific engine of SQLite (ISQLitePlatform)</param> /// <param name="dbfile">The sqlite db file path</param> protected SecureDatabase(ISQLitePlatform platform, string dbfile) : this(platform, dbfile, "SOME-RANDOM-SALT") { } /// <summary> /// Construct a new instance of SecureDatabase. /// </summary> /// <param name="platform">The platform specific engine of SQLite (ISQLitePlatform)</param> /// <param name="dbfile">The sqlite db file path</param> /// /// <param name="randomSaltText">The random salt text</param> protected SecureDatabase(ISQLitePlatform platform, string dbfile, string randomSaltText) : this(platform, dbfile, new CryptoService(randomSaltText)) { } /// <summary> /// Construct a new instance of SecureDatabase. /// This ctor allows you pass an instance of the CryptoService. You could use the one provided by SQLite.Net.Cipher or build and pass your own. /// </summary> /// <param name="platform">The platform specific engine of SQLite (ISQLitePlatform)</param> /// <param name="dbfile">The sqlite db file path</param> /// <param name="cryptoService">An instance of the Crypto Service</param> protected SecureDatabase (ISQLitePlatform platform, string dbfile, ICryptoService cryptoService) : base (platform, dbfile) { _cryptoService = cryptoService; CreateTables (); } /// <summary> /// Override this method to create your tables /// </summary> protected abstract void CreateTables(); /// <summary> /// Executes an sql query against the database. /// This method does not do anything more than the base.ExecuteScalar(); /// </summary> /// <param name="query"></param> /// <param name="args"></param> /// <returns>no of affected rows</returns> public int SecureExecuteScalar(string query, params object[] args) { return ExecuteScalar<int> (query, args); } /// <summary> /// gets a list of objects from the database using Query() method /// and it decrypt all object properties that have the attribute Secure. /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <param name="query">The Sql query</param> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <param name="args">The sql query parameters.</param> /// <returns>List of T </returns> List<T> ISecureDatabase.SecureQuery<T>(string query, string keySeed, params object[] args) { var list = Query<T> (query, args); DecryptList(list, keySeed); return list; } /// <summary> /// Inserts into the database /// Before inserting, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be inserted</typeparam> /// <param name="obj"> the object to be inserted to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int ISecureDatabase.SecureInsert<T>(T obj, string keySeed) { Guard.CheckForNull(obj, "obj cannot be null"); Encrypt(obj,keySeed); return base.Insert(obj); } /// <summary> /// Inserts or Replace into the database /// Before inserting, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be inserted</typeparam> /// <param name="obj"> the object to be inserted to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int ISecureDatabase.SecureInsertOrReplace<T>(T obj, string keySeed) { Guard.CheckForNull(obj, "obj cannot be null"); Encrypt(obj,keySeed); return base.InsertOrReplace(obj); } /// <summary> /// Updates a row in the database /// Before Before Updating, it encrypts all propertiese that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be updated</typeparam> /// <param name="obj"> the object to be updated to the database</param> /// <param name="keySeed">The encryption key seed. You must use the same key seed when accessing the object out of the database.</param> /// <returns>no of affected rows</returns> int ISecureDatabase.SecureUpdate<T>(T obj, string keySeed) { Guard.CheckForNull(obj, "obj cannot be null"); Encrypt(obj, keySeed); return base.Update(obj); } /// <summary> /// deletes a row in the database /// </summary> /// <typeparam name="T">The Type of the object to be deleted</typeparam> /// <param name="id">The id of the object to be deleted.</param> /// <returns>no of affected rows</returns> int ISecureDatabase.SecureDelete<T>(string id) { return base.ExecuteScalar<int>(string.Format("Delete from {0} where id = ? ", typeof (T).Name), id); } /// <summary> /// Gets an object of the database /// If the object is found, before returned, this method will decrypt all its properties that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be accessed</typeparam> /// <param name="id">The id of the object to be accessed.</param> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <returns>returns an instance of T if found.</returns> T ISecureDatabase.SecureGet<T>(string id, string keySeed) { var matching = base.Query<T>(string.Format("select * from {0} where id = ? ", typeof (T).Name), id); var item = matching.FirstOrDefault(); Decrypt(item, keySeed); return item; } /// <summary> /// Gets a list of T objects from the database /// If any objects were found, before returned, this method will decrypt all their properties that have the Secure attribute. /// </summary> /// <typeparam name="T">The Type of the object to be accessed</typeparam> /// <param name="keySeed">The encryption key seed (must be the same that you use when inserted into the database).</param> /// <returns>returns a List of T if found.</returns> List<T> ISecureDatabase.SecureGetAll<T>(string keySeed) { var list = base.Query<T>(string.Format("select * from {0}", typeof (T).Name)); DecryptList(list, keySeed); return list; } /// <summary> /// Gets a count of all rows in the table that matches the type T /// </summary> /// <typeparam name="T">The type of the object we are trying to get the count for.</typeparam> /// <returns>int that represent the no of rows (of T) in the db. </returns> int ISecureDatabase.SecureGetCount<T>() { return base.ExecuteScalar<int>(string.Format("SELECT COUNT(*) FROM {0} ", typeof(T).Name)); } #region Implementation private void Encrypt(object model, string keySeed) { if (model == null) return; IEnumerable<PropertyInfo> secureProperties = GetSecureProperties(model); foreach (var propertyInfo in secureProperties) { var rawPropertyValue = (string)propertyInfo.GetValue(model); var encrypted = _cryptoService.Encrypt(rawPropertyValue, keySeed, null); propertyInfo.SetValue(model, encrypted); } } private void Decrypt(object model, string keySeed) { if (model == null) return; IEnumerable<PropertyInfo> secureProperties = GetSecureProperties(model); foreach (var propertyInfo in secureProperties) { var rawPropertyValue = (string)propertyInfo.GetValue(model); var decrypted = _cryptoService.Decrypt(rawPropertyValue, keySeed, null); propertyInfo.SetValue(model, decrypted); } } private static IEnumerable<PropertyInfo> GetSecureProperties(object model) { var type = model.GetType(); var secureProperties = type.GetRuntimeProperties() .Where(pi => pi.PropertyType == typeof(string) && pi.GetCustomAttributes<Secure>(true).Any()); return secureProperties; } private void DecryptList<T>(List<T> list, string keySeed) { foreach (var item in list) Decrypt(item, keySeed); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Version.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System { sealed public partial class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version> { #region Methods and constructors public static bool operator != (System.Version v1, System.Version v2) { Contract.Ensures(Contract.Result<bool>() == ((v1.Equals(v2)) == false)); return default(bool); } public static bool operator < (System.Version v1, System.Version v2) { return default(bool); } public static bool operator <=(System.Version v1, System.Version v2) { return default(bool); } public static bool operator == (System.Version v1, System.Version v2) { return default(bool); } public static bool operator > (System.Version v1, System.Version v2) { return default(bool); } public static bool operator >= (System.Version v1, System.Version v2) { return default(bool); } public Object Clone() { return default(Object); } public int CompareTo(Object version) { return default(int); } public int CompareTo(System.Version value) { return default(int); } public override bool Equals(Object obj) { return default(bool); } public bool Equals(System.Version obj) { return default(bool); } public override int GetHashCode() { return default(int); } #if !SILVERLIGHT_4_0_WP && !SILVERLIGHT_3_0 && !NETFRAMEWORK_3_5 public static System.Version Parse(string input) { return default(System.Version); } #endif public override string ToString() { return default(string); } public string ToString(int fieldCount) { Contract.Requires(fieldCount >= 0); Contract.Requires(fieldCount <= 4); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()) || fieldCount == 0); return default(string); } #if !SILVERLIGHT_4_0_WP && !SILVERLIGHT_3_0 && !NETFRAMEWORK_3_5 public static bool TryParse(string input, out System.Version result) { result = default(System.Version); return default(bool); } #endif public Version(int major, int minor, int build, int revision) { } public Version(int major, int minor, int build) { } #if SILVERLIGHT internal #else public #endif Version() { } public Version(string version) { } public Version(int major, int minor) { } #endregion #region Properties and indexers public int Build { get { return default(int); } } public int Major { get { return default(int); } } #if NETFRAMEWORK_4_0 public short MajorRevision { get { return default(short); } } public short MinorRevision { get { Contract.Ensures(0 <= Contract.Result<short>()); return default(short); } } #endif public int Minor { get { return default(int); } } public int Revision { get { return default(int); } } #endregion } }
using System; using System.Windows.Forms; using System.Collections; using System.Drawing; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Phrase Search /// </summary> public class PhraseSearch : Search { //Search parameters private ArrayList m_Graphemes; //list of graphemes for useable phrases private bool m_ParaFmt; //how to display results private bool m_UseGraphemesTaught; //Restrict to graphemes taught private string m_Highlight; //phrases containing this grapheme are highligted private string m_Restiction; //only phrases with this grapheme are displayed private int m_Min; //minimal numbers of words in a phrase private string m_Title; private Settings m_Settings; private GraphemeInventory m_GI; private GraphemeTaughtOrder m_GraphemesTaught; private Font m_DefaultFont; private bool m_ViewParaSentWord; //Search Definition tags private const string kGrapheme = "grapheme"; private const string kParaFormat = "paraformat"; private const string kUseGraphemeTaught = "UseGraphemeTaught"; private const string kHighlight = "highlight"; private const string kRestriction = "restriction"; private const string kMin = "minwords"; //private const string kTitle = "Usable Phrases Search"; //private const string kSearch = "Processing Usable Phrases Search"; private const string kSeparator = Constants.Tab; public PhraseSearch(int number, Settings s) : base(number, SearchDefinition.kPhrases) { m_Graphemes = null; m_ParaFmt = false; m_UseGraphemesTaught = false; m_Highlight = ""; m_Restiction = ""; m_Min = 0; m_Settings = s; m_Title = m_Settings.LocalizationTable.GetMessage("PhraseSearchT"); if (m_Title == "") m_Title = "Usable Phrases Search"; m_GI = m_Settings.GraphemeInventory; m_GraphemesTaught = m_Settings.GraphemesTaught; m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); } public ArrayList Graphemes { get { return m_Graphemes; } set { m_Graphemes = value; } } public bool ParaFormat { get { return m_ParaFmt; } set { m_ParaFmt = value; } } public bool UseGraphemesTaught { get { return m_UseGraphemesTaught; } set { m_UseGraphemesTaught = value; } } public string Highlight { get { return m_Highlight; } set { m_Highlight = value; } } public string Restriction { get { return m_Restiction; } set { m_Restiction = value; } } public int Min { get { return m_Min; } set { m_Min = value; } } public string Title { get { return m_Title; } set { m_Title = value; } } public GraphemeInventory GI { get { return m_GI; } } public GraphemeTaughtOrder GraphemesTaught { get { return m_GraphemesTaught; } } public bool ViewParaSentWord { get { return m_ViewParaSentWord; } } public Font DefaultFont { get { return m_DefaultFont; } } public bool SetupSearch() { bool flag = false; string strMsg = ""; FormPhrase form = new FormPhrase(m_GraphemesTaught, m_DefaultFont, m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.Graphemes = form.Graphemes; this.ParaFormat = form.ParaFormat; this.UseGraphemesTaught = form.UseGraphemesTaught; this.Highlight = form.Highlight; this.Restriction = form.Restriction; this.Min = form.Min; if (this.Graphemes != null) { if ((this.Highlight == "") || (this.GI.IsInInventory(this.Highlight))) { if ((this.Restriction == "") || (this.GI.IsInInventory(this.Restriction))) { SearchDefinition sd = new SearchDefinition(SearchDefinition.kPhrases); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; string strSym = ""; string strSegs = ""; for (int i = 0; i < this.Graphemes.Count; i++) { strSym = this.Graphemes[i].ToString(); sdp = new SearchDefinitionParm(PhraseSearch.kGrapheme, strSym); sd.AddSearchParm(sdp); strSegs += strSym + Constants.Space; } if (this.ParaFormat) { sdp = new SearchDefinitionParm(PhraseSearch.kParaFormat); sd.AddSearchParm(sdp); } if (this.UseGraphemesTaught) { sdp = new SearchDefinitionParm(PhraseSearch.kUseGraphemeTaught); sd.AddSearchParm(sdp); } sdp = new SearchDefinitionParm(PhraseSearch.kHighlight, this.Highlight); sd.AddSearchParm(sdp); sdp = new SearchDefinitionParm(PhraseSearch.kRestriction, this.Restriction); sd.AddSearchParm(sdp); sdp = new SearchDefinitionParm(PhraseSearch.kMin, this.Min.ToString()); sd.AddSearchParm(sdp); m_Title = m_Title + " - [" + strSegs.Trim() + "]"; this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("Restriction grapheme " + this.Restriction + "is not in Inventory"); else { strMsg = m_Settings.LocalizationTable.GetMessage("PhraseSearch4"); if (strMsg == "") strMsg = "Restriction grapheme is not in Inventory"; MessageBox.Show(strMsg + ":" + this.Restriction); } } //else MessageBox.Show("Highlight grapheme " + this.Highlight + " is not in inventory"); else { strMsg = m_Settings.LocalizationTable.GetMessage("PhraseSearch1"); if (strMsg == "") strMsg = "Highlight grapheme is not in inventory"; MessageBox.Show(strMsg + ": " + this.Highlight); } } //else MessageBox.Show("Must specified at least one grapheme"); else { strMsg = m_Settings.LocalizationTable.GetMessage("PhraseSearch2"); if (strMsg == "") strMsg = "Must specified at least one grapheme"; MessageBox.Show(strMsg); } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; SearchDefinitionParm sdp = null; string strTag = ""; string strContent = ""; string strGrfs = ""; this.SearchDefinition = sd; ArrayList al = new ArrayList(); for (int i = 0; i < sd.SearchParmsCount(); i++) { sdp = sd.GetSearchParmAt(i); strTag = sdp.GetTag(); strContent = sdp.GetContent(); if (strTag == PhraseSearch.kGrapheme) { al.Add(strContent); strGrfs += strContent + Constants.Space; } if (strTag == PhraseSearch.kParaFormat) this.ParaFormat = true; if (strTag == PhraseSearch.kUseGraphemeTaught) this.UseGraphemesTaught = true; if (strTag == PhraseSearch.kHighlight) { this.Highlight = strContent; } if (strTag == PhraseSearch.kRestriction) { this.Restriction = strContent; } if (strTag == PhraseSearch.kMin) { this.Min = Convert.ToInt32(strContent); } } this.Graphemes = al; flag = true; m_Title = m_Title + " - [" + strGrfs.Trim() + "]"; return flag; } public string BuildResults() { string strText = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); string str = ""; strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser + Environment.NewLine; return strText; } public PhraseSearch ExecutePhraseSearch(TextData td) { if (this.ParaFormat) ExecutePhraseSearchP(td); else ExecutePhraseSearchL(td); return this; } private PhraseSearch ExecutePhraseSearchP(TextData td) { int nCount = 0; string strRslt = ""; string strText = ""; Paragraph para = null; Sentence sent = null; Word wrd = null; int nPara = td.ParagraphCount(); //FormProgressBar form = new FormProgressBar("Processing Usable Phrases Search"); strText = m_Settings.LocalizationTable.GetMessage("PhraseSearch3"); if (strText == "") strText = "Processing Usable Phrases Search"; FormProgressBar form = new FormProgressBar(strText); form.PB_Init(0, nPara); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); int nSent = para.SentenceCount(); for (int j = 0; j < nSent; j++) { sent = para.GetSentence(j); int nWord = sent.WordCount(); string strMatch = ""; int nSize = 0; for (int k = 0; k < nWord; k++) { wrd = sent.GetWord(k); if (wrd == null) break; else { if (wrd.IsBuildableWord(this.Graphemes)) { strMatch += wrd.DisplayWord + Constants.Space; nSize++; } else { if (nSize > (this.Min - 1)) { strRslt += Constants.kHCOn + strMatch.Trim() + Constants.kHCOff + Constants.Space + wrd.DisplayWord + Constants.Space; nSize = 0; strMatch = ""; nCount++; } else { if (strMatch != "") strRslt += strMatch.Trim() + Constants.Space + wrd.DisplayWord + Constants.Space; else strRslt += wrd.DisplayWord + Constants.Space; strMatch = ""; nSize = 0; } } } } if (nSize > 0) { if (nSize > (this.Min - 1)) { strRslt += Constants.kHCOn + strMatch.Trim() + Constants.kHCOff + Constants.Space; nCount++; } else { strRslt += strMatch.Trim() + Constants.Space; } } strRslt = strRslt.Substring(0, strRslt.Length - 1); //get ride of last space strRslt += sent.EndingPunctuation; strRslt += Constants.Space; } strRslt += Environment.NewLine + Environment.NewLine; } form.Close(); this.SearchResults = strRslt; this.SearchCount = nCount; return this; } private PhraseSearch ExecutePhraseSearchL(TextData td) { int nCount = 0; string strRslt = ""; string strText = ""; Paragraph para = null; Sentence sent = null; Word wrd = null; int nPara = td.ParagraphCount(); //FormProgressBar form = new FormProgressBar("Processing Usable Phrases Search"); strText = m_Settings.LocalizationTable.GetMessage("PhraseSearch3"); if (strText == "") strText = "Processing Usable Phrases Search"; FormProgressBar form = new FormProgressBar(strText); form.PB_Init(0, nPara); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); int nSent = para.SentenceCount(); for (int j = 0; j < nSent; j++) { sent = para.GetSentence(j); int nWord = sent.WordCount(); string strMatch = ""; bool fHighlight = false; bool fRestriction = false; int nSize = 0; int nTmp = 0; for (int k = 0; k < nWord; k++) { wrd = sent.GetWord(k); if (wrd.IsBuildableWord(this.Graphemes)) { if ((this.Highlight.Trim() == "") && (this.Restriction.Trim() == "")) strMatch += wrd.DisplayWord + Constants.Space; else { if (this.Highlight.Trim() != "") { if (wrd.ContainInWord(this.Highlight.Trim())) fHighlight = true; strMatch += wrd.DisplayWord + Constants.Space; } else if (this.Restriction.Trim() != "") { if (wrd.ContainInWord(this.Restriction.Trim())) fRestriction = true; strMatch += wrd.DisplayWord + Constants.Space; } } nSize++; } else { if (nSize > (this.Min - 1)) { if ((this.ViewParaSentWord) && (!fRestriction)) { nTmp = i + 1; strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; nTmp = j + 1; strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; nTmp = k + 1 - nSize; strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; } if (this.Highlight.Trim() != "") { if (fHighlight) strRslt += Constants.kHCOn + strMatch.Trim() + Constants.kHCOff; else strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } if (this.Restriction.Trim() != "") { if (fRestriction) { strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } } if ((this.Highlight.Trim() == "") && (this.Restriction.Trim() == "")) { strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } nSize = 0; strMatch = ""; fHighlight = false; fRestriction = false; } else { nSize = 0; strMatch = ""; fHighlight = false; fRestriction = false; } } } if (nSize > 0) { if (nSize > (this.Min - 1)) { if (this.ViewParaSentWord) { nTmp = i + 1; strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; nTmp = j + 1; strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; nTmp = nWord + 1 - nSize; strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += PhraseSearch.kSeparator; } if (this.Highlight.Trim() != "") { if (fHighlight) strRslt += Constants.kHCOn + strMatch.Trim() + Constants.kHCOff; else strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } if (this.Restriction.Trim() != "") { if (fRestriction) { strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } } if ((this.Highlight.Trim() == "") && (this.Restriction.Trim() == "")) { strRslt += strMatch.Trim(); nCount++; strRslt += Environment.NewLine; } } } } } this.SearchResults = strRslt; this.SearchCount = nCount; form.Close(); return this; } } }
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using Microsoft.Samples.CodeDomTestSuite; using Microsoft.VisualBasic; using Microsoft.JScript; public class ConstructorTest : CodeDomTestTree { public override TestTypes TestType { get { return TestTypes.Everett; } } public override bool ShouldVerify { get { return true; } } public override bool ShouldCompile { get { return true; } } public override string Name { get { return "ConstructorTest"; } } public override string Description { get { return "Tests constructors."; } } public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // create a namespace CodeNamespace ns = new CodeNamespace ("NS"); ns.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (ns); // create a class that will be used to test the constructors of other classes CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "Test"; class1.IsClass = true; ns.Types.Add (class1); CodeMemberMethod cmm; // construct a method to test class with chained public constructors // GENERATES (C#): // public static string TestingMethod1() { // Test2 t = new Test2(); // return t.accessStringField; // } if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { AddScenario ("CheckTestingMethod01"); cmm = new CodeMemberMethod (); cmm.Name = "TestingMethod1"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); class1.Members.Add (cmm); } // construct a method to test class with base public constructor // GENERATES (C#): // public static string TestingMethod2() { // Test3 t = new Test3(); // return t.accessStringField; // } AddScenario ("CheckTestingMethod02"); cmm = new CodeMemberMethod (); cmm.Name = "TestingMethod2"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test3", "t", new CodeObjectCreateExpression ("Test3"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); class1.Members.Add (cmm); // construct a method to test class with internal constructor // GENERATES (C#): // public static int TestInternalConstruct(int a) { // ClassWInternalConstruct t = new ClassWInternalConstruct(); // t.i = a; // return t.i; // } CodeParameterDeclarationExpression param = null; #if !WHIDBEY // Everett VB compiler doesn't like this construct if (!(provider is VBCodeProvider)) { #endif AddScenario ("CheckTestInternalConstruct"); cmm = new CodeMemberMethod (); cmm.Name = "TestInternalConstruct"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWInternalConstruct", "t", new CodeObjectCreateExpression ("ClassWInternalConstruct"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); class1.Members.Add (cmm); #if !WHIDBEY } #endif // construct a method to test class with static constructor // GENERATES (C#): // public static int TestStaticConstructor(int a) { // Test4 t = new Test4(); // t.i = a; // return t.i; // } if (Supports (provider, GeneratorSupport.StaticConstructors)) { AddScenario ("CheckTestStaticConstructor"); cmm = new CodeMemberMethod (); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); class1.Members.Add (cmm); } // *** second class, tests chained, public constructors *** // GENERATES (C#): // public class Test2 { // private string stringField; // public Test2() : // this("testingString", null, null) { // } // public Test2(String p1, String p2, String p3) { // this.stringField = p1; // } // public string accessStringField { // get { // return this.stringField; // } // set { // this.stringField = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test2"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (String)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeConstructor cctor; if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); } CodeConstructor cc = new CodeConstructor (); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p1")); cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p2")); cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p3")); cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression () , "stringField"), new CodeArgumentReferenceExpression ("p1"))); class1.Members.Add (cc); // **** third class tests base constructors **** // GENERATES (C#): // public class Test3 : Test2 { // public Test3() : // base("testingString", null, null) { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test3"; class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("Test2")); ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); if (Supports (provider, GeneratorSupport.StaticConstructors)) { // *** fourth class tests static constructors **** // GENERATES (C#): // public class Test4 { // private int number; // static Test4() { // } // public int i { // get { // return number; // } // set { // number = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "Test4"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeTypeConstructor ctc = new CodeTypeConstructor (); class1.Members.Add (ctc); } // ******* class tests internal constructors ********** // GENERATES (C#): // public class ClassWInternalConstruct { // private int number; // /*FamANDAssem*/ internal ClassWInternalConstruct() { // } // public int i { // get { // return number; // } // set { // number = value; // } // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWInternalConstruct"; class1.IsClass = true; ns.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); if (!(provider is JScriptCodeProvider)) { cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.FamilyOrAssembly; class1.Members.Add (cctor); } // ******** class tests private constructors ********** // GENERATES (C#): // public class ClassWPrivateConstruct { // static int number; // private ClassWPrivateConstruct() { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWPrivateConstruct"; class1.IsClass = true; ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Private; class1.Members.Add (cctor); // ******* class tests protected constructors ************** // GENERATES (C#): // public class ClassWProtectedConstruct { // protected ClassWProtectedConstruct() { // } // } class1 = new CodeTypeDeclaration (); class1.Name = "ClassWProtectedConstruct"; class1.IsClass = true; ns.Types.Add (class1); cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Family; class1.Members.Add (cctor); // class that inherits protected constructor // GENERATES (C#): // public class InheritsProtectedConstruct : ClassWProtectedConstruct { // } class1 = new CodeTypeDeclaration (); class1.Name = "InheritsProtectedConstruct"; class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("ClassWProtectedConstruct")); ns.Types.Add (class1); } public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) { object genObject; Type genType; AddScenario ("InstantiateTest", "Find and instantiate Test."); if (!FindAndInstantiate ("NS.Test", asm, out genObject, out genType)) return; VerifyScenario ("InstantiateTest"); if (Supports (provider, GeneratorSupport.ChainedConstructorArguments) && VerifyMethod (genType, genObject, "TestingMethod1", new object[] {}, "testingString")) { VerifyScenario ("CheckTestingMethod01"); } if (VerifyMethod (genType, genObject, "TestingMethod2", new object[] {}, "testingString")) { VerifyScenario ("CheckTestingMethod02"); } if (Supports (provider, GeneratorSupport.StaticConstructors)) { if (VerifyMethod (genType, genObject, "TestStaticConstructor", new object[] {7}, 7)) { VerifyScenario ("CheckTestStaticConstructor"); } } #if !WHIDBEY if (!(provider is VBCodeProvider)) { #endif if (VerifyMethod (genType, genObject, "TestInternalConstruct", new object[] {7}, 7)) { VerifyScenario ("CheckTestInternalConstruct"); } #if !WHIDBEY } #endif if (FindType ("ClassWPrivateConstruct", asm, out genType)) { // should be empty if (genType.GetConstructors ().Length <= 0) VerifyScenario ("ClassWPrivateConstruct"); } if (FindType ("ClassWProtectedConstruct", asm, out genType)) { // should be empty if (genType.GetConstructors ().Length <= 0) VerifyScenario ("ClassWProtectedConstruct"); } } }
// 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.Logic { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// IntegrationAccountPartnersOperations operations. /// </summary> internal partial class IntegrationAccountPartnersOperations : IServiceOperations<LogicManagementClient>, IIntegrationAccountPartnersOperations { /// <summary> /// Initializes a new instance of the IntegrationAccountPartnersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal IntegrationAccountPartnersOperations(LogicManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of integration account partners. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IntegrationAccountPartner>>> ListWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountPartnerFilter> odataQuery = default(ODataQuery<IntegrationAccountPartnerFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } string apiVersion = "2015-08-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IntegrationAccountPartner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<IntegrationAccountPartner>>(_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> /// Gets an integration account partner. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='partnerName'> /// The integration account partner name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IntegrationAccountPartner>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (partnerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "partnerName"); } string apiVersion = "2015-08-01-preview"; // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("partnerName", partnerName); tracingParameters.Add("apiVersion", apiVersion); 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.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{partnerName}", Uri.EscapeDataString(partnerName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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<IntegrationAccountPartner>(); _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<IntegrationAccountPartner>(_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> /// Creates or updates an integration account partner. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='partnerName'> /// The integration account partner name. /// </param> /// <param name='partner'> /// The integration account partner. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IntegrationAccountPartner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, IntegrationAccountPartner partner, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (partnerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "partnerName"); } if (partner == null) { throw new ValidationException(ValidationRules.CannotBeNull, "partner"); } string apiVersion = "2015-08-01-preview"; // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("partnerName", partnerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("partner", partner); 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.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{partnerName}", Uri.EscapeDataString(partnerName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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(partner != null) { _requestContent = SafeJsonConvert.SerializeObject(partner, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IntegrationAccountPartner>(); _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<IntegrationAccountPartner>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IntegrationAccountPartner>(_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 an integration account partner. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='partnerName'> /// The integration account partner name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (partnerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "partnerName"); } string apiVersion = "2015-08-01-preview"; // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("partnerName", partnerName); tracingParameters.Add("apiVersion", apiVersion); 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.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{partnerName}", Uri.EscapeDataString(partnerName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of integration account partners. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IntegrationAccountPartner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IntegrationAccountPartner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<IntegrationAccountPartner>>(_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; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using SDRSharp.Radio; namespace SDRSharp.PanView { public class SpectrumAnalyzer : UserControl { private const float TrackingFontSize = 16.0f; private const int AxisMargin = 30; private const int CarrierPenWidth = 1; private const int GradientAlpha = 180; public const float DefaultCursorHeight = 32.0f; private readonly static Color _spectrumColor = Utils.GetColorSetting("spectrumAnalyzerColor", Color.DarkGray); private readonly static bool _fillSpectrumAnalyzer = Utils.GetBooleanSetting("fillSpectrumAnalyzer"); private float _attack; private float _decay; private bool _performNeeded; private bool _drawBackgroundNeeded; private byte[] _scaledSpectrum; private float[] _smoothedSpectrum; private float[] _temp; private bool[] _peaks; private Bitmap _bkgBuffer; private Bitmap _buffer; private Graphics _graphics; private long _spectrumWidth; private long _centerFrequency; private long _displayCenterFrequency; private Point[] _points; private BandType _bandType; private int _filterBandwidth; private int _filterOffset; private int _stepSize = 1000; private float _xIncrement; private long _frequency; private float _lower; private float _upper; private int _zoom; private float _scale = 1f; private int _oldX; private int _trackingX; private int _trackingY; private long _trackingFrequency; private int _oldFilterBandwidth; private long _oldFrequency; private long _oldCenterFrequency; private bool _changingBandwidth; private bool _changingFrequency; private bool _changingCenterFrequency; private bool _useSmoothing; private bool _enableFilter = true; private bool _hotTrackNeeded; private bool _useSnap; private bool _markPeaks; private float _trackingPower; private string _statusText; private int _displayRange = 130; private int _displayOffset; private LinearGradientBrush _gradientBrush; private ColorBlend _gradientColorBlend = Utils.GetGradientBlend(GradientAlpha, "spectrumAnalyzerGradient"); public SpectrumAnalyzer() { var length = ClientRectangle.Width - 2 * AxisMargin; _smoothedSpectrum = new float[length]; _scaledSpectrum = new byte[length]; _temp = new float[length]; var defaultLevel = - (_displayOffset + _displayRange); for (var i = 0; i < length; i++) { _smoothedSpectrum[i] = defaultLevel; } _bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _graphics = Graphics.FromImage(_buffer); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); UpdateStyles(); } ~SpectrumAnalyzer() { _buffer.Dispose(); _graphics.Dispose(); _gradientBrush.Dispose(); } public event ManualFrequencyChange FrequencyChanged; public event ManualFrequencyChange CenterFrequencyChanged; public event ManualBandwidthChange BandwidthChanged; public int SpectrumWidth { get { return (int) _spectrumWidth; } set { if (_spectrumWidth != value) { _spectrumWidth = value; ApplyZoom(); } } } public int FilterBandwidth { get { return _filterBandwidth; } set { if (_filterBandwidth != value) { _filterBandwidth = value; _performNeeded = true; } } } public int FilterOffset { get { return _filterOffset; } set { if (_filterOffset != value) { _filterOffset = value; _performNeeded = true; } } } public BandType BandType { get { return _bandType; } set { if (_bandType != value) { _bandType = value; _performNeeded = true; } } } public long Frequency { get { return _frequency; } set { if (_frequency != value) { _frequency = value; _performNeeded = true; } } } public long CenterFrequency { get { return _centerFrequency; } set { if (_centerFrequency != value) { _displayCenterFrequency += value - _centerFrequency; _centerFrequency = value; _drawBackgroundNeeded = true; } } } public int DisplayRange { get { return _displayRange; } set { if (_displayRange != value) { _displayRange = value; _drawBackgroundNeeded = true; } } } public int DisplayOffset { get { return _displayOffset; } set { if (_displayOffset != value) { _displayOffset = value; _drawBackgroundNeeded = true; } } } public int Zoom { get { return _zoom; } set { if (_zoom != value) { _zoom = value; ApplyZoom(); } } } public bool UseSmoothing { get { return _useSmoothing; } set { _useSmoothing = value; } } public bool EnableFilter { get { return _enableFilter; } set { _enableFilter = value; _performNeeded = true; } } public string StatusText { get { return _statusText; } set { _statusText = value; _performNeeded = true; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ColorBlend GradientColorBlend { get { return _gradientColorBlend; } set { _gradientColorBlend = new ColorBlend(value.Colors.Length); for (var i = 0; i < value.Colors.Length; i++) { _gradientColorBlend.Colors[i] = Color.FromArgb(GradientAlpha, value.Colors[i]); _gradientColorBlend.Positions[i] = value.Positions[i]; } _gradientBrush.Dispose(); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; _drawBackgroundNeeded = true; } } public float Attack { get { return _attack; } set { _attack = value; } } public float Decay { get { return _decay; } set { _decay = value; } } public int StepSize { get { return _stepSize; } set { if (_stepSize != value) { _stepSize = value; _drawBackgroundNeeded = true; _performNeeded = true; } } } public bool UseSnap { get { return _useSnap; } set { _useSnap = value; } } public bool MarkPeaks { get { return _markPeaks; } set { _markPeaks = value; } } private void ApplyZoom() { _scale = (float) Math.Pow(10, _zoom * Waterfall.MaxZoom / 100.0f); if (_spectrumWidth > 0) { _displayCenterFrequency = GetDisplayCenterFrequency(); _xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth; _drawBackgroundNeeded = true; } } public void CenterZoom() { _displayCenterFrequency = GetDisplayCenterFrequency(); } private long GetDisplayCenterFrequency() { var f = _frequency; switch (_bandType) { case BandType.Lower: f -= _filterBandwidth / 2 + _filterOffset; break; case BandType.Upper: f += _filterBandwidth / 2 + _filterOffset; break; } var lowerLeadingSpectrum = (long) ((_centerFrequency - _spectrumWidth / 2) - (f - _spectrumWidth / _scale / 2)); if (lowerLeadingSpectrum > 0) { f += lowerLeadingSpectrum + 10; } var upperLeadingSpectrum = (long) ((f + _spectrumWidth / _scale / 2) - (_centerFrequency + _spectrumWidth / 2)); if (upperLeadingSpectrum > 0) { f -= upperLeadingSpectrum + 10; } return f; } public void Perform() { if (_drawBackgroundNeeded) { DrawBackground(); } if (_performNeeded || _drawBackgroundNeeded) { DrawForeground(); Invalidate(); } _performNeeded = false; _drawBackgroundNeeded = false; } private void DrawCursor() { _lower = 0f; float bandpassOffset; var bandpassWidth = 0f; var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2); var xCarrier = (float) ClientRectangle.Width / 2 + (_frequency - _displayCenterFrequency) * _xIncrement; switch (_bandType) { case BandType.Upper: bandpassOffset = _filterOffset * _xIncrement; bandpassWidth = cursorWidth - bandpassOffset; _lower = xCarrier + bandpassOffset; break; case BandType.Lower: bandpassOffset = _filterOffset * _xIncrement; bandpassWidth = cursorWidth - bandpassOffset; _lower = xCarrier - bandpassOffset - bandpassWidth; break; case BandType.Center: _lower = xCarrier - cursorWidth / 2; bandpassWidth = cursorWidth; break; } _upper = _lower + bandpassWidth; using (var transparentBackground = new SolidBrush(Color.FromArgb(80, Color.DarkGray))) using (var redPen = new Pen(Color.Red)) using (var graphics = Graphics.FromImage(_buffer)) using (var fontFamily = new FontFamily("Arial")) using (var path = new GraphicsPath()) using (var outlinePen = new Pen(Color.Black)) { if (_enableFilter && cursorWidth < ClientRectangle.Width) { var carrierPen = redPen; carrierPen.Width = CarrierPenWidth; graphics.FillRectangle(transparentBackground, (int) _lower + 1, 0, (int) bandpassWidth, ClientRectangle.Height); if (xCarrier >= AxisMargin && xCarrier <= ClientRectangle.Width - AxisMargin) { graphics.DrawLine(carrierPen, xCarrier, 0f, xCarrier, ClientRectangle.Height); } } if (_markPeaks && _spectrumWidth > 0) { var windowSize = (int) bandpassWidth; windowSize = Math.Max(windowSize, 10); windowSize = Math.Min(windowSize, _scaledSpectrum.Length); PeakDetector.GetPeaks(_scaledSpectrum, _peaks, windowSize); var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue; for (var i = 0; i < _peaks.Length; i++) { if (_peaks[i]) { var y = (int) (ClientRectangle.Height - AxisMargin - _scaledSpectrum[i] * yIncrement); var x = i + AxisMargin; graphics.DrawEllipse(Pens.Yellow, x - 5, y - 5, 10, 10); } } } if (_hotTrackNeeded && _trackingX >= AxisMargin && _trackingX <= ClientRectangle.Width - AxisMargin && _trackingY >= AxisMargin && _trackingY <= ClientRectangle.Height - AxisMargin) { if (_scaledSpectrum != null && !_changingFrequency && !_changingCenterFrequency && !_changingBandwidth) { var index = _trackingX - AxisMargin; if (_useSnap) { // Todo: snap the index } if (index > 0 && index < _scaledSpectrum.Length) { graphics.DrawLine(redPen, _trackingX, 0, _trackingX, ClientRectangle.Height); } } string fstring; if (_changingFrequency) { fstring = "VFO = " + GetFrequencyDisplay(_frequency); } else if (_changingBandwidth) { fstring = "BW = " + GetFrequencyDisplay(_filterBandwidth); } else if (_changingCenterFrequency) { fstring = "Center Freq. = " + GetFrequencyDisplay(_centerFrequency); } else { fstring = string.Format("{0}\r\n{1:0.##}dB", GetFrequencyDisplay(_trackingFrequency), _trackingPower); } path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, Point.Empty, StringFormat.GenericTypographic); var stringSize = path.GetBounds(); var currentCursor = Cursor.Current; var xOffset = _trackingX + 15.0f; var yOffset = _trackingY + (currentCursor == null ? DefaultCursorHeight : currentCursor.Size.Height) - 8.0f; xOffset = Math.Min(xOffset, ClientRectangle.Width - stringSize.Width - 5); yOffset = Math.Min(yOffset, ClientRectangle.Height - stringSize.Height - 5); path.Reset(); path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, new Point((int)xOffset, (int)yOffset), StringFormat.GenericTypographic); var smoothingMode = graphics.SmoothingMode; var interpolationMode = graphics.InterpolationMode; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; outlinePen.Width = 2; graphics.DrawPath(outlinePen, path); graphics.FillPath(Brushes.White, path); graphics.SmoothingMode = smoothingMode; graphics.InterpolationMode = interpolationMode; } } } public unsafe void Render(float* powerSpectrum, int length) { var offset = (float) (_displayCenterFrequency - _centerFrequency) / (float) _spectrumWidth; ExtractSpectrum(powerSpectrum, length, offset, _scale, _useSmoothing); _performNeeded = true; } private unsafe void ExtractSpectrum(float* powerSpectrum, int length, float offset, float scale, bool useSmoothing) { var displayOffset = _displayOffset / 10 * 10; var displayRange = _displayRange / 10 * 10; fixed (float* temp = _temp) fixed (float* smoothedSpectrum = _smoothedSpectrum) fixed (byte* scaledSpectrum = _scaledSpectrum) { Fourier.SmoothCopy(powerSpectrum, temp, length, _smoothedSpectrum.Length, scale, offset); if (useSmoothing) { for (var i = 0; i < _temp.Length; i++) { var ratio = smoothedSpectrum[i] < temp[i] ? Attack : Decay; smoothedSpectrum[i] = smoothedSpectrum[i] * (1 - ratio) + temp[i] * ratio; } } else { Utils.Memcpy(smoothedSpectrum, temp, _smoothedSpectrum.Length * sizeof(float)); } Fourier.ScaleFFT(smoothedSpectrum, scaledSpectrum, _smoothedSpectrum.Length, displayOffset - displayRange, displayOffset); } } private void DrawBackground() { using (var fontBrush = new SolidBrush(Color.Silver)) using (var gridPen = new Pen(Color.FromArgb(80, 80, 80))) using (var axisPen = new Pen(Color.DarkGray)) using (var font = new Font("Arial", 8f)) using (var graphics = Graphics.FromImage(_bkgBuffer)) { ConfigureGraphics(graphics); // Background graphics.Clear(Color.Black); if (_spectrumWidth > 0) { #region Frequency markers var baseLabelLength = (int)graphics.MeasureString("1,000,000.000kHz", font).Width; var frequencyStep = (int)(_spectrumWidth / _scale * baseLabelLength / (ClientRectangle.Width - 2 * AxisMargin)); int stepSnap = _stepSize; frequencyStep = frequencyStep / stepSnap * stepSnap + stepSnap; var lineCount = (int)(_spectrumWidth / _scale / frequencyStep) + 4; var xIncrement = (ClientRectangle.Width - 2.0f * AxisMargin) * frequencyStep * _scale / _spectrumWidth; var centerShift = (int)((_displayCenterFrequency % frequencyStep) * (ClientRectangle.Width - 2.0 * AxisMargin) * _scale / _spectrumWidth); for (var i = -lineCount / 2; i < lineCount / 2; i++) { var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift; if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin) { graphics.DrawLine(gridPen, x, AxisMargin, x, ClientRectangle.Height - AxisMargin); } } for (var i = -lineCount / 2; i < lineCount / 2; i++) { var frequency = _displayCenterFrequency + i * frequencyStep - _displayCenterFrequency % frequencyStep; var fstring = GetFrequencyDisplay(frequency); var sizeF = graphics.MeasureString(fstring, font); var width = sizeF.Width; var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift; if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin) { x -= width / 2f; graphics.DrawString(fstring, font, fontBrush, x, ClientRectangle.Height - AxisMargin + 8f); } } #endregion } #region Grid gridPen.DashStyle = DashStyle.Dash; var powerMarkerCount = _displayRange / 10; // Power axis var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) powerMarkerCount; for (var i = 1; i <= powerMarkerCount; i++) { graphics.DrawLine(gridPen, AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement), ClientRectangle.Width - AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement)); } var displayOffset = _displayOffset / 10 * 10; for (var i = 0; i <= powerMarkerCount; i++) { var db = (displayOffset - (powerMarkerCount - i) * 10).ToString(); var sizeF = graphics.MeasureString(db, font); var width = sizeF.Width; var height = sizeF.Height; graphics.DrawString(db, font, fontBrush, AxisMargin - width - 3, ClientRectangle.Height - AxisMargin - i * yIncrement - height / 2f); } // Axis graphics.DrawLine(axisPen, AxisMargin, AxisMargin, AxisMargin, ClientRectangle.Height - AxisMargin); graphics.DrawLine(axisPen, AxisMargin, ClientRectangle.Height - AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin); #endregion } } public static string GetFrequencyDisplay(long frequency) { string result; if (frequency == 0) { result = "DC"; } else if (Math.Abs(frequency) > 1500000000) { result = string.Format("{0:#,0.000 000}GHz", frequency / 1000000000.0); } else if (Math.Abs(frequency) > 30000000) { result = string.Format("{0:0,0.000#}MHz", frequency / 1000000.0); } else if (Math.Abs(frequency) > 1000) { result = string.Format("{0:#,#.###}kHz", frequency / 1000.0); } else { result = string.Format("{0}Hz", frequency); } return result; } public static void ConfigureGraphics(Graphics graphics) { graphics.CompositingMode = CompositingMode.SourceOver; graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.SmoothingMode = SmoothingMode.None; graphics.PixelOffsetMode = PixelOffsetMode.HighSpeed; graphics.InterpolationMode = InterpolationMode.High; } private void DrawForeground() { if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin) { return; } CopyBackground(); DrawSpectrum(); DrawStatusText(); DrawCursor(); } private unsafe void CopyBackground() { var data1 = _buffer.LockBits(ClientRectangle, ImageLockMode.WriteOnly, _buffer.PixelFormat); var data2 = _bkgBuffer.LockBits(ClientRectangle, ImageLockMode.ReadOnly, _bkgBuffer.PixelFormat); Utils.Memcpy((void*) data1.Scan0, (void*) data2.Scan0, Math.Abs(data1.Stride) * data1.Height); _buffer.UnlockBits(data1); _bkgBuffer.UnlockBits(data2); } private void DrawSpectrum() { if (_scaledSpectrum == null || _scaledSpectrum.Length == 0) { return; } var xIncrement = (ClientRectangle.Width - 2 * AxisMargin) / (float) _scaledSpectrum.Length; var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue; using (var spectrumPen = new Pen(_spectrumColor)) { for (var i = 0; i < _scaledSpectrum.Length; i++) { var strenght = _scaledSpectrum[i]; var x = (int) (AxisMargin + i * xIncrement); var y = (int) (ClientRectangle.Height - AxisMargin - strenght * yIncrement); _points[i + 1].X = x; _points[i + 1].Y = y; } if (_fillSpectrumAnalyzer) { _points[0].X = AxisMargin; _points[0].Y = ClientRectangle.Height - AxisMargin + 1; _points[_points.Length - 1].X = ClientRectangle.Width - AxisMargin; _points[_points.Length - 1].Y = ClientRectangle.Height - AxisMargin + 1; _graphics.FillPolygon(_gradientBrush, _points); } _points[0] = _points[1]; _points[_points.Length - 1] = _points[_points.Length - 2]; _graphics.DrawLines(spectrumPen, _points); } } private void DrawStatusText() { if (string.IsNullOrEmpty(_statusText)) { return; } using (var font = new Font("Lucida Console", 9)) { _graphics.DrawString(_statusText, font, Brushes.White, AxisMargin, 10); } } protected override void OnPaint(PaintEventArgs e) { ConfigureGraphics(e.Graphics); e.Graphics.DrawImageUnscaled(_buffer, 0, 0); } protected override unsafe void OnResize(EventArgs e) { base.OnResize(e); if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0) { _buffer.Dispose(); _graphics.Dispose(); _bkgBuffer.Dispose(); _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _graphics = Graphics.FromImage(_buffer); ConfigureGraphics(_graphics); _bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); var length = ClientRectangle.Width - 2 * AxisMargin; var oldSpectrum = _smoothedSpectrum; _scaledSpectrum = new byte[length]; _smoothedSpectrum = new float[length]; _temp = new float[length]; _peaks = new bool[length]; fixed (float *old = oldSpectrum) { ExtractSpectrum(old, oldSpectrum.Length, 0.0f, 1.0f, false); } _points = new Point[length + 2]; if (_spectrumWidth > 0) { _xIncrement = _scale * length / _spectrumWidth; } _gradientBrush.Dispose(); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; _drawBackgroundNeeded = true; Perform(); } } protected override void OnPaintBackground(PaintEventArgs e) { // Prevent default background painting } protected virtual void OnFrequencyChanged(FrequencyEventArgs e) { if (FrequencyChanged != null) { FrequencyChanged(this, e); } } protected virtual void OnCenterFrequencyChanged(FrequencyEventArgs e) { if (CenterFrequencyChanged != null) { CenterFrequencyChanged(this, e); } } protected virtual void OnBandwidthChanged(BandwidthEventArgs e) { if (BandwidthChanged != null) { BandwidthChanged(this, e); } } private void UpdateFrequency(long f, FrequencyChangeSource source) { var min = (long) (_displayCenterFrequency - _spectrumWidth / _scale / 2); if (f < min) { f = min; } var max = (long) (_displayCenterFrequency + _spectrumWidth / _scale / 2); if (f > max) { f = max; } if (_useSnap) { f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize; } if (f != _frequency) { var args = new FrequencyEventArgs(f, source); OnFrequencyChanged(args); if (!args.Cancel) { _frequency = args.Frequency; _performNeeded = true; } } } private void UpdateCenterFrequency(long f, FrequencyChangeSource source) { if (f < 0) { f = 0; } if (_useSnap) { f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize; } if (f != _centerFrequency) { var args = new FrequencyEventArgs(f, source); OnCenterFrequencyChanged(args); if (!args.Cancel) { var delta = args.Frequency - _centerFrequency; _displayCenterFrequency += delta; _centerFrequency = args.Frequency; _drawBackgroundNeeded = true; } } } private void UpdateBandwidth(int bw) { bw = 10 * (bw / 10); if (bw < 10) { bw = 10; } if (bw != _filterBandwidth) { var args = new BandwidthEventArgs(bw); OnBandwidthChanged(args); if (!args.Cancel) { _filterBandwidth = args.Bandwidth; _performNeeded = true; } } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2); if (e.X > _lower && e.X < _upper && cursorWidth < ClientRectangle.Width) { _oldX = e.X; _oldFrequency = _frequency; _changingFrequency = true; } else if (_enableFilter && ((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Lower)) || (Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Upper)))) { _oldX = e.X; _oldFilterBandwidth = _filterBandwidth; _changingBandwidth = true; } else { _oldX = e.X; _oldCenterFrequency = _centerFrequency; _changingCenterFrequency = true; } } else if (e.Button == MouseButtons.Right) { UpdateFrequency(_frequency / Waterfall.RightClickSnapDistance * Waterfall.RightClickSnapDistance, FrequencyChangeSource.Click); } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (_changingCenterFrequency && e.X == _oldX) { var f = (long)((_oldX - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency); UpdateFrequency(f, FrequencyChangeSource.Click); } _changingCenterFrequency = false; _drawBackgroundNeeded = true; _changingBandwidth = false; _changingFrequency = false; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); _trackingX = e.X; _trackingY = e.Y; _trackingFrequency = (long)((e.X - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency); if (_useSnap) { _trackingFrequency = (_trackingFrequency + Math.Sign(_trackingFrequency) * _stepSize / 2) / _stepSize * _stepSize; } var displayRange = _displayRange / 10 * 10; var displayOffset = _displayOffset / 10 * 10; var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) displayRange; _trackingPower = displayOffset - displayRange - (_trackingY + AxisMargin - ClientRectangle.Height) / yIncrement; if (_changingFrequency) { var f = (long) ((e.X - _oldX) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFrequency); UpdateFrequency(f, FrequencyChangeSource.Drag); } else if (_changingCenterFrequency) { var f = (long) ((_oldX - e.X) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldCenterFrequency); UpdateCenterFrequency(f, FrequencyChangeSource.Drag); } else if (_changingBandwidth) { var bw = 0; switch (_bandType) { case BandType.Upper: bw = e.X - _oldX; break; case BandType.Lower: bw = _oldX - e.X; break; case BandType.Center: bw = (_oldX > (_lower + _upper) / 2 ? e.X - _oldX : _oldX - e.X) * 2; break; } bw = (int) (bw * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFilterBandwidth); UpdateBandwidth(bw); } else if (_enableFilter && ((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Lower)) || (Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Upper)))) { Cursor = Cursors.SizeWE; } else { Cursor = Cursors.Default; } _performNeeded = true; } protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); UpdateFrequency(_frequency + _stepSize * Math.Sign(e.Delta), FrequencyChangeSource.Scroll); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _hotTrackNeeded = false; _performNeeded = true; } protected override void OnMouseEnter(EventArgs e) { Focus(); base.OnMouseEnter(e); _hotTrackNeeded = true; } } }
// // System.Data.Odbc.libodbc // // Authors: // Brian Ritchie (brianlritchie@hotmail.com) // Sureshkumar T (tsureshkumar@novell.com) // // // Copyright (C) Brian Ritchie, 2002 // // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Data; using System.Data.Common; using System.Runtime.InteropServices; namespace System.Data.Odbc { internal enum OdbcHandleType : short { Env = 1, Dbc = 2, Stmt = 3, Desc = 4 }; internal enum OdbcReturn : short { Error = -1, InvalidHandle = -2, StillExecuting = 2, NeedData = 99, Success = 0, SuccessWithInfo = 1, NoData=100 } internal enum OdbcEnv : ushort { OdbcVersion = 200, ConnectionPooling = 201, CPMatch = 202 } internal enum OdbcConnectionAttribute : int { AutoCommit=102, TransactionIsolation=108 } internal enum OdbcInfo : ushort { DataSourceName = 2, DriverName = 6, DriverVersion = 7, DatabaseName = 16, DbmsVersion = 18 } internal enum OdbcInputOutputDirection : short { Input=1, InputOutput=2, ResultCol=3, Output=4, ReturnValue=5 } internal enum OdbcLengthIndicator : short { NoTotal = -4, NullData = -1 } // Keep this sorted. internal enum FieldIdentifier { AutoUniqueValue = 11, /* SQL_DESC_AUTO_UNIQUE_VALUE */ BaseColumnName = 22, /* SQL_DESC_BASE_COLUMN_NAME */ BaseTableName = 23, /* SQL_DESC_BASE_TABLE_NAME */ CaseSensitive = 12, /* SQL_DESC_CASE_SENSITIVE */ CatelogName = 17, /* SQL_DESC_CATALOG_NAME */ ConsiseType = 2, /* SQL_DESC_CONCISE_TYPE */ Count = 1001, /* SQL_DESC_COUNT */ DisplaySize = 6, /* SQL_DESC_DISPLAY_SIZE */ FixedPrecScale = 9, /* SQL_DESC_FIXED_PREC_SCALE */ Label = 18, /* SQL_DESC_LABEL */ Length = 1003, /* SQL_DESC_LENGTH */ LiteralPrefix = 27, /* SQL_DESC_LITERAL_PREFIX */ LiteralSuffix = 28, /* SQL_DESC_LITERAL_SUFFIX */ LocalTypeName = 29, /* SQL_DESC_LOCAL_TYPE_NAME */ Name = 1011, /* SQL_DESC_NAME */ Nullable = 1008, /* SQL_DESC_NULLABLE */ NumPrecRadix = 32, /* SQL_DESC_NUM_PREC_RADIX */ OctetLength = 1013, /* SQL_DESC_OCTET_LENGTH */ Precision = 1005, /* SQL_DESC_PRECISION */ Scale = 1006, /* SQL_DESC_SCALE */ SchemaName = 16, /* SQL_DESC_SCHEMA_NAME */ Searchable = 13, /* SQL_DESC_SEARCHABLE */ TableName = 15, /* SQL_DESC_TABLE_NAME */ Type = 1002, /* SQL_DESC_TYPE */ TypeName = 14, /* SQL_DESC_TYPE_NAME */ Unnamed = 1012, /* SQL_DESC_UNNAMED */ Unsigned = 8, /* SQL_DESC_UNSIGNED */ Updatable = 10 /* SQL_DESC_UPDATABLE */ } [StructLayout(LayoutKind.Sequential)] internal struct OdbcTimestamp { internal short year; internal ushort month; internal ushort day; internal ushort hour; internal ushort minute; internal ushort second; internal ulong fraction; } // sealed internal class libodbc internal class libodbc { #region global constants internal static int SQL_OV_ODBC2 = 2; internal static int SQL_OV_ODBC3 = 3; internal static string SQLSTATE_RIGHT_TRUNC = "01004"; internal static char C_NULL = '\0'; #endregion internal static OdbcInputOutputDirection ConvertParameterDirection( ParameterDirection dir) { switch (dir) { case ParameterDirection.Input: return OdbcInputOutputDirection.Input; case ParameterDirection.InputOutput: return OdbcInputOutputDirection.InputOutput; case ParameterDirection.Output: return OdbcInputOutputDirection.Output; case ParameterDirection.ReturnValue: return OdbcInputOutputDirection.ReturnValue; default: return OdbcInputOutputDirection.Input; } } [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLAllocHandle (OdbcHandleType HandleType, IntPtr InputHandle, ref IntPtr OutputHandlePtr); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLSetEnvAttr (IntPtr EnvHandle, OdbcEnv Attribute, IntPtr Value, int StringLength); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLConnect (IntPtr ConnectionHandle, string ServerName, short NameLength1, string UserName, short NameLength2, string Authentication, short NameLength3); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLDriverConnect(IntPtr ConnectionHandle, IntPtr WindowHandle, string InConnectionString, short StringLength1, string OutConnectionString, short BufferLength, ref short StringLength2Ptr, ushort DriverCompletion); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLExecDirect (IntPtr StatementHandle, string StatementText, int TextLength); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLRowCount (IntPtr StatementHandle, ref int RowCount); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLNumResultCols (IntPtr StatementHandle, ref short ColumnCount); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLFetch (IntPtr StatementHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref bool TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref double TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref long TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref short TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref float TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref OdbcTimestamp TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref int TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, byte[] TargetPtr, int BufferLen, ref int Len); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLDescribeCol(IntPtr StatementHandle, ushort ColumnNumber, byte[] ColumnName, short BufferLength, ref short NameLength, ref short DataType, ref uint ColumnSize, ref short DecimalDigits, ref short Nullable); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLFreeHandle(ushort HandleType, IntPtr SqlHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLDisconnect(IntPtr ConnectionHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLPrepare(IntPtr StatementHandle, string Statement, int TextLength); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLExecute(IntPtr StatementHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLSetConnectAttr(IntPtr ConnectionHandle, OdbcConnectionAttribute Attribute, IntPtr Value, int Length); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLEndTran(int HandleType, IntPtr Handle, short CompletionType); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLBindParameter(IntPtr StatementHandle, ushort ParamNum, short InputOutputType, SQL_C_TYPE ValueType, SQL_TYPE ParamType, uint ColSize, short DecimalDigits, byte[] ParamValue, int BufLen, ref int StrLen); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLBindParameter(IntPtr StatementHandle, ushort ParamNum, short InputOutputType, SQL_C_TYPE ValueType, SQL_TYPE ParamType, uint ColSize, short DecimalDigits, ref int ParamValue, int BufLen, ref int StrLen); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLCancel(IntPtr StatementHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLCloseCursor(IntPtr StatementHandle); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLError(IntPtr EnvironmentHandle, IntPtr ConnectionHandle, IntPtr StatementHandle, byte[] Sqlstate, ref int NativeError, byte[] MessageText, short BufferLength, ref short TextLength); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetStmtAttr(IntPtr StatementHandle, int Attribute, ref IntPtr Value, int BufLen, int StrLen); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLSetDescField(IntPtr DescriptorHandle, short RecNumber, short FieldIdentifier, byte[] Value, int BufLen); [DllImport("odbc32.dll")] internal static extern OdbcReturn SQLGetDiagRec (OdbcHandleType HandleType, IntPtr Handle, ushort RecordNumber, byte [] Sqlstate, ref int NativeError, byte [] MessageText, short BufferLength, ref short TextLength); [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLMoreResults (IntPtr Handle); internal enum SQLFreeStmtOptions : short { Close = 0, Drop, Unbind, ResetParams } [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLFreeStmt (IntPtr Handle, SQLFreeStmtOptions option); [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLGetInfo (IntPtr connHandle, OdbcInfo info, byte [] buffer, short buffLength, ref short remainingStrLen); [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLColAttribute (IntPtr StmtHandle, int column, FieldIdentifier fieldId, byte [] charAttributePtr, int bufferLength, ref int strLengthPtr, ref int numericAttributePtr ); [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLPrimaryKeys (IntPtr StmtHandle, string catalog, int catalogLength, string schema, int schemaLength, string tableName, int tableLength ); [DllImport ("odbc32.dll")] internal static extern OdbcReturn SQLBindCol (IntPtr StmtHandle, int column, SQL_C_TYPE targetType, byte [] buffer, int bufferLength, ref int indicator ); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Marten.Linq; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Linq { public class invoking_query_with_statistics: IntegrationContext { public invoking_query_with_statistics(DefaultStoreFixture fixture) : base(fixture) { theStore.BulkInsert(Target.GenerateRandomData(100).ToArray()); } #region sample_compiled-query-statistics public class TargetPaginationQuery: ICompiledListQuery<Target> { public TargetPaginationQuery(int pageNumber, int pageSize) { PageNumber = pageNumber; PageSize = pageSize; } public int PageNumber { get; set; } public int PageSize { get; set; } public QueryStatistics Stats { get; } = new QueryStatistics(); public Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> QueryIs() { return query => query .Where(x => x.Number > 10) .Skip(PageNumber) .Take(PageSize); } } #endregion [Fact] public void can_get_the_total_from_a_compiled_query() { var count = theSession.Query<Target>().Count(x => x.Number > 10); count.ShouldBeGreaterThan(0); var query = new TargetPaginationQuery(2, 5); var list = theSession .Query(query) .ToList(); list.Any().ShouldBeTrue(); query.Stats.TotalResults.ShouldBe(count); } [Fact] public async Task can_use_json_streaming_with_statistics() { var count = theSession.Query<Target>().Count(x => x.Number > 10); count.ShouldBeGreaterThan(0); var query = new TargetPaginationQuery(2, 5); var stream = new MemoryStream(); var resultCount = await theSession .StreamJsonMany(query, stream); resultCount.ShouldBeGreaterThan(0); stream.Position = 0; var list = theStore.Options.Serializer().FromJson<Target[]>(stream); list.Length.ShouldBe(5); query.Stats.TotalResults.ShouldBe(count); } [Fact] public async Task can_get_the_total_from_a_compiled_query_running_in_a_batch() { var count = await theSession.Query<Target>().Where(x => x.Number > 10).CountAsync(); SpecificationExtensions.ShouldBeGreaterThan(count, 0); var query = new TargetPaginationQuery(2, 5); var batch = theSession.CreateBatchQuery(); var targets = batch.Query(query); await batch.Execute(); (await targets) .Any().ShouldBeTrue(); query.Stats.TotalResults.ShouldBe(count); } [Fact] public void can_get_the_total_from_a_compiled_query_running_in_a_batch_sync() { var count = theSession.Query<Target>().Count(x => x.Number > 10); SpecificationExtensions.ShouldBeGreaterThan(count, 0); var query = new TargetPaginationQuery(2, 5); var batch = theSession.CreateBatchQuery(); var targets = batch.Query(query); batch.ExecuteSynchronously(); targets.Result .Any().ShouldBeTrue(); query.Stats.TotalResults.ShouldBe(count); } [Fact] public async Task can_get_the_total_in_batch_query() { var count = await theSession.Query<Target>().Where(x => x.Number > 10).CountAsync(); SpecificationExtensions.ShouldBeGreaterThan(count, 0); QueryStatistics stats = null; var batch = theSession.CreateBatchQuery(); var list = batch.Query<Target>().Stats(out stats).Where(x => x.Number > 10).Take(5) .ToList(); await batch.Execute(); (await list).Any().ShouldBeTrue(); stats.TotalResults.ShouldBe(count); } [Fact] public void can_get_the_total_in_batch_query_sync() { var count = theSession.Query<Target>().Count(x => x.Number > 10); SpecificationExtensions.ShouldBeGreaterThan(count, 0); QueryStatistics stats = null; var batch = theSession.CreateBatchQuery(); var list = batch.Query<Target>().Stats(out stats).Where(x => x.Number > 10).Take(5) .ToList(); batch.ExecuteSynchronously(); list.Result.Any().ShouldBeTrue(); stats.TotalResults.ShouldBe(count); } #region sample_using-query-statistics [Fact] public void can_get_the_total_in_results() { var count = theSession.Query<Target>().Count(x => x.Number > 10); SpecificationExtensions.ShouldBeGreaterThan(count, 0); // We're going to use stats as an output // parameter to the call below, so we // have to declare the "stats" object // first QueryStatistics stats = null; var list = theSession .Query<Target>() .Stats(out stats) .Where(x => x.Number > 10).Take(5) .ToList(); list.Any().ShouldBeTrue(); // Now, the total results data should // be available stats.TotalResults.ShouldBe(count); } #endregion [Fact] public async Task can_get_the_total_in_results_async() { var count = await theSession.Query<Target>().Where(x => x.Number > 10).CountAsync(); SpecificationExtensions.ShouldBeGreaterThan(count, 0); QueryStatistics stats = null; var list = await theSession.Query<Target>().Stats(out stats).Where(x => x.Number > 10).Take(5) .ToListAsync(); list.Any().ShouldBeTrue(); stats.TotalResults.ShouldBe(count); } } }
// // CodeReader.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Cecil.PE; using Mono.Collections.Generic; using RVA = System.UInt32; namespace Mono.Cecil.Cil { sealed class CodeReader : ByteBuffer { readonly internal MetadataReader reader; int start; Section code_section; MethodDefinition method; MethodBody body; int Offset { get { return base.position - start; } } public CodeReader(Section section, MetadataReader reader) : base(section.Data) { this.code_section = section; this.reader = reader; } public MethodBody ReadMethodBody(MethodDefinition method) { this.method = method; this.body = new MethodBody(method); reader.context = method; ReadMethodBody(); return this.body; } public void MoveTo(int rva) { if (!IsInSection(rva)) { code_section = reader.image.GetSectionAtVirtualAddress((uint)rva); Reset(code_section.Data); } base.position = rva - (int)code_section.VirtualAddress; } bool IsInSection(int rva) { return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData; } void ReadMethodBody() { MoveTo(method.RVA); var flags = ReadByte(); switch (flags & 0x3) { case 0x2: // tiny body.code_size = flags >> 2; body.MaxStackSize = 8; ReadCode(); break; case 0x3: // fat base.position--; ReadFatMethod(); break; default: throw new InvalidOperationException(); } var symbol_reader = reader.module.symbol_reader; if (symbol_reader != null) { var instructions = body.Instructions; symbol_reader.Read(body, offset => GetInstruction(instructions, offset)); } } void ReadFatMethod() { var flags = ReadUInt16(); body.max_stack_size = ReadUInt16(); body.code_size = (int)ReadUInt32(); body.local_var_token = new MetadataToken(ReadUInt32()); body.init_locals = (flags & 0x10) != 0; if (body.local_var_token.RID != 0) body.variables = ReadVariables(body.local_var_token); ReadCode(); if ((flags & 0x8) != 0) ReadSection(); } public VariableDefinitionCollection ReadVariables(MetadataToken local_var_token) { var position = reader.position; var variables = reader.ReadVariables(local_var_token); reader.position = position; return variables; } void ReadCode() { start = position; var code_size = body.code_size; if (code_size < 0 || buffer.Length <= (uint)(code_size + position)) code_size = 0; var end = start + code_size; var instructions = body.instructions = new InstructionCollection((code_size + 1) / 2); while (position < end) { var offset = base.position - start; var opcode = ReadOpCode(); var current = new Instruction(offset, opcode); if (opcode.OperandType != OperandType.InlineNone) current.operand = ReadOperand(current); instructions.Add(current); } ResolveBranches(instructions); } OpCode ReadOpCode() { var il_opcode = ReadByte(); return il_opcode != 0xfe ? OpCodes.OneByteOpCode[il_opcode] : OpCodes.TwoBytesOpCode[ReadByte()]; } object ReadOperand(Instruction instruction) { switch (instruction.opcode.OperandType) { case OperandType.InlineSwitch: var length = ReadInt32(); var base_offset = Offset + (4 * length); var branches = new int[length]; for (int i = 0; i < length; i++) branches[i] = base_offset + ReadInt32(); return branches; case OperandType.ShortInlineBrTarget: return ReadSByte() + Offset; case OperandType.InlineBrTarget: return ReadInt32() + Offset; case OperandType.ShortInlineI: if (instruction.opcode == OpCodes.Ldc_I4_S) return ReadSByte(); return ReadByte(); case OperandType.InlineI: return ReadInt32(); case OperandType.ShortInlineR: return ReadSingle(); case OperandType.InlineR: return ReadDouble(); case OperandType.InlineI8: return ReadInt64(); case OperandType.ShortInlineVar: return GetVariable(ReadByte()); case OperandType.InlineVar: return GetVariable(ReadUInt16()); case OperandType.ShortInlineArg: return GetParameter(ReadByte()); case OperandType.InlineArg: return GetParameter(ReadUInt16()); case OperandType.InlineSig: return GetCallSite(ReadToken()); case OperandType.InlineString: return GetString(ReadToken()); case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: return reader.LookupToken(ReadToken()); default: throw new NotSupportedException(); } } public string GetString(MetadataToken token) { return reader.image.UserStringHeap.Read(token.RID); } public ParameterDefinition GetParameter(int index) { return Mixin.GetParameter(body, index); } public VariableDefinition GetVariable(int index) { return Mixin.GetVariable(body, index); } public CallSite GetCallSite(MetadataToken token) { return reader.ReadCallSite(token); } void ResolveBranches(Collection<Instruction> instructions) { var items = instructions.items; var size = instructions.size; for (int i = 0; i < size; i++) { var instruction = items[i]; switch (instruction.opcode.OperandType) { case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: instruction.operand = GetInstruction((int)instruction.operand); break; case OperandType.InlineSwitch: var offsets = (int[])instruction.operand; var branches = new Instruction[offsets.Length]; for (int j = 0; j < offsets.Length; j++) branches[j] = GetInstruction(offsets[j]); instruction.operand = branches; break; } } } Instruction GetInstruction(int offset) { return GetInstruction(body.Instructions, offset); } static Instruction GetInstruction(Collection<Instruction> instructions, int offset) { var size = instructions.size; var items = instructions.items; if (offset < 0 || offset > items[size - 1].offset) return null; int min = 0; int max = size - 1; while (min <= max) { int mid = min + ((max - min) / 2); var instruction = items[mid]; var instruction_offset = instruction.offset; if (offset == instruction_offset) return instruction; if (offset < instruction_offset) max = mid - 1; else min = mid + 1; } return null; } void ReadSection() { Align(4); const byte fat_format = 0x40; const byte more_sects = 0x80; var flags = ReadByte(); if ((flags & fat_format) == 0) ReadSmallSection(); else ReadFatSection(); if ((flags & more_sects) != 0) ReadSection(); } void ReadSmallSection() { var count = ReadByte() / 12; Advance(2); ReadExceptionHandlers( count, () => (int)ReadUInt16(), () => (int)ReadByte()); } void ReadFatSection() { position--; var count = (ReadInt32() >> 8) / 24; ReadExceptionHandlers( count, ReadInt32, ReadInt32); } // inline ? void ReadExceptionHandlers(int count, Func<int> read_entry, Func<int> read_length) { for (int i = 0; i < count; i++) { var handler = new ExceptionHandler( (ExceptionHandlerType)(read_entry() & 0x7)); handler.TryStart = GetInstruction(read_entry()); handler.TryEnd = GetInstruction(handler.TryStart.Offset + read_length()); handler.HandlerStart = GetInstruction(read_entry()); handler.HandlerEnd = GetInstruction(handler.HandlerStart.Offset + read_length()); ReadExceptionHandlerSpecific(handler); this.body.ExceptionHandlers.Add(handler); } } void ReadExceptionHandlerSpecific(ExceptionHandler handler) { switch (handler.HandlerType) { case ExceptionHandlerType.Catch: handler.CatchType = (TypeReference)reader.LookupToken(ReadToken()); break; case ExceptionHandlerType.Filter: handler.FilterStart = GetInstruction(ReadInt32()); break; default: Advance(4); break; } } void Align(int align) { align--; Advance(((position + align) & ~align) - position); } public MetadataToken ReadToken() { return new MetadataToken(ReadUInt32()); } } }
using System; using Votyra.Core.Models; namespace Votyra.Core.Images { public class InterpolatedImage2iTo2fPostProcessor : IImage2fPostProcessor { private readonly IInterpolationConfig _interpolationConfig; public InterpolatedImage2iTo2fPostProcessor(IInterpolationConfig interpolationConfig) { _interpolationConfig = interpolationConfig; } public IImage2f PostProcess(IImage2f image) { if (_interpolationConfig.ImageSubdivision == 1) return image; switch (_interpolationConfig.ActiveAlgorithm) { case IntepolationAlgorithm.NearestNeighbour: if (image is IImageInvalidatableImage2) return new NNImage2fInvalidatableWrapper(image, _interpolationConfig.ImageSubdivision); else return new NNImage2fWrapper(image, _interpolationConfig.ImageSubdivision); case IntepolationAlgorithm.Linear: if (image is IImageInvalidatableImage2) return new LinearImage2fInvalidatableWrapper(image, _interpolationConfig.ImageSubdivision); else return new LinearImage2fWrapper(image, _interpolationConfig.ImageSubdivision); case IntepolationAlgorithm.Cubic: if (image is IImageInvalidatableImage2) return new CubicImage2fInvalidatableWrapper(image, _interpolationConfig.ImageSubdivision); else return new CubicImage2fWrapper(image, _interpolationConfig.ImageSubdivision); default: throw new ArgumentOutOfRangeException(); } } private class CubicImage2fWrapper : IImage2f, IInitializableImage { protected readonly IImage2f _image; private readonly Vector2i _interpolationCell = new Vector2i(int.MinValue, int.MinValue); private readonly float[,] _interpolationMatrix = new float[4, 4]; protected readonly int _subdivision; public CubicImage2fWrapper(IImage2f image, int subdivision) { _image = image; _subdivision = subdivision; RangeZ = _image.RangeZ; } public Area1f RangeZ { get; } public float Sample(Vector2i point) { var minPoint = point / _subdivision; var fraction = (point - minPoint * _subdivision) / (float) _subdivision; if (minPoint != _interpolationCell) { _interpolationMatrix[0, 0] = _image.Sample(minPoint + new Vector2i(+0 - 1, +0 - 1)); _interpolationMatrix[0, 1] = _image.Sample(minPoint + new Vector2i(+0 - 1, +1 - 1)); _interpolationMatrix[0, 2] = _image.Sample(minPoint + new Vector2i(+0 - 1, +2 - 1)); _interpolationMatrix[0, 3] = _image.Sample(minPoint + new Vector2i(+0 - 1, +3 - 1)); _interpolationMatrix[1, 0] = _image.Sample(minPoint + new Vector2i(+1 - 1, +0 - 1)); _interpolationMatrix[1, 1] = _image.Sample(minPoint + new Vector2i(+1 - 1, +1 - 1)); _interpolationMatrix[1, 2] = _image.Sample(minPoint + new Vector2i(+1 - 1, +2 - 1)); _interpolationMatrix[1, 3] = _image.Sample(minPoint + new Vector2i(+1 - 1, +3 - 1)); _interpolationMatrix[2, 0] = _image.Sample(minPoint + new Vector2i(+2 - 1, +0 - 1)); _interpolationMatrix[2, 1] = _image.Sample(minPoint + new Vector2i(+2 - 1, +1 - 1)); _interpolationMatrix[2, 2] = _image.Sample(minPoint + new Vector2i(+2 - 1, +2 - 1)); _interpolationMatrix[2, 3] = _image.Sample(minPoint + new Vector2i(+2 - 1, +3 - 1)); _interpolationMatrix[3, 0] = _image.Sample(minPoint + new Vector2i(+3 - 1, +0 - 1)); _interpolationMatrix[3, 1] = _image.Sample(minPoint + new Vector2i(+3 - 1, +1 - 1)); _interpolationMatrix[3, 2] = _image.Sample(minPoint + new Vector2i(+3 - 1, +2 - 1)); _interpolationMatrix[3, 3] = _image.Sample(minPoint + new Vector2i(+3 - 1, +3 - 1)); } var col0 = Intepolate(_interpolationMatrix[0, 0], _interpolationMatrix[1, 0], _interpolationMatrix[2, 0], _interpolationMatrix[3, 0], fraction.X); var col1 = Intepolate(_interpolationMatrix[0, 1], _interpolationMatrix[1, 1], _interpolationMatrix[2, 1], _interpolationMatrix[3, 1], fraction.X); var col2 = Intepolate(_interpolationMatrix[0, 2], _interpolationMatrix[1, 2], _interpolationMatrix[2, 2], _interpolationMatrix[3, 2], fraction.X); var col3 = Intepolate(_interpolationMatrix[0, 3], _interpolationMatrix[1, 3], _interpolationMatrix[2, 3], _interpolationMatrix[3, 3], fraction.X); var value = Intepolate(col0, col1, col2, col3, fraction.Y); return value; } public IPoolableMatrix2<float> SampleArea(Range2i area) { var min = ClipMinPoint(area.Min); var max = ClipMinPoint(area.Max); var offset = area.Min - min * _subdivision; var matrix = PoolableMatrix<float>.CreateDirty(area.Size); Area2i tempQualifier = Area2i.FromMinAndMax(min, max); var min1 = tempQualifier.Min; for (var ix1 = 0; ix1 <= tempQualifier.Size.X; ix1++) { for (var iy1 = 0; iy1 <= tempQualifier.Size.Y; iy1++) { var minPoint = new Vector2i(ix1, iy1) + min1; for (var ix = 0; ix < _subdivision; ix++) { for (var iy = 0; iy < _subdivision; iy++) { var imagePos = new Vector2i(ix + minPoint.X * _subdivision, iy + minPoint.Y * _subdivision); var matPos = imagePos - area.Min; if (matrix.ContainsIndex(matPos)) matrix[matPos] = Sample(imagePos); } } } } return matrix; } public void StartUsing() { (_image as IInitializableImage)?.StartUsing(); } public void FinishUsing() { (_image as IInitializableImage)?.FinishUsing(); } private Vector2i ClipMinPoint(Vector2i point) => new Vector2i(ClipMinPoint(point.X), ClipMinPoint(point.Y)); private int ClipMinPoint(int point) { if (point > 0) return point / _subdivision; if (point < 0) return point / _subdivision + (point % _subdivision == 0 ? 0 : -1); return 0; } // Monotone cubic interpolation // https://en.wikipedia.org/wiki/Monotone_cubic_interpolation private float Intepolate(float y0, float y1, float y2, float y3, float x12Rel) { // Get consecutive differences and slopes var dys0 = y1 - y0; var dys1 = y2 - y1; var dys2 = y3 - y2; // Get degree-1 coefficients float c1s1; if (dys0 * dys1 <= 0) c1s1 = 0; else c1s1 = 6f / (3f / dys0 + 3f / dys1); float c1s2; if (dys1 * dys2 <= 0) c1s2 = 0; else c1s2 = 6f / (3f / dys1 + 3f / dys2); // Get degree-2 and degree-3 coefficients var c3s1 = c1s1 + c1s2 - dys1 - dys1; var c2s1 = dys1 - c1s1 - c3s1; // Interpolate var diff = x12Rel; var diffSq = diff * diff; return y1 + c1s1 * diff + c2s1 * diffSq + c3s1 * diff * diffSq; } } private class CubicImage2fInvalidatableWrapper : CubicImage2fWrapper, IImageInvalidatableImage2 { public CubicImage2fInvalidatableWrapper(IImage2f image, int subdivision) : base(image, subdivision) { var invalidatedArea = (image as IImageInvalidatableImage2).InvalidatedArea; InvalidatedArea = Range2i.FromMinAndMax(invalidatedArea.Min * subdivision, invalidatedArea.Max * subdivision); } public Range2i InvalidatedArea { get; } } private class LinearImage2fWrapper : IImage2f, IInitializableImage { protected readonly IImage2f _image; protected readonly int _subdivision; public LinearImage2fWrapper(IImage2f image, int subdivision) { _image = image; _subdivision = subdivision; RangeZ = _image.RangeZ; } public Area1f RangeZ { get; } public float Sample(Vector2i point) { var minPoint = point / _subdivision; var fraction = (point - minPoint * _subdivision) / (float) _subdivision; var x0y0 = _image.Sample(minPoint); var x0y1 = _image.Sample(minPoint + new Vector2i(0, 1)); var x1y0 = _image.Sample(minPoint + new Vector2i(1, 0)); var x1y1 = _image.Sample(minPoint + new Vector2i(1, 1)); var value = (1f - fraction.X) * (1f - fraction.Y) * x0y0 + fraction.X * (1f - fraction.Y) * x1y0 + (1f - fraction.X) * fraction.Y * x0y1 + fraction.X * fraction.Y * x1y1; return value; } public IPoolableMatrix2<float> SampleArea(Range2i area) { var min = ClipMinPoint(area.Min); var max = ClipMinPoint(area.Max); var offset = area.Min - min * _subdivision; var matrix = PoolableMatrix<float>.CreateDirty(area.Size); Area2i tempQualifier = Area2i.FromMinAndMax(min, max); var min1 = tempQualifier.Min; for (var ix1 = 0; ix1 <= tempQualifier.Size.X; ix1++) { for (var iy1 = 0; iy1 <= tempQualifier.Size.Y; iy1++) { var minPoint = new Vector2i(ix1, iy1) + min1; for (var ix = 0; ix < _subdivision; ix++) { for (var iy = 0; iy < _subdivision; iy++) { var imagePos = new Vector2i(ix + minPoint.X * _subdivision, iy + minPoint.Y * _subdivision); var matPos = imagePos - area.Min; if (matrix.ContainsIndex(matPos)) matrix[matPos] = Sample(imagePos); } } } } return matrix; } public void StartUsing() { (_image as IInitializableImage)?.StartUsing(); } public void FinishUsing() { (_image as IInitializableImage)?.FinishUsing(); } private Vector2i ClipMinPoint(Vector2i point) => new Vector2i(ClipMinPoint(point.X), ClipMinPoint(point.Y)); private int ClipMinPoint(int point) { if (point > 0) return point / _subdivision; if (point < 0) return point / _subdivision + (point % _subdivision == 0 ? 0 : -1); return 0; } } private class LinearImage2fInvalidatableWrapper : LinearImage2fWrapper, IImageInvalidatableImage2 { public LinearImage2fInvalidatableWrapper(IImage2f image, int subdivision) : base(image, subdivision) { var invalidatedArea = (image as IImageInvalidatableImage2).InvalidatedArea; InvalidatedArea = Range2i.FromMinAndMax(invalidatedArea.Min * subdivision, invalidatedArea.Max * subdivision); } public Range2i InvalidatedArea { get; } } private class NNImage2fWrapper : IImage2f, IInitializableImage { protected readonly IImage2f _image; protected readonly int _subdivision; public NNImage2fWrapper(IImage2f image, int subdivision) { _image = image; _subdivision = subdivision; RangeZ = _image.RangeZ; } public Area1f RangeZ { get; } public float Sample(Vector2i point) { var minPoint = point / _subdivision; var x0y0 = _image.Sample(minPoint); return x0y0; } public IPoolableMatrix2<float> SampleArea(Range2i area) { var min = ClipMinPoint(area.Min); var max = ClipMinPoint(area.Max); var offset = area.Min - min * _subdivision; var matrix = PoolableMatrix<float>.CreateDirty(area.Size); Area2i tempQualifier = Area2i.FromMinAndMax(min, max); var min1 = tempQualifier.Min; for (var ix1 = 0; ix1 <= tempQualifier.Size.X; ix1++) { for (var iy1 = 0; iy1 <= tempQualifier.Size.Y; iy1++) { var minPoint = new Vector2i(ix1, iy1)+min1; for (var ix = 0; ix < _subdivision; ix++) { for (var iy = 0; iy < _subdivision; iy++) { var imagePos = new Vector2i(ix + minPoint.X * _subdivision, iy + minPoint.Y * _subdivision); var matPos = imagePos - area.Min; if (matrix.ContainsIndex(matPos)) matrix[matPos] = Sample(imagePos); } } } } return matrix; } public void StartUsing() { (_image as IInitializableImage)?.StartUsing(); } public void FinishUsing() { (_image as IInitializableImage)?.FinishUsing(); } private Vector2i ClipMinPoint(Vector2i point) => new Vector2i(ClipMinPoint(point.X), ClipMinPoint(point.Y)); private int ClipMinPoint(int point) { if (point > 0) return point / _subdivision; if (point < 0) return point / _subdivision + (point % _subdivision == 0 ? 0 : -1); return 0; } } private class NNImage2fInvalidatableWrapper : NNImage2fWrapper, IImageInvalidatableImage2 { public NNImage2fInvalidatableWrapper(IImage2f image, int subdivision) : base(image, subdivision) { var invalidatedArea = (image as IImageInvalidatableImage2).InvalidatedArea; InvalidatedArea = Range2i.FromMinAndMax(invalidatedArea.Min * subdivision, invalidatedArea.Max * subdivision); } public Range2i InvalidatedArea { get; } } } }
namespace android.app { [global::MonoJavaBridge.JavaClass()] public partial class WallpaperManager : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static WallpaperManager() { InitJNI(); } protected WallpaperManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _clear854; public virtual void clear() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._clear854); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._clear854); } internal static global::MonoJavaBridge.MethodId _getInstance855; public static global::android.app.WallpaperManager getInstance(android.content.Context arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getInstance855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.app.WallpaperManager; } internal static global::MonoJavaBridge.MethodId _getDrawable856; public virtual global::android.graphics.drawable.Drawable getDrawable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.WallpaperManager._getDrawable856)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getDrawable856)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _setBitmap857; public virtual void setBitmap(android.graphics.Bitmap arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._setBitmap857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._setBitmap857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _peekDrawable858; public virtual global::android.graphics.drawable.Drawable peekDrawable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.WallpaperManager._peekDrawable858)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._peekDrawable858)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getFastDrawable859; public virtual global::android.graphics.drawable.Drawable getFastDrawable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.WallpaperManager._getFastDrawable859)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getFastDrawable859)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _peekFastDrawable860; public virtual global::android.graphics.drawable.Drawable peekFastDrawable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.WallpaperManager._peekFastDrawable860)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._peekFastDrawable860)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getWallpaperInfo861; public virtual global::android.app.WallpaperInfo getWallpaperInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.WallpaperManager._getWallpaperInfo861)) as android.app.WallpaperInfo; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getWallpaperInfo861)) as android.app.WallpaperInfo; } internal static global::MonoJavaBridge.MethodId _setResource862; public virtual void setResource(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._setResource862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._setResource862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setStream863; public virtual void setStream(java.io.InputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._setStream863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._setStream863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDesiredMinimumWidth864; public virtual int getDesiredMinimumWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.WallpaperManager._getDesiredMinimumWidth864); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getDesiredMinimumWidth864); } internal static global::MonoJavaBridge.MethodId _getDesiredMinimumHeight865; public virtual int getDesiredMinimumHeight() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.WallpaperManager._getDesiredMinimumHeight865); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._getDesiredMinimumHeight865); } internal static global::MonoJavaBridge.MethodId _suggestDesiredDimensions866; public virtual void suggestDesiredDimensions(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._suggestDesiredDimensions866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._suggestDesiredDimensions866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setWallpaperOffsets867; public virtual void setWallpaperOffsets(android.os.IBinder arg0, float arg1, float arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._setWallpaperOffsets867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._setWallpaperOffsets867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setWallpaperOffsetSteps868; public virtual void setWallpaperOffsetSteps(float arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._setWallpaperOffsetSteps868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._setWallpaperOffsetSteps868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _sendWallpaperCommand869; public virtual void sendWallpaperCommand(android.os.IBinder arg0, java.lang.String arg1, int arg2, int arg3, int arg4, android.os.Bundle arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._sendWallpaperCommand869, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._sendWallpaperCommand869, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } internal static global::MonoJavaBridge.MethodId _clearWallpaperOffsets870; public virtual void clearWallpaperOffsets(android.os.IBinder arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.WallpaperManager._clearWallpaperOffsets870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.WallpaperManager.staticClass, global::android.app.WallpaperManager._clearWallpaperOffsets870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.lang.String ACTION_LIVE_WALLPAPER_CHOOSER { get { return "android.service.wallpaper.LIVE_WALLPAPER_CHOOSER"; } } public static global::java.lang.String COMMAND_TAP { get { return "android.wallpaper.tap"; } } public static global::java.lang.String COMMAND_DROP { get { return "android.home.drop"; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.WallpaperManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/WallpaperManager")); global::android.app.WallpaperManager._clear854 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "clear", "()V"); global::android.app.WallpaperManager._getInstance855 = @__env.GetStaticMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getInstance", "(Landroid/content/Context;)Landroid/app/WallpaperManager;"); global::android.app.WallpaperManager._getDrawable856 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getDrawable", "()Landroid/graphics/drawable/Drawable;"); global::android.app.WallpaperManager._setBitmap857 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "setBitmap", "(Landroid/graphics/Bitmap;)V"); global::android.app.WallpaperManager._peekDrawable858 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "peekDrawable", "()Landroid/graphics/drawable/Drawable;"); global::android.app.WallpaperManager._getFastDrawable859 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getFastDrawable", "()Landroid/graphics/drawable/Drawable;"); global::android.app.WallpaperManager._peekFastDrawable860 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "peekFastDrawable", "()Landroid/graphics/drawable/Drawable;"); global::android.app.WallpaperManager._getWallpaperInfo861 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getWallpaperInfo", "()Landroid/app/WallpaperInfo;"); global::android.app.WallpaperManager._setResource862 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "setResource", "(I)V"); global::android.app.WallpaperManager._setStream863 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "setStream", "(Ljava/io/InputStream;)V"); global::android.app.WallpaperManager._getDesiredMinimumWidth864 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getDesiredMinimumWidth", "()I"); global::android.app.WallpaperManager._getDesiredMinimumHeight865 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "getDesiredMinimumHeight", "()I"); global::android.app.WallpaperManager._suggestDesiredDimensions866 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "suggestDesiredDimensions", "(II)V"); global::android.app.WallpaperManager._setWallpaperOffsets867 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "setWallpaperOffsets", "(Landroid/os/IBinder;FF)V"); global::android.app.WallpaperManager._setWallpaperOffsetSteps868 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "setWallpaperOffsetSteps", "(FF)V"); global::android.app.WallpaperManager._sendWallpaperCommand869 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "sendWallpaperCommand", "(Landroid/os/IBinder;Ljava/lang/String;IIILandroid/os/Bundle;)V"); global::android.app.WallpaperManager._clearWallpaperOffsets870 = @__env.GetMethodIDNoThrow(global::android.app.WallpaperManager.staticClass, "clearWallpaperOffsets", "(Landroid/os/IBinder;)V"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Runtime.CompilerServices; using static System.TestHelpers; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ClearEmpty() { var span = Span<byte>.Empty; span.Clear(); } [Fact] public static void ClearEmptyWithReference() { var span = Span<string>.Empty; span.Clear(); } [Fact] public static void ClearByteLonger() { const byte initial = 5; var actual = new byte[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = initial; } var expected = new byte[actual.Length]; var span = new Span<byte>(actual); span.Clear(); Assert.Equal<byte>(expected, actual); } [Fact] public static void ClearByteUnaligned() { const byte initial = 5; const int length = 32; var actualFull = new byte[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new byte[length]; var start = 1; var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1); var actualSpan = new Span<byte>(actualFull, start, length - start - 1); actualSpan.Clear(); byte[] actual = actualSpan.ToArray(); byte[] expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } [Fact] public unsafe static void ClearByteUnalignedFixed() { const byte initial = 5; const int length = 32; var actualFull = new byte[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new byte[length]; var start = 1; var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1); fixed (byte* p = actualFull) { var actualSpan = new Span<byte>(p + start, length - start - 1); actualSpan.Clear(); byte[] actual = actualSpan.ToArray(); byte[] expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } } [Fact] public static void ClearIntPtrOffset() { IntPtr initial = IntPtr.Zero + 5; const int length = 32; var actualFull = new IntPtr[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new IntPtr[length]; var start = 2; var expectedSpan = new Span<IntPtr>(expectedFull, start, length - start - 1); var actualSpan = new Span<IntPtr>(actualFull, start, length - start - 1); actualSpan.Clear(); IntPtr[] actual = actualSpan.ToArray(); IntPtr[] expected = expectedSpan.ToArray(); Assert.Equal<IntPtr>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } [Fact] public static void ClearIntPtrLonger() { IntPtr initial = IntPtr.Zero + 5; var actual = new IntPtr[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = initial; } var expected = new IntPtr[actual.Length]; var span = new Span<IntPtr>(actual); span.Clear(); Assert.Equal<IntPtr>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferences() { int[] actual = { 1, 2, 3 }; int[] expected = { 0, 0, 0 }; var span = new Span<int>(actual); span.Clear(); Assert.Equal<int>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferencesLonger() { int[] actual = new int[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = i + 1; } int[] expected = new int[actual.Length]; var span = new Span<int>(actual); span.Clear(); Assert.Equal<int>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferencesPointerSize() { long[] actual = new long[15]; for (int i = 0; i < actual.Length; i++) { actual[i] = i + 1; } long[] expected = new long[actual.Length]; var span = new Span<long>(actual); span.Clear(); Assert.Equal<long>(expected, actual); } [Fact] public static void ClearReferenceType() { string[] actual = { "a", "b", "c" }; string[] expected = { null, null, null }; var span = new Span<string>(actual); span.Clear(); Assert.Equal<string>(expected, actual); } [Fact] public static void ClearReferenceTypeLonger() { string[] actual = new string[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = (i + 1).ToString(); } string[] expected = new string[actual.Length]; var span = new Span<string>(actual); span.Clear(); Assert.Equal<string>(expected, actual); } [Fact] public static void ClearEnumType() { TestEnum[] actual = { TestEnum.e0, TestEnum.e1, TestEnum.e2 }; TestEnum[] expected = { default, default, default }; var span = new Span<TestEnum>(actual); span.Clear(); Assert.Equal<TestEnum>(expected, actual); } [Fact] public static void ClearValueTypeWithReferences() { TestValueTypeWithReference[] actual = { new TestValueTypeWithReference() { I = 1, S = "a" }, new TestValueTypeWithReference() { I = 2, S = "b" }, new TestValueTypeWithReference() { I = 3, S = "c" } }; TestValueTypeWithReference[] expected = { default, default, default }; var span = new Span<TestValueTypeWithReference>(actual); span.Clear(); Assert.Equal<TestValueTypeWithReference>(expected, actual); } // NOTE: ClearLongerThanUintMaxValueBytes test is constrained to run on Windows and MacOSX because it causes // problems on Linux due to the way deferred memory allocation works. On Linux, the allocation can // succeed even if there is not enough memory but then the test may get killed by the OOM killer at the // time the memory is accessed which triggers the full memory allocation. [Fact] [OuterLoop] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] unsafe static void ClearLongerThanUintMaxValueBytes() { if (sizeof(IntPtr) == sizeof(long)) { // Arrange IntPtr bytes = (IntPtr)(((long)int.MaxValue) * sizeof(int)); int length = (int)(((long)bytes) / sizeof(int)); if (!AllocationHelper.TryAllocNative(bytes, out IntPtr memory)) { Console.WriteLine($"Span.Clear test {nameof(ClearLongerThanUintMaxValueBytes)} skipped (could not alloc memory)."); return; } try { Span<int> span = new Span<int>(memory.ToPointer(), length); span.Fill(5); // Act span.Clear(); // Assert using custom code for perf and to avoid allocating extra memory ref int data = ref Unsafe.AsRef<int>(memory.ToPointer()); for (int i = 0; i < length; i++) { var actual = Unsafe.Add(ref data, i); if (actual != 0) { Assert.Equal(0, actual); } } } finally { AllocationHelper.ReleaseNative(ref memory); } } } } }
namespace FakeItEasy.Specs { using System; using FakeItEasy.Configuration; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public static class WrappingFakeSpecs { public interface IFoo { int NonVoidMethod(string? parameter); void VoidMethod(string? parameter); void OutAndRefMethod(ref int @ref, out int @out); event EventHandler? SomeEvent; } public interface IBar { int Id { get; } } [Scenario] public static void NonVoidSuccess( Foo realObject, IFoo wrapper, int result) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a non-void method is called on the wrapper" .x(() => result = wrapper.NonVoidMethod("hello")); "Then the real object's method is called" .x(() => realObject.NonVoidMethodCalled.Should().BeTrue()); "And the wrapper returns the value returned by the real object's method" .x(() => result.Should().Be(5)); } [Scenario] public static void NonVoidException( Foo realObject, IFoo wrapper, Exception exception) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a non-void method is called on the wrapper" .x(() => exception = Record.Exception(() => wrapper.NonVoidMethod(null))); "Then the real object's method is called" .x(() => realObject.NonVoidMethodCalled.Should().BeTrue()); "And the wrapper throws the exception thrown by the real object's method" .x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>()); "And the exception stack trace is preserved" .x(() => exception.StackTrace.Should().Contain("FakeItEasy.Specs.WrappingFakeSpecs.Foo.NonVoidMethod")); } [Scenario] public static void VoidSuccess( Foo realObject, IFoo wrapper) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a void method is called on the wrapper" .x(() => wrapper.VoidMethod("hello")); "Then the real object's method is called" .x(() => realObject.VoidMethodCalled.Should().BeTrue()); } [Scenario] public static void VoidException( Foo realObject, IFoo wrapper, Exception exception) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a void method is called on the wrapper" .x(() => exception = Record.Exception(() => wrapper.VoidMethod(null))); "Then the real object's method is called" .x(() => realObject.VoidMethodCalled.Should().BeTrue()); "And the wrapper throws the exception thrown by the real object's method" .x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>()); "And the exception stack trace is preserved" .x(() => exception.StackTrace.Should().Contain("FakeItEasy.Specs.WrappingFakeSpecs.Foo.VoidMethod")); } [Scenario] public static void OutAndRef( Foo realObject, IFoo wrapper, int @ref, int @out) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "And a @ref variable with an initial value of 1" .x(() => @ref = 1); "When a method with out and ref parameters is called on the wrapper" .x(() => wrapper.OutAndRefMethod(ref @ref, out @out)); "Then the real object's method is called" .x(() => realObject.OutAndRefMethodCalled.Should().BeTrue()); "And the value of @ref is incremented" .x(() => @ref.Should().Be(2)); "And the value of @out is set" .x(() => @out.Should().Be(42)); } [Scenario] public static void FakeEqualsFake(Foo realObject, IFoo wrapper, bool equals) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When Equals is called on the fake with itself as the argument" .x(() => equals = wrapper.Equals(wrapper)); "Then it should return true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void FakeEqualsWrappedObject(Foo realObject, IFoo wrapper, bool equals) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When Equals is called on the fake with the real object as the argument" .x(() => equals = wrapper.Equals(realObject)); "Then it should return false" .x(() => equals.Should().BeFalse()); } [Scenario] public static void FakeEqualsFakeWithValueSemantics(Bar realObject, IBar wrapper, bool equals) { "Given a real object that overrides Equals with value semantics" .x(() => realObject = new Bar(42)); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IBar>(o => o.Wrapping(realObject))); "When Equals is called on the fake with itself as the argument" .x(() => equals = wrapper.Equals(wrapper)); "Then it should return true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void FakeEqualsWrappedObjectWithValueSemantics(Bar realObject, IBar wrapper, bool equals) { "Given a real object that overrides Equals with value semantics" .x(() => realObject = new Bar(42)); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IBar>(o => o.Wrapping(realObject))); "When Equals is called on the fake with the real object as the argument" .x(() => equals = wrapper.Equals(realObject)); "Then it should return true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void FakeClassEqualsWrappedObjectWithOverriddenReferenceSemantics( ClassThatOverrideEqualsForNoReason realObject, ClassThatOverrideEqualsForNoReason wrapper, bool equals) { "Given a real object that overrides Equals but keeps reference semantics" .x(() => realObject = new ClassThatOverrideEqualsForNoReason()); "And a faked class of the same type that wraps the real object" .x(() => wrapper = A.Fake<ClassThatOverrideEqualsForNoReason>(o => o.Wrapping(realObject))); "When Equals is called on the fake with itself as the argument" .x(() => equals = wrapper.Equals(wrapper)); "Then it should return true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void FakeObjectEqualsWrappedObjectWithOverriddenReferenceSemantics( ClassThatOverrideEqualsForNoReason realObject, object wrapper, bool equals) { "Given a real object that overrides Equals but keeps reference semantics" .x(() => realObject = new ClassThatOverrideEqualsForNoReason()); "And a faked Object type that wraps the real object" .x(() => wrapper = A.Fake<object>(o => o.Wrapping(realObject))); "When Equals is called on the fake with itself as the argument" .x(() => equals = wrapper.Equals(wrapper)); "Then it should return true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void VoidCallsWrappedMethod(Foo realObject, IFoo wrapper, bool callbackWasCalled) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a void method on the fake is configured to invoke a callback and call the wrapped method" .x(() => A.CallTo(() => wrapper.VoidMethod("hello")) .Invokes(() => callbackWasCalled = true) .CallsWrappedMethod()); "And the configured method is called on the fake" .x(() => wrapper.VoidMethod("hello")); "Then the callback is invoked" .x(() => callbackWasCalled.Should().BeTrue()); "And the real object's method is called" .x(() => realObject.VoidMethodCalled.Should().BeTrue()); } [Scenario] public static void NonVoidCallsWrappedMethod(Foo realObject, IFoo wrapper, bool callbackWasCalled, int returnValue) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "When a non-void method on the fake is configured to invoke a callback and call the wrapped method" .x(() => A.CallTo(() => wrapper.NonVoidMethod("hello")) .Invokes(() => callbackWasCalled = true) .CallsWrappedMethod()); "And the configured method is called on the fake" .x(() => returnValue = wrapper.NonVoidMethod("hello")); "Then the callback is invoked" .x(() => callbackWasCalled.Should().BeTrue()); "And the real object's method is called" .x(() => realObject.NonVoidMethodCalled.Should().BeTrue()); "And the wrapper returns the value returned by the real object's method" .x(() => returnValue.Should().Be(5)); } [Scenario] public static void NotAWrappingFakeCallsWrappedMethod(IFoo fake, Exception exception) { "Given a non-wrapping fake" .x(() => fake = A.Fake<IFoo>()); "When a method on the fake is configured to call the wrapped method" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.VoidMethod("hello")).CallsWrappedMethod())); "Then it throws a FakeConfigurationException" .x(() => exception.Should() .BeAnExceptionOfType<FakeConfigurationException>() .WithMessage("The configured fake is not a wrapping fake.")); } [Scenario] public static void EventSubscriptionSubscribesToWrappedEvent(Foo realObject, IFoo wrapper, EventHandler handler) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "And an event handler" .x(() => handler = A.Fake<EventHandler>()); "When the handler is subscribed to the fake's event" .x(() => wrapper.SomeEvent += handler); "And the event is raised using a method on the wrapped object" .x(() => realObject.RaiseSomeEvent()); "Then the handler is called" .x(() => A.CallTo(handler).MustHaveHappened()); } [Scenario] public static void RaisingEventOnWrappingFakeUsingRaiseSyntax(Foo realObject, IFoo wrapper, EventHandler handler, Exception exception) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "And an event handler" .x(() => handler = A.Fake<EventHandler>()); "When the event is raised on the fake using the '+= Raise' syntax" .x(() => exception = Record.Exception(() => wrapper.SomeEvent += Raise.WithEmpty())); "Then an InvalidOperationException is thrown" .x(() => exception.Should() .BeAnExceptionOfType<InvalidOperationException>() .WithMessage("*The fake cannot raise the event because it's a wrapping fake*")); } [Scenario] public static void RaisingEventOnWrappingFakeWorkaround(Foo realObject, IFoo wrapper, EventHandler? handlers, EventHandler individualHandler) { "Given a real object" .x(() => realObject = new Foo()); "And a fake wrapping this object" .x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject))); "And an event handler" .x(() => individualHandler = A.Fake<EventHandler>()); "When the fake is configured to handle event subscriptions manually" .x(() => { A.CallTo(wrapper).Where(call => call.Method.Name == "add_SomeEvent").Invokes((EventHandler h) => handlers += h); A.CallTo(wrapper).Where(call => call.Method.Name == "remove_SomeEvent").Invokes((EventHandler h) => handlers -= h); }); "And the handler is subscribed to the event" .x(() => wrapper.SomeEvent += individualHandler); "And the event is raised" .x(() => handlers?.Invoke(wrapper, EventArgs.Empty)); "Then the event handler is called" .x(() => A.CallTo(individualHandler).MustHaveHappened()); } public class Foo : IFoo { public bool NonVoidMethodCalled { get; private set; } public bool VoidMethodCalled { get; private set; } public bool OutAndRefMethodCalled { get; private set; } public int NonVoidMethod(string? parameter) { this.NonVoidMethodCalled = true; if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } return parameter.Length; } public void VoidMethod(string? parameter) { this.VoidMethodCalled = true; if (parameter is null) { throw new ArgumentNullException(nameof(parameter)); } } public void OutAndRefMethod(ref int @ref, out int @out) { this.OutAndRefMethodCalled = true; @ref += 1; @out = 42; } public event EventHandler? SomeEvent; #pragma warning disable CA1030 // Use events where appropriate public void RaiseSomeEvent() => this.SomeEvent?.Invoke(this, EventArgs.Empty); #pragma warning restore CA1030 // Use events where appropriate } public class Bar : IBar { public Bar(int id) { this.Id = id; } public int Id { get; } public override bool Equals(object? obj) { return obj is IBar other && other.Id == this.Id; } public override int GetHashCode() { return this.Id.GetHashCode(); } } public class ClassThatOverrideEqualsForNoReason { public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Data; using SunnyChen.Common.DataServices; using SunnyChen.Common.Enumerations; namespace SunnyChen.Common.Network { /// <summary> /// Provides data communication and error response handling for SOCKET oriented connections. /// </summary> /// <example> /// Following example demonstrates the usage of NetworkCommunicator. In this demonstration, /// the NetworkCommunicator sends a space-separated command string to the server and gets the /// result which is encapsulated in a <see cref="SunnyChen.Common.Network.ResponseResultGeneric&lt;ResultType&gt;"/> object /// from the server. /// <code> /// public ErrorLevel GetServerResponse(Socket _client, string _command, out string _result) /// { /// NetworkCommunicator communicator = new NetworkCommunicator(_client); /// communicator.Send(_command); /// ResponseResultGeneric&lt;string&gt; result = communicator.ReceiveString(); /// _result = result.Result; /// return result.ErrorLevel; /// } /// </code> /// </example> public class NetworkCommunicator { #region Private Fields /// <summary> /// /// </summary> private Socket socket__ = null; /// <summary> /// /// </summary> private ulong totalBytesSent__ = 0; /// <summary> /// /// </summary> private ulong totalBytesRec__ = 0; private string name__ = string.Empty; #endregion #region Constructors /// <summary> /// Creates the NetworkCommunicator instance with the specified Socket object. /// </summary> /// <param name="_socket">The Socket object.</param> public NetworkCommunicator(Socket _socket) { socket__ = _socket; //socket__.SendBufferSize = 512 * 1024; //socket__.ReceiveBufferSize = 512 * 1024; //name__ = DataServices.DataUtility.GetRandomString(12); } /// <summary> /// Creates the named NetworkCommunicator instance with the specified Socket object. /// </summary> /// <param name="_socket">The Socket object.</param> /// <param name="_name">The name that gives to the NetworkCommunicator instance.</param> public NetworkCommunicator(Socket _socket, string _name) { socket__ = _socket; name__ = _name; } #endregion #region Public Delegates and Events /// <summary> /// Represents the method that will handle an event that has a <see cref="System.Exception"/> argument. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="SunnyChen.Common.ExceptionEventArgs"/> that contains the exception information.</param> public delegate void CommunicationExceptionEventHandler(object sender, ExceptionEventArgs e); /// <summary> /// Occurs when an exception raises during the network communication. /// </summary> public event CommunicationExceptionEventHandler CommunicationException; /// <summary> /// Occurs before the data is going to be sent. /// </summary> public event EventHandler BeforeSend; /// <summary> /// Occurs after the data has been sent. /// </summary> public event EventHandler AfterSend; /// <summary> /// Occurs before the data is going to be received. /// </summary> public event EventHandler BeforeReceive; /// <summary> /// Occurs after the data has been received. /// </summary> public event EventHandler AfterReceive; #endregion #region Protected Methods /// <summary> /// The internal event handler that handles the <see cref="CommunicationException"/> event. /// </summary> /// <param name="e">The source of the event.</param> protected virtual void OnCommunicationException(ExceptionEventArgs e) { if (CommunicationException != null) { CommunicationException(this, e); } } /// <summary> /// The internal event handler that handles the <see cref="BeforeSend"/> event. /// </summary> /// <param name="e">The source of the event.</param> protected virtual void OnBeforeSend(System.EventArgs e) { if (BeforeSend != null) { BeforeSend(this, e); } } /// <summary> /// The internal event handler that handles the <see cref="AfterSend"/> event. /// </summary> /// <param name="e">The source of the event.</param> protected virtual void OnAfterSend(System.EventArgs e) { if (AfterSend != null) { AfterSend(this, e); } } /// <summary> /// The internal event handler that handles the <see cref="BeforeReceive"/> event. /// </summary> /// <param name="e">The source of the event.</param> protected virtual void OnBeforeReceive(System.EventArgs e) { if (BeforeReceive != null) { BeforeReceive(this, e); } } /// <summary> /// The internal event handler that handles the <see cref="AfterReceive"/> event. /// </summary> /// <param name="e">The source of the event.</param> protected virtual void OnAfterReceive(System.EventArgs e) { if (AfterReceive != null) { AfterReceive(this, e); } } #endregion #region Public Properties /// <summary> /// Gets the bytes sent to the connected socket. /// </summary> public ulong BytesSent { get { return totalBytesSent__; } } /// <summary> /// Gets the bytes received from the connected socket. /// </summary> public ulong BytesReceived { get { return totalBytesRec__; } } /// <summary> /// Gets the remote connected endpoint. /// </summary> public EndPoint RemoteEndPoint { get { return socket__.RemoteEndPoint; } } /// <summary> /// Gets the local endpoint. /// </summary> public EndPoint LocalEndPoint { get { return socket__.LocalEndPoint; } } /// <summary> /// Gets the name of the communicator. /// </summary> public string Name { get { return name__; } } #endregion #region Public Static Methods /// <summary> /// The static method that sends specific bytes to a connected socket. /// </summary> /// <param name="socket">The connected socket to which the data is going to be sent.</param> /// <param name="buffer">The byte array in which the data is going to be sent.</param> /// <param name="offset">Zero-based index value. It determines from which byte of the array should be sent.</param> /// <param name="size">Number of bytes to send.</param> /// <param name="timeout">An integer timeout value.</param> public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout) { int startTickCount = Environment.TickCount; int sent = 0; // how many bytes is already sent do { //if (timeout > 0) //{ // if (Environment.TickCount > startTickCount + timeout) // throw new Exception("Timeout."); //} try { sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably full, wait and try again //System.Threading.Thread.Sleep(30); } else throw ex; // any serious error occurs } } while (sent < size); } /// <summary> /// The static method that receives specific bytes from a connected socket. /// </summary> /// <param name="socket">The connected socket from which the data is being received.</param> /// <param name="buffer">The byte array from which the data is being received.</param> /// <param name="offset">Zero-based index value. It determines from which byte of the array that the received data should be stored.</param> /// <param name="size">Number of bytes to receive.</param> /// <param name="timeout">An integer timeout value.</param> public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout) { int startTickCount = Environment.TickCount; int received = 0; // how many bytes is already received do { //if (timeout > 0) //{ // if (Environment.TickCount > startTickCount + timeout) // throw new Exception("Timeout."); //} try { received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably empty, wait and try again //System.Threading.Thread.Sleep(30); } else throw ex; // any serious error occurr } } while (received < size); } #endregion #region Public Methods /// <summary> /// Sends a specified string with the error level information. /// </summary> /// <param name="_str">String to be sent.</param> /// <param name="_errorLevel">Error level information.</param> /// <returns> /// This function has the following return values. /// <list type="table"> /// <listheader><term>Return Value</term><description>Description</description></listheader> /// <item><term>0</term><description>Succeeded</description></item> /// <item><term>-1</term><description>Exception occurred</description></item> /// </list> /// </returns> public int Send(string _str, ErrorLevel _errorLevel) { try { OnBeforeSend(null); DataPackage dp = new DataPackage(); dp.Bytes = Encoding.ASCII.GetBytes(_str); dp.ActualBufferLength = _str.Length; dp.ErrorLevel = _errorLevel; dp.StreamType = StreamType.stString; byte[] serialized = DataPackage.Serialize((DataPackage)dp); int requestLen = serialized.Length; int requestLen_Host2NetworkOrder = IPAddress.HostToNetworkOrder(requestLen); byte[] requestLen_Host2NetworkOrder_Array = BitConverter.GetBytes(requestLen_Host2NetworkOrder); Send(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); Send(socket__, serialized, 0, requestLen, 0); return 0; } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return -1; } finally { OnAfterSend(null); } } /// <summary> /// Sends a specified DataSet object with error level information. /// </summary> /// <param name="_dataSet">DataSet object to be sent.</param> /// <param name="_errorLevel">Error level information.</param> /// <returns>Zero on success.</returns> public int Send(DataSet _dataSet, ErrorLevel _errorLevel) { try { OnBeforeSend(null); DataPackage dp = new DataPackage(); dp.Bytes = DataPackage.Serialize((DataSet)_dataSet); dp.ActualBufferLength = dp.Bytes.Length; dp.ErrorLevel = _errorLevel; dp.StreamType = StreamType.stDataSet; byte[] serialized = DataPackage.Serialize((DataPackage)dp); int requestLen = serialized.Length; int requestLen_Host2NetworkOrder = IPAddress.HostToNetworkOrder(requestLen); byte[] requestLen_Host2NetworkOrder_Array = BitConverter.GetBytes(requestLen_Host2NetworkOrder); Send(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); Send(socket__, serialized, 0, requestLen, 0); return 0; } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return -1; } finally { OnAfterSend(null); } } /// <summary> /// Sends the specified bytes with error level information. /// </summary> /// <param name="_bytes">Bytes to be sent.</param> /// <param name="_errorLevel">Error level information.</param> /// <returns>Zero on success.</returns> public int Send(byte[] _bytes, ErrorLevel _errorLevel) { try { OnBeforeSend(null); DataPackage dp = new DataPackage(); dp.Bytes = _bytes; dp.ActualBufferLength = _bytes.Length; dp.ErrorLevel = _errorLevel; dp.StreamType = StreamType.stByteArray; byte[] serialized = DataPackage.Serialize((DataPackage)dp); int requestLen = serialized.Length; int requestLen_Host2NetworkOrder = IPAddress.HostToNetworkOrder(requestLen); byte[] requestLen_Host2NetworkOrder_Array = BitConverter.GetBytes(requestLen_Host2NetworkOrder); Send(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); Send(socket__, serialized, 0, requestLen, 0); return 0; } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return -1; } finally { OnAfterSend(null); } } /// <summary> /// Sends a specified string. /// </summary> /// <param name="_str">String to be sent.</param> /// <returns>Zero on success.</returns> public int Send(string _str) { return this.Send(_str, ErrorLevel.elOK); } /// <summary> /// Sends a specified DataSet object. /// </summary> /// <param name="_dataSet">DataSet object to be sent.</param> /// <returns>Zero on success.</returns> public int Send(DataSet _dataSet) { return this.Send(_dataSet, ErrorLevel.elOK); } /// <summary> /// Sends the specified bytes. /// </summary> /// <param name="_bytes">Bytes to be sent.</param> /// <returns>Zero on success.</returns> public int Send(byte[] _bytes) { return this.Send(_bytes, ErrorLevel.elOK); } /// <summary> /// Receives a string from remote. /// </summary> /// <returns>String received.</returns> public ResponseResultGeneric<string> ReceiveString() { try { OnBeforeReceive(null); byte[] requestLen_Host2NetworkOrder_Array = new byte[4]; Receive(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); int requestLen_Host2NetworkOrder = BitConverter.ToInt32(requestLen_Host2NetworkOrder_Array, 0); int requestLen = IPAddress.NetworkToHostOrder(requestLen_Host2NetworkOrder); byte[] finalBytesReceive = new byte[requestLen]; Receive(socket__, finalBytesReceive, 0, requestLen, 0); DataPackage dp = (DataPackage)DataPackage.Deserialize(finalBytesReceive); if (dp.StreamType == StreamType.stString) { string ret = Encoding.ASCII.GetString(dp.Bytes, 0, dp.ActualBufferLength); ResponseResultGeneric<string> result = new ResponseResultGeneric<string>(); result.Result = ret; result.ErrorLevel = dp.ErrorLevel; return result; } else { return null; } } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return null; } finally { OnAfterReceive(null); } } /// <summary> /// Receives a DataSet object from remote. /// </summary> /// <returns>Received DataSet object.</returns> public ResponseResultGeneric<DataSet> ReceiveDataSet() { try { OnBeforeReceive(null); byte[] requestLen_Host2NetworkOrder_Array = new byte[4]; Receive(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); int requestLen_Host2NetworkOrder = BitConverter.ToInt32(requestLen_Host2NetworkOrder_Array, 0); int requestLen = IPAddress.NetworkToHostOrder(requestLen_Host2NetworkOrder); byte[] finalBytesReceive = new byte[requestLen]; Receive(socket__, finalBytesReceive, 0, requestLen, 0); DataPackage dp = (DataPackage)DataPackage.Deserialize(finalBytesReceive); if (dp.StreamType == StreamType.stDataSet) { ResponseResultGeneric<DataSet> result = new ResponseResultGeneric<DataSet>(); result.Result = (DataSet)DataPackage.Deserialize(dp.Bytes); result.ErrorLevel = dp.ErrorLevel; return result; } else { return null; } } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return null; } finally { OnAfterReceive(null); } } /// <summary> /// Receives the byte array from remote. /// </summary> /// <returns>Received bytes.</returns> public ResponseResultGeneric<byte[]> ReceiveByteArray() { try { OnBeforeReceive(null); byte[] requestLen_Host2NetworkOrder_Array = new byte[4]; Receive(socket__, requestLen_Host2NetworkOrder_Array, 0, 4, 0); int requestLen_Host2NetworkOrder = BitConverter.ToInt32(requestLen_Host2NetworkOrder_Array, 0); int requestLen = IPAddress.NetworkToHostOrder(requestLen_Host2NetworkOrder); byte[] finalBytesReceive = new byte[requestLen]; Receive(socket__, finalBytesReceive, 0, requestLen, 0); DataPackage dp = (DataPackage)DataPackage.Deserialize(finalBytesReceive); if (dp.StreamType == StreamType.stByteArray) { ResponseResultGeneric<byte[]> result = new ResponseResultGeneric<byte[]>(); result.Result = dp.Bytes; result.ErrorLevel = dp.ErrorLevel; return result; } else { return null; } } catch (Exception ex) { this.OnCommunicationException(new ExceptionEventArgs(ex)); return null; } finally { OnAfterReceive(null); } } #endregion } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Squareup.Okhttp.Internal { // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/Util", DoNotGenerateAcw=true)] public sealed partial class Util : global::Java.Lang.Object { static IntPtr EMPTY_BYTE_ARRAY_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/field[@name='EMPTY_BYTE_ARRAY']" [Register ("EMPTY_BYTE_ARRAY")] public static IList<byte> EmptyByteArray { get { if (EMPTY_BYTE_ARRAY_jfieldId == IntPtr.Zero) EMPTY_BYTE_ARRAY_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "EMPTY_BYTE_ARRAY", "[B"); return JavaArray<byte>.FromJniHandle (JNIEnv.GetStaticObjectField (class_ref, EMPTY_BYTE_ARRAY_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (EMPTY_BYTE_ARRAY_jfieldId == IntPtr.Zero) EMPTY_BYTE_ARRAY_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "EMPTY_BYTE_ARRAY", "[B"); IntPtr native_value = JavaArray<byte>.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, EMPTY_BYTE_ARRAY_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr EMPTY_STRING_ARRAY_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/field[@name='EMPTY_STRING_ARRAY']" [Register ("EMPTY_STRING_ARRAY")] public static IList<string> EmptyStringArray { get { if (EMPTY_STRING_ARRAY_jfieldId == IntPtr.Zero) EMPTY_STRING_ARRAY_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "EMPTY_STRING_ARRAY", "[Ljava/lang/String;"); return JavaArray<string>.FromJniHandle (JNIEnv.GetStaticObjectField (class_ref, EMPTY_STRING_ARRAY_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (EMPTY_STRING_ARRAY_jfieldId == IntPtr.Zero) EMPTY_STRING_ARRAY_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "EMPTY_STRING_ARRAY", "[Ljava/lang/String;"); IntPtr native_value = JavaArray<string>.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, EMPTY_STRING_ARRAY_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr ISO_8859_1_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/field[@name='ISO_8859_1']" [Register ("ISO_8859_1")] public static global::Java.Nio.Charset.Charset Iso88591 { get { if (ISO_8859_1_jfieldId == IntPtr.Zero) ISO_8859_1_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ISO_8859_1", "Ljava/nio/charset/Charset;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ISO_8859_1_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Nio.Charset.Charset> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (ISO_8859_1_jfieldId == IntPtr.Zero) ISO_8859_1_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ISO_8859_1", "Ljava/nio/charset/Charset;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, ISO_8859_1_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr US_ASCII_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/field[@name='US_ASCII']" [Register ("US_ASCII")] public static global::Java.Nio.Charset.Charset UsAscii { get { if (US_ASCII_jfieldId == IntPtr.Zero) US_ASCII_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "US_ASCII", "Ljava/nio/charset/Charset;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, US_ASCII_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Nio.Charset.Charset> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (US_ASCII_jfieldId == IntPtr.Zero) US_ASCII_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "US_ASCII", "Ljava/nio/charset/Charset;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, US_ASCII_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr UTF_8_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/field[@name='UTF_8']" [Register ("UTF_8")] public static global::Java.Nio.Charset.Charset Utf8 { get { if (UTF_8_jfieldId == IntPtr.Zero) UTF_8_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "UTF_8", "Ljava/nio/charset/Charset;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, UTF_8_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Nio.Charset.Charset> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (UTF_8_jfieldId == IntPtr.Zero) UTF_8_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "UTF_8", "Ljava/nio/charset/Charset;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, UTF_8_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/squareup/okhttp/internal/Util", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Util); } } internal Util (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_checkOffsetAndCount_III; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='checkOffsetAndCount' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]" [Register ("checkOffsetAndCount", "(III)V", "")] public static void CheckOffsetAndCount (int p0, int p1, int p2) { if (id_checkOffsetAndCount_III == IntPtr.Zero) id_checkOffsetAndCount_III = JNIEnv.GetStaticMethodID (class_ref, "checkOffsetAndCount", "(III)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_checkOffsetAndCount_III, new JValue (p0), new JValue (p1), new JValue (p2)); } static IntPtr id_closeAll_Ljava_io_Closeable_Ljava_io_Closeable_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='closeAll' and count(parameter)=2 and parameter[1][@type='java.io.Closeable'] and parameter[2][@type='java.io.Closeable']]" [Register ("closeAll", "(Ljava/io/Closeable;Ljava/io/Closeable;)V", "")] public static void CloseAll (global::Java.IO.ICloseable p0, global::Java.IO.ICloseable p1) { if (id_closeAll_Ljava_io_Closeable_Ljava_io_Closeable_ == IntPtr.Zero) id_closeAll_Ljava_io_Closeable_Ljava_io_Closeable_ = JNIEnv.GetStaticMethodID (class_ref, "closeAll", "(Ljava/io/Closeable;Ljava/io/Closeable;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_closeAll_Ljava_io_Closeable_Ljava_io_Closeable_, new JValue (p0), new JValue (p1)); } static IntPtr id_closeQuietly_Ljava_io_Closeable_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='closeQuietly' and count(parameter)=1 and parameter[1][@type='java.io.Closeable']]" [Register ("closeQuietly", "(Ljava/io/Closeable;)V", "")] public static void CloseQuietly (global::Java.IO.ICloseable p0) { if (id_closeQuietly_Ljava_io_Closeable_ == IntPtr.Zero) id_closeQuietly_Ljava_io_Closeable_ = JNIEnv.GetStaticMethodID (class_ref, "closeQuietly", "(Ljava/io/Closeable;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_closeQuietly_Ljava_io_Closeable_, new JValue (p0)); } static IntPtr id_closeQuietly_Ljava_net_ServerSocket_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='closeQuietly' and count(parameter)=1 and parameter[1][@type='java.net.ServerSocket']]" [Register ("closeQuietly", "(Ljava/net/ServerSocket;)V", "")] public static void CloseQuietly (global::Java.Net.ServerSocket p0) { if (id_closeQuietly_Ljava_net_ServerSocket_ == IntPtr.Zero) id_closeQuietly_Ljava_net_ServerSocket_ = JNIEnv.GetStaticMethodID (class_ref, "closeQuietly", "(Ljava/net/ServerSocket;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_closeQuietly_Ljava_net_ServerSocket_, new JValue (p0)); } static IntPtr id_closeQuietly_Ljava_net_Socket_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='closeQuietly' and count(parameter)=1 and parameter[1][@type='java.net.Socket']]" [Register ("closeQuietly", "(Ljava/net/Socket;)V", "")] public static void CloseQuietly (global::Java.Net.Socket p0) { if (id_closeQuietly_Ljava_net_Socket_ == IntPtr.Zero) id_closeQuietly_Ljava_net_Socket_ = JNIEnv.GetStaticMethodID (class_ref, "closeQuietly", "(Ljava/net/Socket;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_closeQuietly_Ljava_net_Socket_, new JValue (p0)); } static IntPtr id_copy_Ljava_io_InputStream_Ljava_io_OutputStream_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='copy' and count(parameter)=2 and parameter[1][@type='java.io.InputStream'] and parameter[2][@type='java.io.OutputStream']]" [Register ("copy", "(Ljava/io/InputStream;Ljava/io/OutputStream;)I", "")] public static int Copy (global::System.IO.Stream p0, global::System.IO.Stream p1) { if (id_copy_Ljava_io_InputStream_Ljava_io_OutputStream_ == IntPtr.Zero) id_copy_Ljava_io_InputStream_Ljava_io_OutputStream_ = JNIEnv.GetStaticMethodID (class_ref, "copy", "(Ljava/io/InputStream;Ljava/io/OutputStream;)I"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); IntPtr native_p1 = global::Android.Runtime.OutputStreamAdapter.ToLocalJniHandle (p1); int __ret = JNIEnv.CallStaticIntMethod (class_ref, id_copy_Ljava_io_InputStream_Ljava_io_OutputStream_, new JValue (native_p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); return __ret; } static IntPtr id_daemonThreadFactory_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='daemonThreadFactory' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("daemonThreadFactory", "(Ljava/lang/String;)Ljava/util/concurrent/ThreadFactory;", "")] public static global::Java.Util.Concurrent.IThreadFactory DaemonThreadFactory (string p0) { if (id_daemonThreadFactory_Ljava_lang_String_ == IntPtr.Zero) id_daemonThreadFactory_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "daemonThreadFactory", "(Ljava/lang/String;)Ljava/util/concurrent/ThreadFactory;"); IntPtr native_p0 = JNIEnv.NewString (p0); global::Java.Util.Concurrent.IThreadFactory __ret = global::Java.Lang.Object.GetObject<global::Java.Util.Concurrent.IThreadFactory> (JNIEnv.CallStaticObjectMethod (class_ref, id_daemonThreadFactory_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_deleteContents_Ljava_io_File_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='deleteContents' and count(parameter)=1 and parameter[1][@type='java.io.File']]" [Register ("deleteContents", "(Ljava/io/File;)V", "")] public static void DeleteContents (global::Java.IO.File p0) { if (id_deleteContents_Ljava_io_File_ == IntPtr.Zero) id_deleteContents_Ljava_io_File_ = JNIEnv.GetStaticMethodID (class_ref, "deleteContents", "(Ljava/io/File;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_deleteContents_Ljava_io_File_, new JValue (p0)); } static IntPtr id_equal_Ljava_lang_Object_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='equal' and count(parameter)=2 and parameter[1][@type='java.lang.Object'] and parameter[2][@type='java.lang.Object']]" [Register ("equal", "(Ljava/lang/Object;Ljava/lang/Object;)Z", "")] public static bool Equal (global::Java.Lang.Object p0, global::Java.Lang.Object p1) { if (id_equal_Ljava_lang_Object_Ljava_lang_Object_ == IntPtr.Zero) id_equal_Ljava_lang_Object_Ljava_lang_Object_ = JNIEnv.GetStaticMethodID (class_ref, "equal", "(Ljava/lang/Object;Ljava/lang/Object;)Z"); bool __ret = JNIEnv.CallStaticBooleanMethod (class_ref, id_equal_Ljava_lang_Object_Ljava_lang_Object_, new JValue (p0), new JValue (p1)); return __ret; } static IntPtr id_getDefaultPort_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='getDefaultPort' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("getDefaultPort", "(Ljava/lang/String;)I", "")] public static int GetDefaultPort (string p0) { if (id_getDefaultPort_Ljava_lang_String_ == IntPtr.Zero) id_getDefaultPort_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "getDefaultPort", "(Ljava/lang/String;)I"); IntPtr native_p0 = JNIEnv.NewString (p0); int __ret = JNIEnv.CallStaticIntMethod (class_ref, id_getDefaultPort_Ljava_lang_String_, new JValue (native_p0)); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_getEffectivePort_Ljava_net_URI_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='getEffectivePort' and count(parameter)=1 and parameter[1][@type='java.net.URI']]" [Register ("getEffectivePort", "(Ljava/net/URI;)I", "")] public static int GetEffectivePort (global::Java.Net.URI p0) { if (id_getEffectivePort_Ljava_net_URI_ == IntPtr.Zero) id_getEffectivePort_Ljava_net_URI_ = JNIEnv.GetStaticMethodID (class_ref, "getEffectivePort", "(Ljava/net/URI;)I"); int __ret = JNIEnv.CallStaticIntMethod (class_ref, id_getEffectivePort_Ljava_net_URI_, new JValue (p0)); return __ret; } static IntPtr id_getEffectivePort_Ljava_net_URL_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='getEffectivePort' and count(parameter)=1 and parameter[1][@type='java.net.URL']]" [Register ("getEffectivePort", "(Ljava/net/URL;)I", "")] public static int GetEffectivePort (global::Java.Net.URL p0) { if (id_getEffectivePort_Ljava_net_URL_ == IntPtr.Zero) id_getEffectivePort_Ljava_net_URL_ = JNIEnv.GetStaticMethodID (class_ref, "getEffectivePort", "(Ljava/net/URL;)I"); int __ret = JNIEnv.CallStaticIntMethod (class_ref, id_getEffectivePort_Ljava_net_URL_, new JValue (p0)); return __ret; } static IntPtr id_hash_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='hash' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("hash", "(Ljava/lang/String;)Ljava/lang/String;", "")] public static string Hash (string p0) { if (id_hash_Ljava_lang_String_ == IntPtr.Zero) id_hash_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "hash", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_hash_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_immutableList_Ljava_util_List_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='immutableList' and count(parameter)=1 and parameter[1][@type='java.util.List']]" [Register ("immutableList", "(Ljava/util/List;)Ljava/util/List;", "")] public static global::System.Collections.IList ImmutableList (global::System.Collections.IList p0) { if (id_immutableList_Ljava_util_List_ == IntPtr.Zero) id_immutableList_Ljava_util_List_ = JNIEnv.GetStaticMethodID (class_ref, "immutableList", "(Ljava/util/List;)Ljava/util/List;"); IntPtr native_p0 = global::Android.Runtime.JavaList.ToLocalJniHandle (p0); global::System.Collections.IList __ret = global::Android.Runtime.JavaList.FromJniHandle (JNIEnv.CallStaticObjectMethod (class_ref, id_immutableList_Ljava_util_List_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_pokeInt_arrayBIILjava_nio_ByteOrder_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='pokeInt' and count(parameter)=4 and parameter[1][@type='byte[]'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='java.nio.ByteOrder']]" [Register ("pokeInt", "([BIILjava/nio/ByteOrder;)V", "")] public static void PokeInt (byte[] p0, int p1, int p2, global::Java.Nio.ByteOrder p3) { if (id_pokeInt_arrayBIILjava_nio_ByteOrder_ == IntPtr.Zero) id_pokeInt_arrayBIILjava_nio_ByteOrder_ = JNIEnv.GetStaticMethodID (class_ref, "pokeInt", "([BIILjava/nio/ByteOrder;)V"); IntPtr native_p0 = JNIEnv.NewArray (p0); JNIEnv.CallStaticVoidMethod (class_ref, id_pokeInt_arrayBIILjava_nio_ByteOrder_, new JValue (native_p0), new JValue (p1), new JValue (p2), new JValue (p3)); if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_readAsciiLine_Ljava_io_InputStream_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='readAsciiLine' and count(parameter)=1 and parameter[1][@type='java.io.InputStream']]" [Register ("readAsciiLine", "(Ljava/io/InputStream;)Ljava/lang/String;", "")] public static string ReadAsciiLine (global::System.IO.Stream p0) { if (id_readAsciiLine_Ljava_io_InputStream_ == IntPtr.Zero) id_readAsciiLine_Ljava_io_InputStream_ = JNIEnv.GetStaticMethodID (class_ref, "readAsciiLine", "(Ljava/io/InputStream;)Ljava/lang/String;"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_readAsciiLine_Ljava_io_InputStream_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_readFully_Ljava_io_InputStream_arrayB; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='readFully' and count(parameter)=2 and parameter[1][@type='java.io.InputStream'] and parameter[2][@type='byte[]']]" [Register ("readFully", "(Ljava/io/InputStream;[B)V", "")] public static void ReadFully (global::System.IO.Stream p0, byte[] p1) { if (id_readFully_Ljava_io_InputStream_arrayB == IntPtr.Zero) id_readFully_Ljava_io_InputStream_arrayB = JNIEnv.GetStaticMethodID (class_ref, "readFully", "(Ljava/io/InputStream;[B)V"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); IntPtr native_p1 = JNIEnv.NewArray (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_readFully_Ljava_io_InputStream_arrayB, new JValue (native_p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p0); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_readFully_Ljava_io_InputStream_arrayBII; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='readFully' and count(parameter)=4 and parameter[1][@type='java.io.InputStream'] and parameter[2][@type='byte[]'] and parameter[3][@type='int'] and parameter[4][@type='int']]" [Register ("readFully", "(Ljava/io/InputStream;[BII)V", "")] public static void ReadFully (global::System.IO.Stream p0, byte[] p1, int p2, int p3) { if (id_readFully_Ljava_io_InputStream_arrayBII == IntPtr.Zero) id_readFully_Ljava_io_InputStream_arrayBII = JNIEnv.GetStaticMethodID (class_ref, "readFully", "(Ljava/io/InputStream;[BII)V"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); IntPtr native_p1 = JNIEnv.NewArray (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_readFully_Ljava_io_InputStream_arrayBII, new JValue (native_p0), new JValue (native_p1), new JValue (p2), new JValue (p3)); JNIEnv.DeleteLocalRef (native_p0); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_readFully_Ljava_io_Reader_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='readFully' and count(parameter)=1 and parameter[1][@type='java.io.Reader']]" [Register ("readFully", "(Ljava/io/Reader;)Ljava/lang/String;", "")] public static string ReadFully (global::Java.IO.Reader p0) { if (id_readFully_Ljava_io_Reader_ == IntPtr.Zero) id_readFully_Ljava_io_Reader_ = JNIEnv.GetStaticMethodID (class_ref, "readFully", "(Ljava/io/Reader;)Ljava/lang/String;"); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_readFully_Ljava_io_Reader_, new JValue (p0)), JniHandleOwnership.TransferLocalRef); return __ret; } static IntPtr id_readSingleByte_Ljava_io_InputStream_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='readSingleByte' and count(parameter)=1 and parameter[1][@type='java.io.InputStream']]" [Register ("readSingleByte", "(Ljava/io/InputStream;)I", "")] public static int ReadSingleByte (global::System.IO.Stream p0) { if (id_readSingleByte_Ljava_io_InputStream_ == IntPtr.Zero) id_readSingleByte_Ljava_io_InputStream_ = JNIEnv.GetStaticMethodID (class_ref, "readSingleByte", "(Ljava/io/InputStream;)I"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); int __ret = JNIEnv.CallStaticIntMethod (class_ref, id_readSingleByte_Ljava_io_InputStream_, new JValue (native_p0)); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_skipAll_Ljava_io_InputStream_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='skipAll' and count(parameter)=1 and parameter[1][@type='java.io.InputStream']]" [Register ("skipAll", "(Ljava/io/InputStream;)V", "")] public static void SkipAll (global::System.IO.Stream p0) { if (id_skipAll_Ljava_io_InputStream_ == IntPtr.Zero) id_skipAll_Ljava_io_InputStream_ = JNIEnv.GetStaticMethodID (class_ref, "skipAll", "(Ljava/io/InputStream;)V"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); JNIEnv.CallStaticVoidMethod (class_ref, id_skipAll_Ljava_io_InputStream_, new JValue (native_p0)); JNIEnv.DeleteLocalRef (native_p0); } static IntPtr id_skipByReading_Ljava_io_InputStream_J; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='skipByReading' and count(parameter)=2 and parameter[1][@type='java.io.InputStream'] and parameter[2][@type='long']]" [Register ("skipByReading", "(Ljava/io/InputStream;J)J", "")] public static long SkipByReading (global::System.IO.Stream p0, long p1) { if (id_skipByReading_Ljava_io_InputStream_J == IntPtr.Zero) id_skipByReading_Ljava_io_InputStream_J = JNIEnv.GetStaticMethodID (class_ref, "skipByReading", "(Ljava/io/InputStream;J)J"); IntPtr native_p0 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p0); long __ret = JNIEnv.CallStaticLongMethod (class_ref, id_skipByReading_Ljava_io_InputStream_J, new JValue (native_p0), new JValue (p1)); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_writeSingleByte_Ljava_io_OutputStream_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='Util']/method[@name='writeSingleByte' and count(parameter)=2 and parameter[1][@type='java.io.OutputStream'] and parameter[2][@type='int']]" [Register ("writeSingleByte", "(Ljava/io/OutputStream;I)V", "")] public static void WriteSingleByte (global::System.IO.Stream p0, int p1) { if (id_writeSingleByte_Ljava_io_OutputStream_I == IntPtr.Zero) id_writeSingleByte_Ljava_io_OutputStream_I = JNIEnv.GetStaticMethodID (class_ref, "writeSingleByte", "(Ljava/io/OutputStream;I)V"); IntPtr native_p0 = global::Android.Runtime.OutputStreamAdapter.ToLocalJniHandle (p0); JNIEnv.CallStaticVoidMethod (class_ref, id_writeSingleByte_Ljava_io_OutputStream_I, new JValue (native_p0), new JValue (p1)); JNIEnv.DeleteLocalRef (native_p0); } } }
// ----------------------------------------------------------------------------------------- // <copyright file="CloudStorageAccountTests.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using System; using System.Globalization; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.WindowsAzure.Storage.Shared.Protocol; #if WINDOWS_DESKTOP using Microsoft.VisualStudio.TestTools.UnitTesting; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #endif namespace Microsoft.WindowsAzure.Storage.Core.Util { [TestClass] public class CloudStorageAccountTests : TestBase { private string token = "?sp=abcde&sig=1"; [TestMethod] [Description("Anonymous credentials")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsAnonymous() { StorageCredentials cred = new StorageCredentials(); Assert.IsNull(cred.AccountName); Assert.IsTrue(cred.IsAnonymous); Assert.IsFalse(cred.IsSAS); Assert.IsFalse(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc?querya=1"); Assert.AreEqual(testUri, cred.TransformUri(testUri)); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); TestHelper.ExpectedException<InvalidOperationException>( () => cred.UpdateKey(base64EncodedDummyKey), "Updating shared key on an anonymous credentials instance should fail."); } [TestMethod] [Description("Shared key credentials")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsSharedKey() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); Assert.AreEqual(TestBase.TargetTenantConfig.AccountName, cred.AccountName, false); Assert.IsFalse(cred.IsAnonymous); Assert.IsFalse(cred.IsSAS); Assert.IsTrue(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc?querya=1"); Assert.AreEqual(testUri, cred.TransformUri(testUri)); Assert.AreEqual(TestBase.TargetTenantConfig.AccountKey, cred.ExportBase64EncodedKey()); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); cred.UpdateKey(base64EncodedDummyKey); Assert.AreEqual(base64EncodedDummyKey, cred.ExportBase64EncodedKey()); #if !(WINDOWS_RT || ASPNET_K) dummyKey[0] = 3; base64EncodedDummyKey = Convert.ToBase64String(dummyKey); cred.UpdateKey(dummyKey); Assert.AreEqual(base64EncodedDummyKey, cred.ExportBase64EncodedKey()); #endif } [TestMethod] [Description("SAS token credentials")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsSAS() { StorageCredentials cred = new StorageCredentials(token); Assert.IsNull(cred.AccountName); Assert.IsFalse(cred.IsAnonymous); Assert.IsTrue(cred.IsSAS); Assert.IsFalse(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc"); Assert.AreEqual(testUri.AbsoluteUri + token + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion, cred.TransformUri(testUri).AbsoluteUri, true); testUri = new Uri("http://test/abc?query=a&query2=b"); string expectedUri = testUri.AbsoluteUri + "&" + token.Substring(1) + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion; Assert.AreEqual(expectedUri, cred.TransformUri(testUri).AbsoluteUri, true); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); TestHelper.ExpectedException<InvalidOperationException>( () => cred.UpdateKey(base64EncodedDummyKey), "Updating shared key on a SAS credentials instance should fail."); } [TestMethod] [Description("CloudStorageAccount object with an empty key value.")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsEmptyKeyValue() { string accountName = TestBase.TargetTenantConfig.AccountName; string keyValue = TestBase.TargetTenantConfig.AccountKey; string emptyKeyValueAsString = string.Empty; string emptyKeyConnectionString = string.Format(CultureInfo.InvariantCulture, "DefaultEndpointsProtocol=https;AccountName={0};AccountKey=", accountName); StorageCredentials credentials1 = new StorageCredentials(accountName, emptyKeyValueAsString); Assert.AreEqual(accountName, credentials1.AccountName); Assert.IsFalse(credentials1.IsAnonymous); Assert.IsFalse(credentials1.IsSAS); Assert.IsTrue(credentials1.IsSharedKey); Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(credentials1.ExportKey())); CloudStorageAccount account1 = new CloudStorageAccount(credentials1, true); Assert.AreEqual(emptyKeyConnectionString, account1.ToString(true)); Assert.IsNotNull(account1.Credentials); Assert.AreEqual(accountName, account1.Credentials.AccountName); Assert.IsFalse(account1.Credentials.IsAnonymous); Assert.IsFalse(account1.Credentials.IsSAS); Assert.IsTrue(account1.Credentials.IsSharedKey); Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account1.Credentials.ExportKey())); CloudStorageAccount account2 = CloudStorageAccount.Parse(emptyKeyConnectionString); Assert.AreEqual(emptyKeyConnectionString, account2.ToString(true)); Assert.IsNotNull(account2.Credentials); Assert.AreEqual(accountName, account2.Credentials.AccountName); Assert.IsFalse(account2.Credentials.IsAnonymous); Assert.IsFalse(account2.Credentials.IsSAS); Assert.IsTrue(account2.Credentials.IsSharedKey); Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account2.Credentials.ExportKey())); CloudStorageAccount account3; bool isValidAccount3 = CloudStorageAccount.TryParse(emptyKeyConnectionString, out account3); Assert.IsTrue(isValidAccount3); Assert.IsNotNull(account3); Assert.AreEqual(emptyKeyConnectionString, account3.ToString(true)); Assert.IsNotNull(account3.Credentials); Assert.AreEqual(accountName, account3.Credentials.AccountName); Assert.IsFalse(account3.Credentials.IsAnonymous); Assert.IsFalse(account3.Credentials.IsSAS); Assert.IsTrue(account3.Credentials.IsSharedKey); Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account3.Credentials.ExportKey())); StorageCredentials credentials2 = new StorageCredentials(accountName, keyValue); Assert.AreEqual(accountName, credentials2.AccountName); Assert.IsFalse(credentials2.IsAnonymous); Assert.IsFalse(credentials2.IsSAS); Assert.IsTrue(credentials2.IsSharedKey); Assert.AreEqual(keyValue, Convert.ToBase64String(credentials2.ExportKey())); credentials2.UpdateKey(emptyKeyValueAsString, null); Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(credentials2.ExportKey())); #if !(WINDOWS_RT || ASPNET_K) byte[] emptyKeyValueAsByteArray = new byte[0]; StorageCredentials credentials3 = new StorageCredentials(accountName, keyValue); Assert.AreEqual(accountName, credentials3.AccountName); Assert.IsFalse(credentials3.IsAnonymous); Assert.IsFalse(credentials3.IsSAS); Assert.IsTrue(credentials3.IsSharedKey); Assert.AreEqual(keyValue, Convert.ToBase64String(credentials3.ExportKey())); credentials3.UpdateKey(emptyKeyValueAsByteArray, null); Assert.AreEqual(Convert.ToBase64String(emptyKeyValueAsByteArray), Convert.ToBase64String(credentials3.ExportKey())); #endif } [TestMethod] [Description("CloudStorageAccount object with a null key value.")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsNullKeyValue() { string accountName = TestBase.TargetTenantConfig.AccountName; string keyValue = TestBase.TargetTenantConfig.AccountKey; string nullKeyValueAsString = null; TestHelper.ExpectedException<ArgumentNullException>(() => { StorageCredentials credentials1 = new StorageCredentials(accountName, nullKeyValueAsString); }, "Cannot create key with a null value."); StorageCredentials credentials2 = new StorageCredentials(accountName, keyValue); Assert.AreEqual(accountName, credentials2.AccountName); Assert.IsFalse(credentials2.IsAnonymous); Assert.IsFalse(credentials2.IsSAS); Assert.IsTrue(credentials2.IsSharedKey); Assert.AreEqual(keyValue, Convert.ToBase64String(credentials2.ExportKey())); TestHelper.ExpectedException<ArgumentNullException>(() => { credentials2.UpdateKey(nullKeyValueAsString, null); }, "Cannot update key with a null string value."); #if !(WINDOWS_RT || ASPNET_K) byte[] nullKeyValueAsByteArray = null; StorageCredentials credentials3 = new StorageCredentials(accountName, keyValue); Assert.AreEqual(accountName, credentials3.AccountName); Assert.IsFalse(credentials3.IsAnonymous); Assert.IsFalse(credentials3.IsSAS); Assert.IsTrue(credentials3.IsSharedKey); Assert.AreEqual(keyValue, Convert.ToBase64String(credentials3.ExportKey())); TestHelper.ExpectedException<ArgumentNullException>(() => { credentials3.UpdateKey(nullKeyValueAsByteArray, null); }, "Cannot update key with a null byte array value."); #endif } [TestMethod] [Description("Compare credentials for equality")] [TestCategory(ComponentCategory.Auth)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void StorageCredentialsEquality() { StorageCredentials credSharedKey1 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); StorageCredentials credSharedKey2 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); StorageCredentials credSharedKey3 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName + "1", TestBase.TargetTenantConfig.AccountKey); StorageCredentials credSharedKey4 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, Convert.ToBase64String(new byte[] { 0, 1, 2 })); StorageCredentials credSAS1 = new StorageCredentials(token); StorageCredentials credSAS2 = new StorageCredentials(token); StorageCredentials credSAS3 = new StorageCredentials(token + "1"); StorageCredentials credAnonymous1 = new StorageCredentials(); StorageCredentials credAnonymous2 = new StorageCredentials(); Assert.IsTrue(credSharedKey1.Equals(credSharedKey2)); Assert.IsFalse(credSharedKey1.Equals(credSharedKey3)); Assert.IsFalse(credSharedKey1.Equals(credSharedKey4)); Assert.IsTrue(credSAS1.Equals(credSAS2)); Assert.IsFalse(credSAS1.Equals(credSAS3)); Assert.IsTrue(credAnonymous1.Equals(credAnonymous2)); Assert.IsFalse(credSharedKey1.Equals(credSAS1)); Assert.IsFalse(credSharedKey1.Equals(credAnonymous1)); Assert.IsFalse(credSAS1.Equals(credAnonymous1)); } private void AccountsAreEqual(CloudStorageAccount a, CloudStorageAccount b) { // endpoints are the same Assert.AreEqual(a.BlobEndpoint, b.BlobEndpoint); Assert.AreEqual(a.QueueEndpoint, b.QueueEndpoint); Assert.AreEqual(a.TableEndpoint, b.TableEndpoint); Assert.AreEqual(a.FileEndpoint, b.FileEndpoint); // storage uris are the same Assert.AreEqual(a.BlobStorageUri, b.BlobStorageUri); Assert.AreEqual(a.QueueStorageUri, b.QueueStorageUri); Assert.AreEqual(a.TableStorageUri, b.TableStorageUri); Assert.AreEqual(a.FileStorageUri, b.FileStorageUri); // seralized representatons are the same. string aToStringNoSecrets = a.ToString(); string aToStringWithSecrets = a.ToString(true); string bToStringNoSecrets = b.ToString(false); string bToStringWithSecrets = b.ToString(true); Assert.AreEqual(aToStringNoSecrets, bToStringNoSecrets, false); Assert.AreEqual(aToStringWithSecrets, bToStringWithSecrets, false); // credentials are the same if (a.Credentials != null && b.Credentials != null) { Assert.AreEqual(a.Credentials.IsAnonymous, b.Credentials.IsAnonymous); Assert.AreEqual(a.Credentials.IsSAS, b.Credentials.IsSAS); Assert.AreEqual(a.Credentials.IsSharedKey, b.Credentials.IsSharedKey); // make sure if (!a.Credentials.IsAnonymous && a.Credentials != CloudStorageAccount.DevelopmentStorageAccount.Credentials && b.Credentials != CloudStorageAccount.DevelopmentStorageAccount.Credentials) { Assert.AreNotEqual(aToStringWithSecrets, bToStringNoSecrets, true); } } else if (a.Credentials == null && b.Credentials == null) { return; } else { Assert.Fail("credentials mismatch"); } } [TestMethod] [Description("DevStore account")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevelopmentStorageAccount() { CloudStorageAccount devstoreAccount = CloudStorageAccount.DevelopmentStorageAccount; Assert.AreEqual(devstoreAccount.BlobEndpoint, new Uri("http://127.0.0.1:10000/devstoreaccount1")); Assert.AreEqual(devstoreAccount.QueueEndpoint, new Uri("http://127.0.0.1:10001/devstoreaccount1")); Assert.AreEqual(devstoreAccount.TableEndpoint, new Uri("http://127.0.0.1:10002/devstoreaccount1")); Assert.AreEqual(devstoreAccount.BlobStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10000/devstoreaccount1-secondary")); Assert.AreEqual(devstoreAccount.QueueStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10001/devstoreaccount1-secondary")); Assert.AreEqual(devstoreAccount.TableStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10002/devstoreaccount1-secondary")); Assert.IsNull(devstoreAccount.FileStorageUri); string devstoreAccountToStringWithSecrets = devstoreAccount.ToString(true); CloudStorageAccount testAccount = CloudStorageAccount.Parse(devstoreAccountToStringWithSecrets); AccountsAreEqual(testAccount, devstoreAccount); CloudStorageAccount acct; if (!CloudStorageAccount.TryParse(devstoreAccountToStringWithSecrets, out acct)) { Assert.Fail("Expected TryParse success."); } } [TestMethod] [Description("Regular account with HTTP")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDefaultStorageAccountWithHttp() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, false); Assert.AreEqual(cloudStorageAccount.BlobEndpoint, new Uri(String.Format("http://{0}.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.QueueEndpoint, new Uri(String.Format("http://{0}.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.TableEndpoint, new Uri(String.Format("http://{0}.table.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.FileEndpoint, new Uri(String.Format("http://{0}.file.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.table.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.file.core.windows.net", TestBase.TargetTenantConfig.AccountName))); string cloudStorageAccountToStringNoSecrets = cloudStorageAccount.ToString(); string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true); CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets); AccountsAreEqual(testAccount, cloudStorageAccount); } [TestMethod] [Description("Regular account with HTTPS")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDefaultStorageAccountWithHttps() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true); Assert.AreEqual(cloudStorageAccount.BlobEndpoint, new Uri(String.Format("https://{0}.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.QueueEndpoint, new Uri(String.Format("https://{0}.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.TableEndpoint, new Uri(String.Format("https://{0}.table.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.FileEndpoint, new Uri(String.Format("https://{0}.file.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.table.core.windows.net", TestBase.TargetTenantConfig.AccountName))); Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.file.core.windows.net", TestBase.TargetTenantConfig.AccountName))); string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true); CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets); AccountsAreEqual(testAccount, cloudStorageAccount); } [TestMethod] [Description("Regular account with HTTP")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountEndpointSuffixWithHttp() { const string TestEndpointSuffix = "fake.endpoint.suffix"; CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse( string.Format( "DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, TestEndpointSuffix)); Assert.AreEqual(cloudStorageAccount.BlobEndpoint, new Uri(String.Format("http://{0}.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.QueueEndpoint, new Uri(String.Format("http://{0}.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.TableEndpoint, new Uri(String.Format("http://{0}.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.FileEndpoint, new Uri(String.Format("http://{0}.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri, new Uri(String.Format("http://{0}-secondary.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true); CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets); AccountsAreEqual(testAccount, cloudStorageAccount); } [TestMethod] [Description("Regular account with HTTPS")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountEndpointSuffixWithHttps() { const string TestEndpointSuffix = "fake.endpoint.suffix"; CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse( string.Format( "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, TestEndpointSuffix)); Assert.AreEqual(cloudStorageAccount.BlobEndpoint, new Uri(String.Format("https://{0}.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.QueueEndpoint, new Uri(String.Format("https://{0}.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.TableEndpoint, new Uri(String.Format("https://{0}.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.FileEndpoint, new Uri(String.Format("https://{0}.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri, new Uri(String.Format("https://{0}-secondary.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix))); string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true); CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets); AccountsAreEqual(testAccount, cloudStorageAccount); } [TestMethod] [Description("Regular account with HTTP")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountEndpointSuffixWithBlob() { const string TestEndpointSuffix = "fake.endpoint.suffix"; const string AlternateBlobEndpoint = "http://blob.other.endpoint/"; CloudStorageAccount testAccount = CloudStorageAccount.Parse( string.Format( "DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};BlobEndpoint={3}", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, TestEndpointSuffix, AlternateBlobEndpoint)); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(testAccount.ToString(true)); // make sure it round trips this.AccountsAreEqual(testAccount, cloudStorageAccount); } [TestMethod] [Description("Regular account with HTTP")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountConnectionStringRoundtrip() { string accountString1 = string.Format( "DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, "fake.endpoint.suffix"); string accountString2 = string.Format( "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); string accountString3 = string.Format( "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};QueueEndpoint={2}", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, "https://alternate.queue.endpoint/"); string accountString4 = string.Format( "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};QueueEndpoint={3}", TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey, "fake.endpoint.suffix", "https://alternate.queue.endpoint/"); connectionStringRoundtripHelper(accountString1); connectionStringRoundtripHelper(accountString2); connectionStringRoundtripHelper(accountString3); connectionStringRoundtripHelper(accountString4); } private void connectionStringRoundtripHelper(string accountString) { CloudStorageAccount originalAccount = CloudStorageAccount.Parse(accountString); CloudStorageAccount copiedAccount = CloudStorageAccount.Parse(originalAccount.ToString(true)); // make sure it round trips this.AccountsAreEqual(originalAccount, copiedAccount); } [TestMethod] [Description("Service client creation methods")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountClientMethods() { CloudStorageAccount account = new CloudStorageAccount(TestBase.StorageCredentials, false); CloudBlobClient blob = account.CreateCloudBlobClient(); CloudQueueClient queue = account.CreateCloudQueueClient(); CloudTableClient table = account.CreateCloudTableClient(); CloudFileClient file = account.CreateCloudFileClient(); // check endpoints Assert.AreEqual(account.BlobEndpoint, blob.BaseUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueEndpoint, queue.BaseUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableEndpoint, table.BaseUri, "Table endpoint doesn't match account"); Assert.AreEqual(account.FileEndpoint, file.BaseUri, "File endpoint doesn't match account"); // check storage uris Assert.AreEqual(account.BlobStorageUri, blob.StorageUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueStorageUri, queue.StorageUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableStorageUri, table.StorageUri, "Table endpoint doesn't match account"); Assert.AreEqual(account.FileStorageUri, file.StorageUri, "File endpoint doesn't match account"); // check creds Assert.AreEqual(account.Credentials, blob.Credentials, "Blob creds don't match account"); Assert.AreEqual(account.Credentials, queue.Credentials, "Queue creds don't match account"); Assert.AreEqual(account.Credentials, table.Credentials, "Table creds don't match account"); Assert.AreEqual(account.Credentials, file.Credentials, "File creds don't match account"); } [TestMethod] [Description("Service client creation methods")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountClientUriVerify() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true); CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("container1"); Assert.AreEqual(cloudStorageAccount.BlobEndpoint.ToString() + "container1", container.Uri.ToString()); CloudQueueClient queueClient = cloudStorageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("queue1"); Assert.AreEqual(cloudStorageAccount.QueueEndpoint.ToString() + "queue1", queue.Uri.ToString()); CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("table1"); Assert.AreEqual(cloudStorageAccount.TableEndpoint.ToString() + "table1", table.Uri.ToString()); CloudFileClient fileClient = cloudStorageAccount.CreateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference("share1"); Assert.AreEqual(cloudStorageAccount.FileEndpoint.ToString() + "share1", share.Uri.ToString()); } [TestMethod] [Description("TryParse should return false for invalid connection strings")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountTryParseNullEmpty() { CloudStorageAccount account; // TryParse should not throw exception when passing in null or empty string Assert.IsFalse(CloudStorageAccount.TryParse(null, out account)); Assert.IsFalse(CloudStorageAccount.TryParse(string.Empty, out account)); } [TestMethod] [Description("UseDevelopmentStorage=false should fail")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStoreNonTrueFails() { CloudStorageAccount account; Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false", out account)); } [TestMethod] [Description("UseDevelopmentStorage should fail when used with an account name")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStorePlusAccountFails() { CloudStorageAccount account; Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false;AccountName=devstoreaccount1", out account)); } [TestMethod] [Description("UseDevelopmentStorage should fail when used with a custom endpoint")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStorePlusEndpointFails() { CloudStorageAccount account; Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false;BlobEndpoint=http://127.0.0.1:1000/devstoreaccount1", out account)); } [TestMethod] [Description("Custom endpoints")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDefaultEndpointOverride() { CloudStorageAccount account; Assert.IsTrue(CloudStorageAccount.TryParse("DefaultEndpointsProtocol=http;BlobEndpoint=http://customdomain.com/;AccountName=asdf;AccountKey=123=", out account)); Assert.AreEqual(new Uri("http://customdomain.com/"), account.BlobEndpoint); Assert.IsNull(account.BlobStorageUri.SecondaryUri); } [TestMethod] [Description("Use DevStore with a proxy")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStoreProxyUri() { CloudStorageAccount account; Assert.IsTrue(CloudStorageAccount.TryParse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://ipv4.fiddler", out account)); Assert.AreEqual(new Uri("http://ipv4.fiddler:10000/devstoreaccount1"), account.BlobEndpoint); Assert.AreEqual(new Uri("http://ipv4.fiddler:10001/devstoreaccount1"), account.QueueEndpoint); Assert.AreEqual(new Uri("http://ipv4.fiddler:10002/devstoreaccount1"), account.TableEndpoint); Assert.AreEqual(new Uri("http://ipv4.fiddler:10000/devstoreaccount1-secondary"), account.BlobStorageUri.SecondaryUri); Assert.AreEqual(new Uri("http://ipv4.fiddler:10001/devstoreaccount1-secondary"), account.QueueStorageUri.SecondaryUri); Assert.AreEqual(new Uri("http://ipv4.fiddler:10002/devstoreaccount1-secondary"), account.TableStorageUri.SecondaryUri); Assert.IsNull(account.FileStorageUri); } [TestMethod] [Description("ToString method for DevStore account should not return endpoint info")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStoreRoundtrip() { string accountString = "UseDevelopmentStorage=true"; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method for DevStore account with a proxy should not return endpoint info")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDevStoreProxyRoundtrip() { string accountString = "UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://ipv4.fiddler/"; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method for regular account should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountDefaultCloudRoundtrip() { string accountString = "DefaultEndpointsProtocol=http;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method for custom endpoints should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountExplicitCloudRoundtrip() { string accountString = "BlobEndpoint=https://blobs/;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method for anonymous credentials should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountAnonymousRoundtrip() { string accountString = "BlobEndpoint=http://blobs/"; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); CloudStorageAccount account = new CloudStorageAccount(null, new Uri("http://blobs/"), null, null, null); AccountsAreEqual(account, CloudStorageAccount.Parse(account.ToString(true))); } [TestMethod] [Description("Parse method should ignore empty values")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountEmptyValues() { string accountString = ";BlobEndpoint=http://blobs/;;AccountName=test;;AccountKey=abc=;"; string validAccountString = "BlobEndpoint=http://blobs/;AccountName=test;AccountKey=abc="; Assert.AreEqual(validAccountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method with custom blob endpoint should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountJustBlobToString() { string accountString = "BlobEndpoint=http://blobs/;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method with custom queue endpoint should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountJustQueueToString() { string accountString = "QueueEndpoint=http://queue/;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method with custom table endpoint should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountJustTableToString() { string accountString = "TableEndpoint=http://table/;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("ToString method with custom file endpoint should return the same connection string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountJustFileToString() { string accountString = "FileEndpoint=http://file/;AccountName=test;AccountKey=abc="; Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true)); } [TestMethod] [Description("Exporting account key should be possible both as a byte array and a Base64 encoded string")] [TestCategory(ComponentCategory.Core)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudStorageAccountExportKey() { string accountKeyString = "abc2564="; string accountString = "BlobEndpoint=http://blobs/;AccountName=test;AccountKey=" + accountKeyString; CloudStorageAccount account = CloudStorageAccount.Parse(accountString); StorageCredentials accountAndKey = (StorageCredentials)account.Credentials; string key = accountAndKey.ExportBase64EncodedKey(); Assert.AreEqual(accountKeyString, key); byte[] keyBytes = accountAndKey.ExportKey(); byte[] expectedKeyBytes = Convert.FromBase64String(accountKeyString); for (int i = 0; i < expectedKeyBytes.Length; i++) { Assert.AreEqual(expectedKeyBytes[i], keyBytes[i]); } Assert.AreEqual(expectedKeyBytes.Length, keyBytes.Length); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ASC.Common.Caching; using ASC.Core.Tenants; using ASC.Core.Users; namespace ASC.Core.Caching { public class CachedUserService : IUserService, ICachedService { private const string USERS = "users"; private const string GROUPS = "groups"; private const string REFS = "refs"; private readonly IUserService service; private readonly ICache cache; private readonly ICacheNotify cacheNotify; private readonly TrustInterval trustInterval; private int getchanges; public TimeSpan CacheExpiration { get; set; } public TimeSpan DbExpiration { get; set; } public TimeSpan PhotoExpiration { get; set; } public CachedUserService(IUserService service) { if (service == null) throw new ArgumentNullException("service"); this.service = service; cache = AscCache.Memory; trustInterval = new TrustInterval(); CacheExpiration = TimeSpan.FromMinutes(20); DbExpiration = TimeSpan.FromMinutes(1); PhotoExpiration = TimeSpan.FromMinutes(10); cacheNotify = AscCache.Notify; cacheNotify.Subscribe<UserInfo>((u, a) => InvalidateCache(u)); cacheNotify.Subscribe<UserPhoto>((p, a) => cache.Remove(p.Key)); cacheNotify.Subscribe<Group>((g, a) => InvalidateCache()); cacheNotify.Subscribe<UserGroupRef>((r, a) => UpdateUserGroupRefCache(r, a == CacheNotifyAction.Remove)); } public IDictionary<Guid, UserInfo> GetUsers(int tenant, DateTime from) { var users = GetUsers(tenant); lock (users) { return (from == default(DateTime) ? users.Values : users.Values.Where(u => u.LastModified >= from)).ToDictionary(u => u.ID); } } public UserInfo GetUser(int tenant, Guid id) { if (CoreContext.Configuration.Personal) { return GetUserForPersonal(tenant, id); } var users = GetUsers(tenant); lock (users) { UserInfo u; users.TryGetValue(id, out u); return u; } } public UserInfo GetUser(int tenant, string email) { return service.GetUser(tenant, email); } public UserInfo GetUserByUserName(int tenant, string userName) { return service.GetUserByUserName(tenant, userName); } /// <summary> /// For Personal only /// </summary> /// <param name="tenant"></param> /// <param name="id"></param> /// <returns></returns> private UserInfo GetUserForPersonal(int tenant, Guid id) { if (!CoreContext.Configuration.Personal) return GetUser(tenant, id); var key = GetUserCacheKeyForPersonal(tenant, id); var user = cache.Get<UserInfo>(key); if (user == null) { user = service.GetUser(tenant, id); if (user != null) { cache.Insert(key, user, CacheExpiration); } } return user; } public UserInfo GetUserByPasswordHash(int tenant, string login, string passwordHash) { return service.GetUserByPasswordHash(tenant, login, passwordHash); } public IEnumerable<UserInfo> GetUsersAllTenants(IEnumerable<string> userIds) { return service.GetUsersAllTenants(userIds); } public UserInfo SaveUser(int tenant, UserInfo user) { user = service.SaveUser(tenant, user); cacheNotify.Publish(user, CacheNotifyAction.InsertOrUpdate); return user; } public void RemoveUser(int tenant, Guid id) { service.RemoveUser(tenant, id); cacheNotify.Publish(new UserInfo { Tenant = tenant, ID = id }, CacheNotifyAction.Remove); } public byte[] GetUserPhoto(int tenant, Guid id) { var photo = cache.Get<byte[]>(GetUserPhotoCacheKey(tenant, id)); if (photo == null) { photo = service.GetUserPhoto(tenant, id); cache.Insert(GetUserPhotoCacheKey(tenant, id), photo, PhotoExpiration); } return photo; } public void SetUserPhoto(int tenant, Guid id, byte[] photo) { service.SetUserPhoto(tenant, id, photo); cacheNotify.Publish(new UserPhoto { Key = GetUserPhotoCacheKey(tenant, id) }, CacheNotifyAction.Remove); } public DateTime GetUserPasswordStamp(int tenant, Guid id) { return service.GetUserPasswordStamp(tenant, id); } public void SetUserPasswordHash(int tenant, Guid id, string passwordHash) { service.SetUserPasswordHash(tenant, id, passwordHash); } public IDictionary<Guid, Group> GetGroups(int tenant, DateTime from) { var groups = GetGroups(tenant); lock (groups) { return (from == default(DateTime) ? groups.Values : groups.Values.Where(g => g.LastModified >= from)).ToDictionary(g => g.Id); } } public Group GetGroup(int tenant, Guid id) { var groups = GetGroups(tenant); lock (groups) { Group g; groups.TryGetValue(id, out g); return g; } } public Group SaveGroup(int tenant, Group group) { group = service.SaveGroup(tenant, group); cacheNotify.Publish(group, CacheNotifyAction.InsertOrUpdate); return group; } public void RemoveGroup(int tenant, Guid id) { service.RemoveGroup(tenant, id); cacheNotify.Publish(new Group { Id = id }, CacheNotifyAction.Remove); } public IDictionary<string, UserGroupRef> GetUserGroupRefs(int tenant, DateTime from) { if (CoreContext.Configuration.Personal) { return new Dictionary<string, UserGroupRef>(); } GetChangesFromDb(); var key = GetRefCacheKey(tenant); var refs = cache.Get<UserGroupRefStore>(key) as IDictionary<string, UserGroupRef>; if (refs == null) { refs = service.GetUserGroupRefs(tenant, default(DateTime)); cache.Insert(key, new UserGroupRefStore(refs), CacheExpiration); } lock (refs) { return from == default(DateTime) ? refs : refs.Values.Where(r => r.LastModified >= from).ToDictionary(r => r.CreateKey()); } } public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef r) { r = service.SaveUserGroupRef(tenant, r); cacheNotify.Publish(r, CacheNotifyAction.InsertOrUpdate); return r; } public void RemoveUserGroupRef(int tenant, Guid userId, Guid groupId, UserGroupRefType refType) { service.RemoveUserGroupRef(tenant, userId, groupId, refType); var r = new UserGroupRef(userId, groupId, refType) { Tenant = tenant }; cacheNotify.Publish(r, CacheNotifyAction.Remove); } public void InvalidateCache() { InvalidateCache(null); } private void InvalidateCache(UserInfo userInfo) { if (CoreContext.Configuration.Personal && userInfo != null) { var key = GetUserCacheKeyForPersonal(userInfo.Tenant, userInfo.ID); cache.Remove(key); } trustInterval.Expire(); } private IDictionary<Guid, UserInfo> GetUsers(int tenant) { GetChangesFromDb(); var key = GetUserCacheKey(tenant); var users = cache.Get<IDictionary<Guid, UserInfo>>(key); if (users == null) { users = service.GetUsers(tenant, default(DateTime)); cache.Insert(key, users, CacheExpiration); } return users; } private IDictionary<Guid, Group> GetGroups(int tenant) { GetChangesFromDb(); var key = GetGroupCacheKey(tenant); var groups = cache.Get<IDictionary<Guid, Group>>(key); if (groups == null) { groups = service.GetGroups(tenant, default(DateTime)); cache.Insert(key, groups, CacheExpiration); } return groups; } private void GetChangesFromDb() { if (!trustInterval.Expired) { return; } if (Interlocked.CompareExchange(ref getchanges, 1, 0) == 0) { try { if (!trustInterval.Expired) { return; } var starttime = trustInterval.StartTime; if (starttime != default(DateTime)) { var correction = TimeSpan.FromTicks(DbExpiration.Ticks * 3); starttime = trustInterval.StartTime.Subtract(correction); } trustInterval.Start(DbExpiration); //get and merge changes in cached tenants foreach (var tenantGroup in service.GetUsers(Tenant.DEFAULT_TENANT, starttime).Values.GroupBy(u => u.Tenant)) { var users = cache.Get<IDictionary<Guid, UserInfo>>(GetUserCacheKey(tenantGroup.Key)); if (users != null) { lock (users) { foreach (var u in tenantGroup) { users[u.ID] = u; } } } } foreach (var tenantGroup in service.GetGroups(Tenant.DEFAULT_TENANT, starttime).Values.GroupBy(g => g.Tenant)) { var groups = cache.Get<IDictionary<Guid, Group>>(GetGroupCacheKey(tenantGroup.Key)); if (groups != null) { lock (groups) { foreach (var g in tenantGroup) { groups[g.Id] = g; } } } } foreach (var tenantGroup in service.GetUserGroupRefs(Tenant.DEFAULT_TENANT, starttime).Values.GroupBy(r => r.Tenant)) { var refs = cache.Get<UserGroupRefStore>(GetRefCacheKey(tenantGroup.Key)); if (refs != null) { lock (refs) { foreach (var r in tenantGroup) { refs[r.CreateKey()] = r; } } } } } finally { Volatile.Write(ref getchanges, 0); } } } private void UpdateUserGroupRefCache(UserGroupRef r, bool remove) { var key = GetRefCacheKey(r.Tenant); var refs = cache.Get<UserGroupRefStore>(key); if (!remove && refs != null) { lock (refs) { refs[r.CreateKey()] = r; } } else { InvalidateCache(); } } private static string GetUserPhotoCacheKey(int tenant, Guid userId) { return tenant.ToString() + "userphoto" + userId.ToString(); } private static string GetGroupCacheKey(int tenant) { return tenant.ToString() + GROUPS; } private static string GetRefCacheKey(int tenant) { return tenant.ToString() + REFS; } private static string GetUserCacheKey(int tenant) { return tenant.ToString() + USERS; } private static string GetUserCacheKeyForPersonal(int tenant, Guid userId) { return tenant.ToString() + USERS + userId; } [Serializable] class UserPhoto { public string Key { get; set; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; protected bool indentCaretOnCommit; protected int indentDepth; protected bool earlyEndExpansionHappened; internal IVsExpansionSession ExpansionSession; public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc); protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken); public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } SnapshotSpan snippetSpan; if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. AddReferencesAndImports(ExpansionSession, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan endTrackingSpan) { if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { SnapshotSpan endSpanInSurfaceBuffer; if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out endSpanInSurfaceBuffer)) { return; } int endLine, endColumn; TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endColumn, iEndLine = endLine, iEndIndex = endColumn }); } } private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize)); } else { // If we don't have a document, then just guess the typical default TabSize value. indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string endLineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText); int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return true; } return false; } public virtual bool TryHandleReturn() { if (ExpansionSession != null) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); ExpansionSession.EndCurrentExpansion(fLeaveCaret: hitWithinField ? 0 : 1); ExpansionSession = null; return hitWithinField; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } int startLine = 0; int startIndex = 0; int endLine = 0; int endIndex = 0; // The expansion itself needs to be created in the data buffer, so map everything up var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer); var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer); SnapshotSpan dataBufferSpan; if (!TryGetSpanOnHigherBuffer( SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer), textViewModel.DataBuffer, out dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); var expansion = buffer as IVsExpansion; if (buffer == null || expansion == null) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK; } public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); IVsTextLines textLines; vsTextView.GetBuffer(out textLines); // Handle virtual space (e.g, see Dev10 778675) int lineLength; textLines.GetLengthOfLine(caretLine, out lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (string.IsNullOrEmpty(assemblyName)) { continue; } if (visualStudioWorkspace == null || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (vsWorkspace == null) { return false; } var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument; if (containedDocument == null) { return false; } var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal; if (containedLanguageHost != null) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default(SnapshotSpan); return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default(SnapshotSpan); return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.IO.Compression { // This class can be used to read bits from an byte array quickly. // Normally we get bits from 'bitBuffer' field and bitsInBuffer stores // the number of bits available in 'BitBuffer'. // When we used up the bits in bitBuffer, we will try to get byte from // the byte array and copy the byte to appropiate position in bitBuffer. // // The byte array is not reused. We will go from 'start' to 'end'. // When we reach the end, most read operations will return -1, // which means we are running out of input. internal class InputBuffer { private byte[] _buffer; // byte array to store input private int _start; // start poisition of the buffer private int _end; // end position of the buffer private uint _bitBuffer = 0; // store the bits here, we can quickly shift in this buffer private int _bitsInBuffer = 0; // number of bits available in bitBuffer // Total bits available in the input buffer public int AvailableBits { get { return _bitsInBuffer; } } // Total bytes available in the input buffer public int AvailableBytes { get { return (_end - _start) + (_bitsInBuffer / 8); } } // Ensure that count bits are in the bit buffer. // Returns false if input is not sufficient to make this true. // Count can be up to 16. public bool EnsureBitsAvailable(int count) { Debug.Assert(0 < count && count <= 16, "count is invalid."); // manual inlining to improve perf if (_bitsInBuffer < count) { if (NeedsInput()) { return false; } // insert a byte to bitbuffer _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; if (_bitsInBuffer < count) { if (NeedsInput()) { return false; } // insert a byte to bitbuffer _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; } } return true; } // This function will try to load 16 or more bits into bitBuffer. // It returns whatever is contained in bitBuffer after loading. // The main difference between this and GetBits is that this will // never return -1. So the caller needs to check AvailableBits to // see how many bits are available. public uint TryLoad16Bits() { if (_bitsInBuffer < 8) { if (_start < _end) { _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; } if (_start < _end) { _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; } } else if (_bitsInBuffer < 16) { if (_start < _end) { _bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer; _bitsInBuffer += 8; } } return _bitBuffer; } private uint GetBitMask(int count) { return ((uint)1 << count) - 1; } // Gets count bits from the input buffer. Returns -1 if not enough bits available. public int GetBits(int count) { Debug.Assert(0 < count && count <= 16, "count is invalid."); if (!EnsureBitsAvailable(count)) { return -1; } int result = (int)(_bitBuffer & GetBitMask(count)); _bitBuffer >>= count; _bitsInBuffer -= count; return result; } /// Copies length bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// Returns the number of bytes copied, 0 if no byte is available. public int CopyTo(byte[] output, int offset, int length) { Debug.Assert(output != null, ""); Debug.Assert(offset >= 0, ""); Debug.Assert(length >= 0, ""); Debug.Assert(offset <= output.Length - length, ""); Debug.Assert((_bitsInBuffer % 8) == 0, ""); // Copy the bytes in bitBuffer first. int bytesFromBitBuffer = 0; while (_bitsInBuffer > 0 && length > 0) { output[offset++] = (byte)_bitBuffer; _bitBuffer >>= 8; _bitsInBuffer -= 8; length--; bytesFromBitBuffer++; } if (length == 0) { return bytesFromBitBuffer; } int avail = _end - _start; if (length > avail) { length = avail; } Array.Copy(_buffer, _start, output, offset, length); _start += length; return bytesFromBitBuffer + length; } // Return true is all input bytes are used. // This means the caller can call SetInput to add more input. public bool NeedsInput() { return _start == _end; } // Set the byte array to be processed. // All the bits remained in bitBuffer will be processed before the new bytes. // We don't clone the byte array here since it is expensive. // The caller should make sure after a buffer is passed in. // It will not be changed before calling this function again. public void SetInput(byte[] buffer, int offset, int length) { Debug.Assert(buffer != null, ""); Debug.Assert(offset >= 0, ""); Debug.Assert(length >= 0, ""); Debug.Assert(offset <= buffer.Length - length, ""); Debug.Assert(_start == _end, ""); _buffer = buffer; _start = offset; _end = offset + length; } // Skip n bits in the buffer public void SkipBits(int n) { Debug.Assert(_bitsInBuffer >= n, "No enough bits in the buffer, Did you call EnsureBitsAvailable?"); _bitBuffer >>= n; _bitsInBuffer -= n; } // Skips to the next byte boundary. public void SkipToByteBoundary() { _bitBuffer >>= (_bitsInBuffer % 8); _bitsInBuffer = _bitsInBuffer - (_bitsInBuffer % 8); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // 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.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Common; using NLog.Internal; using NLog.Targets; using NLog.Targets.Wrappers; [TestFixture] public class FallbackGroupTargetTests : NLogTestBase { [Test] public void FallbackGroupTargetSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.AreEqual(10, exceptions.Count); foreach (var e in exceptions) { Assert.IsNull(e); } Assert.AreEqual(10, myTarget1.WriteCount); Assert.AreEqual(0, myTarget2.WriteCount); Assert.AreEqual(0, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } } [Test] public void FallbackGroupTargetSyncTest2() { // fail once var myTarget1 = new MyTarget() { FailCounter = 1 }; var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.AreEqual(10, exceptions.Count); foreach (var e in exceptions) { Assert.IsNull(e); } Assert.AreEqual(1, myTarget1.WriteCount); Assert.AreEqual(10, myTarget2.WriteCount); Assert.AreEqual(0, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } } [Test] public void FallbackGroupTargetSyncTest3() { // fail once var myTarget1 = new MyTarget() { FailCounter = 1 }; var myTarget2 = new MyTarget() { FailCounter = 1 }; var myTarget3 = new MyTarget(); var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.AreEqual(10, exceptions.Count); foreach (var e in exceptions) { Assert.IsNull(e); } Assert.AreEqual(1, myTarget1.WriteCount); Assert.AreEqual(1, myTarget2.WriteCount); Assert.AreEqual(10, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } } [Test] public void FallbackGroupTargetSyncTest4() { // fail once var myTarget1 = new MyTarget() { FailCounter = 1 }; var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, ReturnToFirstOnSuccess = true, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } // sequence is like this: // t1(fail), t2(success), t1(success), ... t1(success) Assert.AreEqual(10, exceptions.Count); foreach (var e in exceptions) { Assert.IsNull(e); } Assert.AreEqual(10, myTarget1.WriteCount); Assert.AreEqual(1, myTarget2.WriteCount); Assert.AreEqual(0, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } } [Test] public void FallbackGroupTargetSyncTest5() { // fail once var myTarget1 = new MyTarget() { FailCounter = 3 }; var myTarget2 = new MyTarget() { FailCounter = 3 }; var myTarget3 = new MyTarget() { FailCounter = 3 }; var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, ReturnToFirstOnSuccess = true, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.AreEqual(10, exceptions.Count); for (int i = 0; i < 10; ++i) { if (i < 3) { Assert.IsNotNull(exceptions[i]); } else { Assert.IsNull(exceptions[i]); } } Assert.AreEqual(10, myTarget1.WriteCount); Assert.AreEqual(3, myTarget2.WriteCount); Assert.AreEqual(3, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } } [Test] public void FallbackGroupTargetSyncTest6() { // fail once var myTarget1 = new MyTarget() { FailCounter = 10 }; var myTarget2 = new MyTarget() { FailCounter = 3 }; var myTarget3 = new MyTarget() { FailCounter = 3 }; var wrapper = new FallbackGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, ReturnToFirstOnSuccess = true, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.AreEqual(10, exceptions.Count); for (int i = 0; i < 10; ++i) { if (i < 3) { // for the first 3 rounds, no target is available Assert.IsNotNull(exceptions[i]); Assert.IsInstanceOfType(typeof(InvalidOperationException), exceptions[i]); Assert.AreEqual("Some failure.", exceptions[i].Message); } else { Assert.IsNull(exceptions[i], Convert.ToString(exceptions[i])); } } Assert.AreEqual(10, myTarget1.WriteCount); Assert.AreEqual(10, myTarget2.WriteCount); Assert.AreEqual(3, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.Fail(flushException.ToString()); } Assert.AreEqual(1, myTarget1.FlushCount); Assert.AreEqual(1, myTarget2.FlushCount); Assert.AreEqual(1, myTarget3.FlushCount); } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.IsTrue(this.FlushCount <= this.WriteCount); this.WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } protected override void Write(LogEventInfo logEvent) { Assert.IsTrue(this.FlushCount <= this.WriteCount); this.WriteCount++; if (this.FailCounter > 0) { this.FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace ALang { public abstract class TreeElement { public int Line { get; set; } //TODO: initialize in parser public virtual bool IsCompileTime { get { return false; } } public virtual int RequiredSpaceInLocals { get; } = 0; public abstract void GenerateInstructions(Generator generator); public virtual void PrepareBeforeGenerate() { } public virtual void PrepareStatement(Generator generator) { } public virtual void CleanUpStatement(Generator generator) { } public void PrepareBeforeGenerateRecursive() { foreach (var child in m_children) { child.PrepareBeforeGenerateRecursive(); } PrepareBeforeGenerate(); } public void PrepareStatementRecursive(Generator generator) { foreach (var child in m_children) { child.PrepareStatementRecursive(generator); } PrepareStatement(generator); } public void CleanUpStatementRecursive(Generator generator) { foreach (var child in m_children) { child.CleanUpStatementRecursive(generator); } CleanUpStatement(generator); } public IList<TreeElement> Children() { return m_children; } public IList<T> Children<T>() where T : TreeElement { return m_children.Select(c => (T) c).ToList(); } public T Child<T>(int index) where T : TreeElement { CheckChildrenCount(index); return (T) m_children[index]; } public T Parent<T>() where T : TreeElement { return (T) m_parent; } public TreeElement Parent() { return m_parent; } public T RootParent<T>() where T : TreeElement { return m_parent == null ? (T) this : m_parent.RootParent<T>(); } public TreeElement RootParent() { return m_parent == null ? this : m_parent.RootParent(); } public void SetParent(TreeElement parent, int index = -1) { if (m_parent != null) { if (index == -1) { index = m_parent.m_children.IndexOf(this); } m_parent.SetChild(m_parent.m_children.IndexOf(this), null); } m_parent = parent; if (m_parent == null) return; if (m_parent.ChildIndex(this) == -1) { m_parent.SetChild(index, this); } } public int ChildrenCount() { return m_children.Count; } public int ChildIndex(TreeElement child) { return m_children.IndexOf(child); } public int IndexInParent() { return m_parent.ChildIndex(this); } public TreeElement Child(int index) { CheckChildrenCount(index); return m_children[index]; } public void AddChild(TreeElement child) { SetChild(m_children.Count, child); } public void SetChild(int index, TreeElement child) { if (index == -1) { index = m_children.Count; } CheckChildrenCount(index); m_children[index] = child; if (child != null && child.m_parent != this) { child.SetParent(this); } } public void RemoveChildren() { m_children.Clear(); } protected List<TreeElement> m_children = new List<TreeElement>(); protected TreeElement m_parent = null; private void CheckChildrenCount(int expected) { if (expected > (m_children.Count - 1)) { for (int i = 0, iend = expected - (m_children.Count - 1); i < iend; ++i) { m_children.Add(null); } } } } public class PrintCurrentValElement : TreeElement //TODO: remove it { public override void GenerateInstructions(Generator generator) { VarGet.IsGet = true; VarGet.GenerateInstructions(generator); generator.AddOp(GenCodes.Print, 1, ByteConverter.New().CastByte((sbyte) LanguageSymbols.DefTypesName.Index.Int32).Bytes); } public GetVariableElement VarGet { get { return m_varGet; } set { m_varGet = value; AddChild(m_varGet); } } private GetVariableElement m_varGet; } }
--- /dev/null 2016-01-28 07:47:49.000000000 -0500 +++ src/System.Threading/src/SR.cs 2016-01-28 07:49:38.498826000 -0500 @@ -0,0 +1,382 @@ +using System; +using System.Resources; + +namespace FxResources.System.Threading +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const string s_resourcesName = "FxResources.System.Threading.SR"; + + internal static string Argument_SemaphoreInitialMaximum + { + get + { + return SR.GetResourceString("Argument_SemaphoreInitialMaximum", null); + } + } + + internal static string Argument_WaitHandleNameTooLong + { + get + { + return SR.GetResourceString("Argument_WaitHandleNameTooLong", null); + } + } + + internal static string ArgumentOutOfRange_NeedNonNegNumRequired + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNumRequired", null); + } + } + + internal static string ArgumentOutOfRange_NeedPosNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedPosNum", null); + } + } + + internal static string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_AddParticipants_NonPositive_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_AddParticipants_Overflow_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_AddParticipants_Overflow_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_ctor_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_ctor_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_Dispose + { + get + { + return SR.GetResourceString("Barrier_Dispose", null); + } + } + + internal static string Barrier_InvalidOperation_CalledFromPHA + { + get + { + return SR.GetResourceString("Barrier_InvalidOperation_CalledFromPHA", null); + } + } + + internal static string Barrier_RemoveParticipants_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_RemoveParticipants_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_RemoveParticipants_InvalidOperation + { + get + { + return SR.GetResourceString("Barrier_RemoveParticipants_InvalidOperation", null); + } + } + + internal static string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_SignalAndWait_ArgumentOutOfRange + { + get + { + return SR.GetResourceString("Barrier_SignalAndWait_ArgumentOutOfRange", null); + } + } + + internal static string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded + { + get + { + return SR.GetResourceString("Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded", null); + } + } + + internal static string Barrier_SignalAndWait_InvalidOperation_ZeroTotal + { + get + { + return SR.GetResourceString("Barrier_SignalAndWait_InvalidOperation_ZeroTotal", null); + } + } + + internal static string BarrierPostPhaseException + { + get + { + return SR.GetResourceString("BarrierPostPhaseException", null); + } + } + + internal static string Common_OperationCanceled + { + get + { + return SR.GetResourceString("Common_OperationCanceled", null); + } + } + + internal static string CountdownEvent_Decrement_BelowZero + { + get + { + return SR.GetResourceString("CountdownEvent_Decrement_BelowZero", null); + } + } + + internal static string CountdownEvent_Increment_AlreadyMax + { + get + { + return SR.GetResourceString("CountdownEvent_Increment_AlreadyMax", null); + } + } + + internal static string CountdownEvent_Increment_AlreadyZero + { + get + { + return SR.GetResourceString("CountdownEvent_Increment_AlreadyZero", null); + } + } + + internal static string InvalidNullEmptyArgument + { + get + { + return SR.GetResourceString("InvalidNullEmptyArgument", null); + } + } + + internal static string LockRecursionException_ReadAfterWriteNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_ReadAfterWriteNotAllowed", null); + } + } + + internal static string LockRecursionException_RecursiveReadNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_RecursiveReadNotAllowed", null); + } + } + + internal static string LockRecursionException_RecursiveUpgradeNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_RecursiveUpgradeNotAllowed", null); + } + } + + internal static string LockRecursionException_RecursiveWriteNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_RecursiveWriteNotAllowed", null); + } + } + + internal static string LockRecursionException_UpgradeAfterReadNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_UpgradeAfterReadNotAllowed", null); + } + } + + internal static string LockRecursionException_UpgradeAfterWriteNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_UpgradeAfterWriteNotAllowed", null); + } + } + + internal static string LockRecursionException_WriteAfterReadNotAllowed + { + get + { + return SR.GetResourceString("LockRecursionException_WriteAfterReadNotAllowed", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Threading.SR); + } + } + + internal static string SynchronizationLockException_IncorrectDispose + { + get + { + return SR.GetResourceString("SynchronizationLockException_IncorrectDispose", null); + } + } + + internal static string SynchronizationLockException_MisMatchedRead + { + get + { + return SR.GetResourceString("SynchronizationLockException_MisMatchedRead", null); + } + } + + internal static string SynchronizationLockException_MisMatchedUpgrade + { + get + { + return SR.GetResourceString("SynchronizationLockException_MisMatchedUpgrade", null); + } + } + + internal static string SynchronizationLockException_MisMatchedWrite + { + get + { + return SR.GetResourceString("SynchronizationLockException_MisMatchedWrite", null); + } + } + + internal static string UnknownError_Num + { + get + { + return SR.GetResourceString("UnknownError_Num", null); + } + } + + internal static string WaitHandle_NamesNotSupported + { + get + { + return SR.GetResourceString("WaitHandle_NamesNotSupported", null); + } + } + + internal static string WaitHandleCannotBeOpenedException_InvalidHandle + { + get + { + return SR.GetResourceString("WaitHandleCannotBeOpenedException_InvalidHandle", null); + } + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, args); + } + return string.Concat(resourceFormat, string.Join(", ", args)); + } + + internal static string Format(string resourceFormat, object p1) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1); + } + return string.Join(", ", new object[] { resourceFormat, p1 }); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2 }); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2, p3); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2, p3 }); + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str, 4)) + { + return defaultString; + } + return str; + } + + private static bool UsingResourceKeys() + { + return false; + } + } +}
// <copyright file="EdgeOptions.cs" company="Microsoft"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Chromium; namespace OpenQA.Selenium.Edge { /// <summary> /// Class to manage options specific to <see cref="EdgeDriver"/> /// </summary> /// <example> /// <code> /// EdgeOptions options = new EdgeOptions(); /// </code> /// <para></para> /// <para>For use with EdgeDriver:</para> /// <para></para> /// <code> /// EdgeDriver driver = new EdgeDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class EdgeOptions : ChromiumOptions { private const string DefaultBrowserNameValue = "MicrosoftEdge"; private const string WebViewBrowserNameValue = "WebView2"; // Engine switching private const string UseChromiumCapability = "ms:edgeChromium"; private bool useChromium = false; private const string EdgeOptionsCapabilityName = "edgeOptions"; // Edge Legacy options private const string UseInPrivateBrowsingCapability = "ms:inPrivate"; private const string ExtensionPathsCapability = "ms:extensionPaths"; private const string StartPageCapability = "ms:startPage"; private bool useInPrivateBrowsing; private string startPage; private List<string> extensionPaths = new List<string>(); // Additional Edge-specific Chromium options private bool useWebView; /// <summary> /// Initializes a new instance of the <see cref="EdgeOptions"/> class. /// </summary> public EdgeOptions() { this.AddKnownCapabilityName(UseChromiumCapability, "UseChromium property"); this.AddKnownCapabilityName(UseInPrivateBrowsingCapability, "UseInPrivateBrowsing property"); this.AddKnownCapabilityName(StartPageCapability, "StartPage property"); this.AddKnownCapabilityName(ExtensionPathsCapability, "AddExtensionPaths method"); } /// <summary> /// Gets or sets a value indicating whether to launch Edge Chromium. Defaults to using Edge Legacy. /// </summary> public bool UseChromium { get { return this.useChromium; } set { this.useChromium = value; } } /// <summary> /// Gets the default value of the browserName capability. /// </summary> protected override string BrowserNameValue { get { return UseWebView ? WebViewBrowserNameValue : DefaultBrowserNameValue; } } /// <summary> /// Gets the vendor prefix to apply to Chromium-specific capability names. /// </summary> protected override string VendorPrefix { get { return "ms"; } } /// <summary> /// Gets the name of the capability used to store Chromium options in /// an <see cref="ICapabilities"/> object. /// </summary> public override string CapabilityName { get { return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.VendorPrefix, EdgeOptionsCapabilityName); } } /// <summary> /// Gets or sets whether to create a WebView session used for launching an Edge (Chromium) WebView-based app on desktop. /// </summary> public bool UseWebView { get { return this.useWebView; } set { this.useWebView = value; } } /// <summary> /// Gets or sets a value indicating whether the browser should be launched using /// InPrivate browsing. /// </summary> public bool UseInPrivateBrowsing { get { return this.useInPrivateBrowsing; } set { this.useInPrivateBrowsing = value; } } /// <summary> /// Gets or sets the URL of the page with which the browser will be navigated to on launch. /// </summary> public string StartPage { get { return this.startPage; } set { this.startPage = value; } } /// <summary> /// Adds a path to an extension that is to be used with the Edge Legacy driver. /// </summary> /// <param name="extensionPath">The full path and file name of the extension.</param> public void AddExtensionPath(string extensionPath) { if (string.IsNullOrEmpty(extensionPath)) { throw new ArgumentException("extensionPath must not be null or empty", "extensionPath"); } this.AddExtensionPaths(extensionPath); } /// <summary> /// Adds a list of paths to an extensions that are to be used with the Edge Legacy driver. /// </summary> /// <param name="extensionPathsToAdd">An array of full paths with file names of extensions to add.</param> public void AddExtensionPaths(params string[] extensionPathsToAdd) { this.AddExtensionPaths(new List<string>(extensionPathsToAdd)); } /// <summary> /// Adds a list of paths to an extensions that are to be used with the Edge Legacy driver. /// </summary> /// <param name="extensionPathsToAdd">An <see cref="IEnumerable{T}"/> of full paths with file names of extensions to add.</param> public void AddExtensionPaths(IEnumerable<string> extensionPathsToAdd) { if (extensionPathsToAdd == null) { throw new ArgumentNullException("extensionPathsToAdd", "extensionPathsToAdd must not be null"); } this.extensionPaths.AddRange(extensionPathsToAdd); } /// <summary> /// Returns DesiredCapabilities for Edge with these options included as /// capabilities. This copies the options. Further changes will not be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Edge with these options.</returns> public override ICapabilities ToCapabilities() { return this.useChromium ? ToChromiumCapabilities() : ToLegacyCapabilities(); } /// <summary> /// Adds vendor-specific capabilities for Chromium-based browsers. /// </summary> /// <param name="capabilities">The capabilities to add.</param> protected override void AddVendorSpecificChromiumCapabilities(IWritableCapabilities capabilities) { capabilities.SetCapability(EdgeOptions.UseChromiumCapability, this.useChromium); } private ICapabilities ToChromiumCapabilities() { return base.ToCapabilities(); } private ICapabilities ToLegacyCapabilities() { IWritableCapabilities capabilities = this.GenerateDesiredCapabilities(true); capabilities.SetCapability(EdgeOptions.UseChromiumCapability, this.useChromium); if (this.useInPrivateBrowsing) { capabilities.SetCapability(UseInPrivateBrowsingCapability, true); } if (!string.IsNullOrEmpty(this.startPage)) { capabilities.SetCapability(StartPageCapability, this.startPage); } if (this.extensionPaths.Count > 0) { capabilities.SetCapability(ExtensionPathsCapability, this.extensionPaths); } return capabilities.AsReadOnly(); } } }
// 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. //----------------------------------------------------------------------------- // // Description: // ContentType class parses and validates the content-type string. // It provides functionality to compare the type/subtype values. // // Details: // Grammar which this class follows - // // Content-type grammar MUST conform to media-type grammar as per // RFC 2616 (ABNF notation): // // media-type = type "/" subtype *( ";" parameter ) // type = token // subtype = token // parameter = attribute "=" value // attribute = token // value = token | quoted-string // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) // qdtext = <any TEXT except <">> // quoted-pair = "\" CHAR // token = 1*<any CHAR except CTLs or separators> // separators = "(" | ")" | "<" | ">" | "@" // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT // TEXT = <any OCTET except CTLs, but including LWS> // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character(octets 0 - 31)and DEL(127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // LWS = [CRLF] 1*( SP | HT ) // CRLF = CR LF // Linear white space (LWS) MUST NOT be used between the type and subtype, nor // between an attribute and its value. Leading and trailing LWS are prohibited. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; // For Dictionary<string, string> using System.Text; // For StringBuilder using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// Content Type class /// </summary> internal sealed class ContentType { #region Internal Constructors /// <summary> /// This constructor creates a ContentType object that represents /// the content-type string. At construction time we validate the /// string as per the grammar specified in RFC 2616. /// Note: We allow empty strings as valid input. Empty string should /// we used more as an indication of an absent/unknown ContentType. /// </summary> /// <param name="contentType">content-type</param> /// <exception cref="ArgumentNullException">If the contentType parameter is null</exception> /// <exception cref="ArgumentException">If the contentType string has leading or /// trailing Linear White Spaces(LWS) characters</exception> /// <exception cref="ArgumentException">If the contentType string invalid CR-LF characters</exception> internal ContentType(string contentType) { if (contentType == null) throw new ArgumentNullException(nameof(contentType)); if (contentType.Length == 0) { _contentType = string.Empty; } else { if (IsLinearWhiteSpaceChar(contentType[0]) || IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])) throw new ArgumentException(SR.ContentTypeCannotHaveLeadingTrailingLWS); //Carriage return can be expressed as '\r\n' or '\n\r' //We need to make sure that a \r is accompanied by \n ValidateCarriageReturns(contentType); //Begin Parsing int semiColonIndex = contentType.IndexOf(SemicolonSeparator); if (semiColonIndex == -1) { // Parse content type similar to - type/subtype ParseTypeAndSubType(contentType); } else { // Parse content type similar to - type/subtype ; param1=value1 ; param2=value2 ; param3="value3" ParseTypeAndSubType(contentType.Substring(0, semiColonIndex)); ParseParameterAndValue(contentType.Substring(semiColonIndex)); } } // keep this untouched for return from OriginalString property _originalString = contentType; //This variable is used to print out the correct content type string representation //using the ToString method. This is mainly important while debugging and seeing the //value of the content type object in the debugger. _isInitialized = true; } #endregion Internal Constructors #region Internal Properties /// <summary> /// TypeComponent of the Content Type /// If the content type is "text/xml". This property will return "text" /// </summary> internal string TypeComponent { get { return _type; } } /// <summary> /// SubType component /// If the content type is "text/xml". This property will return "xml" /// </summary> internal string SubTypeComponent { get { return _subType; } } /// <summary> /// Enumerator which iterates over the Parameter and Value pairs which are stored /// in a dictionary. We hand out just the enumerator in order to make this property /// ReadOnly /// Consider following Content type - /// type/subtype ; param1=value1 ; param2=value2 ; param3="value3" /// This will return an enumerator over a dictionary of the parameter/value pairs. /// </summary> internal Dictionary<string, string>.Enumerator ParameterValuePairs { get { EnsureParameterDictionary(); return _parameterDictionary.GetEnumerator(); } } #endregion Internal Properties #region Internal Methods /// <summary> /// This method does a strong comparison of the content types, as parameters are not allowed. /// We only compare the type and subType values in an ASCII case-insensitive manner. /// Parameters are not allowed to be present on any of the content type operands. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType) { return AreTypeAndSubTypeEqual(contentType, false); } /// <summary> /// This method does a weak comparison of the content types. We only compare the /// type and subType values in an ASCII case-insensitive manner. /// Parameter and value pairs are not used for the comparison. /// If you wish to compare the parameters too, then you must get the ParameterValuePairs from /// both the ContentType objects and compare each parameter entry. /// The allowParameterValuePairs parameter is used to indicate whether the /// comparison is tolerant to parameters being present or no. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <param name="allowParameterValuePairs">If true, allows the presence of parameter value pairs. /// If false, parameter/value pairs cannot be present in the content type string. /// In either case, the parameter value pair is not used for the comparison.</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType, bool allowParameterValuePairs) { bool result = false; if (contentType != null) { if (!allowParameterValuePairs) { //Return false if this content type object has parameters if (_parameterDictionary != null) { if (_parameterDictionary.Count > 0) return false; } //Return false if the content type object passed in has parameters Dictionary<string, string>.Enumerator contentTypeEnumerator; contentTypeEnumerator = contentType.ParameterValuePairs; contentTypeEnumerator.MoveNext(); if (contentTypeEnumerator.Current.Key != null) return false; } // Perform a case-insensitive comparison on the type/subtype strings. This is a // safe comparison because the _type and _subType strings have been restricted to // ASCII characters, digits, and a small set of symbols. This is not a safe comparison // for the broader set of strings that have not been restricted in the same way. result = (string.Equals(_type, contentType.TypeComponent, StringComparison.OrdinalIgnoreCase) && string.Equals(_subType, contentType.SubTypeComponent, StringComparison.OrdinalIgnoreCase)); } return result; } /// <summary> /// ToString - outputs a normalized form of the content type string /// </summary> /// <returns></returns> public override string ToString() { if (_contentType == null) { //This is needed so that while debugging we get the correct //string if (!_isInitialized) return string.Empty; Debug.Assert(string.CompareOrdinal(_type, string.Empty) != 0 || string.CompareOrdinal(_subType, string.Empty) != 0); StringBuilder stringBuilder = new StringBuilder(_type); stringBuilder.Append(PackUriHelper.ForwardSlashChar); stringBuilder.Append(_subType); if (_parameterDictionary != null && _parameterDictionary.Count > 0) { foreach (string parameterKey in _parameterDictionary.Keys) { stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(SemicolonSeparator); stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(parameterKey); stringBuilder.Append(EqualSeparator); stringBuilder.Append(_parameterDictionary[parameterKey]); } } _contentType = stringBuilder.ToString(); } return _contentType; } #endregion Internal Methods #region Private Methods /// <summary> /// This method validates if the content type string has /// valid CR-LF characters. Specifically we test if '\r' is /// accompanied by a '\n' in the string, else its an error. /// </summary> /// <param name="contentType"></param> private static void ValidateCarriageReturns(string contentType) { Debug.Assert(!IsLinearWhiteSpaceChar(contentType[0]) && !IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])); //Prior to calling this method we have already checked that first and last //character of the content type are not Linear White Spaces. So its safe to //assume that the index will be greater than 0 and less that length-2. int index = contentType.IndexOf(s_linearWhiteSpaceChars[2]); while (index != -1) { if (contentType[index - 1] == s_linearWhiteSpaceChars[1] || contentType[index + 1] == s_linearWhiteSpaceChars[1]) { index = contentType.IndexOf(s_linearWhiteSpaceChars[2], ++index); } else throw new ArgumentException(SR.InvalidLinearWhiteSpaceCharacter); } } /// <summary> /// Parses the type and subType tokens from the string. /// Also verifies if the Tokens are valid as per the grammar. /// </summary> /// <param name="typeAndSubType">substring that has the type and subType of the content type</param> /// <exception cref="ArgumentException">If the typeAndSubType parameter does not have the "/" character</exception> private void ParseTypeAndSubType(string typeAndSubType) { //okay to trim at this point the end of the string as Linear White Spaces(LWS) chars are allowed here. typeAndSubType = typeAndSubType.TrimEnd(s_linearWhiteSpaceChars); string[] splitBasedOnForwardSlash = typeAndSubType.Split(PackUriHelper.s_forwardSlashCharArray); if (splitBasedOnForwardSlash.Length != 2) throw new ArgumentException(SR.InvalidTypeSubType); _type = ValidateToken(splitBasedOnForwardSlash[0]); _subType = ValidateToken(splitBasedOnForwardSlash[1]); } /// <summary> /// Parse the individual parameter=value strings /// </summary> /// <param name="parameterAndValue">This string has the parameter and value pair of the form /// parameter=value</param> /// <exception cref="ArgumentException">If the string does not have the required "="</exception> private void ParseParameterAndValue(string parameterAndValue) { while (parameterAndValue != string.Empty) { //At this point the first character MUST be a semi-colon //First time through this test is serving more as an assert. if (parameterAndValue[0] != SemicolonSeparator) throw new ArgumentException(SR.ExpectingSemicolon); //At this point if we have just one semicolon, then its an error. //Also, there can be no trailing LWS characters, as we already checked for that //in the constructor. if (parameterAndValue.Length == 1) throw new ArgumentException(SR.ExpectingParameterValuePairs); //Removing the leading ; from the string parameterAndValue = parameterAndValue.Substring(1); //okay to trim start as there can be spaces before the beginning //of the parameter name. parameterAndValue = parameterAndValue.TrimStart(s_linearWhiteSpaceChars); int equalSignIndex = parameterAndValue.IndexOf(EqualSeparator); if (equalSignIndex <= 0 || equalSignIndex == (parameterAndValue.Length - 1)) throw new ArgumentException(SR.InvalidParameterValuePair); int parameterStartIndex = equalSignIndex + 1; //Get length of the parameter value int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex); EnsureParameterDictionary(); _parameterDictionary.Add( ValidateToken(parameterAndValue.Substring(0, equalSignIndex)), ValidateQuotedStringOrToken(parameterAndValue.Substring(parameterStartIndex, parameterValueLength))); parameterAndValue = parameterAndValue.Substring(parameterStartIndex + parameterValueLength).TrimStart(s_linearWhiteSpaceChars); } } /// <summary> /// This method returns the length of the first parameter value in the input string. /// </summary> /// <param name="s"></param> /// <param name="startIndex">Starting index for parsing</param> /// <returns></returns> private static int GetLengthOfParameterValue(string s, int startIndex) { Debug.Assert(s != null); int length = 0; //if the parameter value does not start with a '"' then, //we expect a valid token. So we look for Linear White Spaces or //a ';' as the terminator for the token value. if (s[startIndex] != '"') { int semicolonIndex = s.IndexOf(SemicolonSeparator, startIndex); if (semicolonIndex != -1) { int lwsIndex = s.IndexOfAny(s_linearWhiteSpaceChars, startIndex); if (lwsIndex != -1 && lwsIndex < semicolonIndex) length = lwsIndex; else length = semicolonIndex; } else length = semicolonIndex; //If there is no linear whitespace found we treat the entire remaining string as //parameter value. if (length == -1) length = s.Length; } else { //if the parameter value starts with a '"' then, we need to look for the //pairing '"' that is not preceded by a "\" ["\" is used to escape the '"'] bool found = false; length = startIndex; while (!found) { length = s.IndexOf('"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); if (s[length - 1] != '\\') { found = true; length++; } } } return length - startIndex; } /// <summary> /// Validating the given token /// The following checks are being made - /// 1. If all the characters in the token are either ASCII letter or digit. /// 2. If all the characters in the token are either from the remaining allowed cha----ter set. /// </summary> /// <param name="token">string token</param> /// <returns>validated string token</returns> /// <exception cref="ArgumentException">If the token is Empty</exception> private static string ValidateToken(string token) { if (string.IsNullOrEmpty(token)) throw new ArgumentException(SR.InvalidToken_ContentType); for (int i = 0; i < token.Length; i++) { if (!IsAsciiLetterOrDigit(token[i]) && !IsAllowedCharacter(token[i])) { throw new ArgumentException(SR.InvalidToken_ContentType); } } return token; } /// <summary> /// Validating if the value of a parameter is either a valid token or a /// valid quoted string /// </summary> /// <param name="parameterValue">parameter value string</param> /// <returns>validate parameter value string</returns> /// <exception cref="ArgumentException">If the parameter value is empty</exception> private static string ValidateQuotedStringOrToken(string parameterValue) { if (string.IsNullOrEmpty(parameterValue)) throw new ArgumentException(SR.InvalidParameterValue); if (parameterValue.Length >= 2 && parameterValue.StartsWith(Quote, StringComparison.Ordinal) && parameterValue.EndsWith(Quote, StringComparison.Ordinal)) ValidateQuotedText(parameterValue.Substring(1, parameterValue.Length - 2)); else ValidateToken(parameterValue); return parameterValue; } /// <summary> /// This method validates if the text in the quoted string /// </summary> /// <param name="quotedText"></param> private static void ValidateQuotedText(string quotedText) { //empty is okay for (int i = 0; i < quotedText.Length; i++) { if (IsLinearWhiteSpaceChar(quotedText[i])) continue; if (quotedText[i] <= ' ' || quotedText[i] >= 0xFF) throw new ArgumentException(SR.InvalidParameterValue); else if (quotedText[i] == '"' && (i == 0 || quotedText[i - 1] != '\\')) throw new ArgumentException(SR.InvalidParameterValue); } } /// <summary> /// Returns true if the input character is an allowed character /// Returns false if the input cha----ter is not an allowed character /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAllowedCharacter(char character) { return Array.IndexOf(s_allowedCharacters, character) >= 0; } /// <summary> /// Returns true if the input character is an ASCII digit or letter /// Returns false if the input character is not an ASCII digit or letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetterOrDigit(char character) { return (IsAsciiLetter(character) || (character >= '0' && character <= '9')); } /// <summary> /// Returns true if the input character is an ASCII letter /// Returns false if the input character is not an ASCII letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } /// <summary> /// Returns true if the input character is one of the Linear White Space characters - /// ' ', '\t', '\n', '\r' /// Returns false if the input character is none of the above /// </summary> /// <param name="ch">input character</param> /// <returns></returns> private static bool IsLinearWhiteSpaceChar(char ch) { if (ch > ' ') { return false; } int whiteSpaceIndex = Array.IndexOf(s_linearWhiteSpaceChars, ch); return whiteSpaceIndex != -1; } /// <summary> /// Lazy initialization for the ParameterDictionary /// </summary> private void EnsureParameterDictionary() { if (_parameterDictionary == null) { _parameterDictionary = new Dictionary<string, string>(); //initial size 0 } } #endregion Private Methods #region Private Members private string _contentType = null; private string _type = string.Empty; private string _subType = string.Empty; private readonly string _originalString; private Dictionary<string, string> _parameterDictionary = null; private readonly bool _isInitialized = false; private const string Quote = "\""; private const char SemicolonSeparator = ';'; private const char EqualSeparator = '='; //This array is sorted by the ascii value of these characters. private static readonly char[] s_allowedCharacters = { '!' /*33*/, '#' /*35*/, '$' /*36*/, '%' /*37*/, '&' /*38*/, '\'' /*39*/, '*' /*42*/, '+' /*43*/, '-' /*45*/, '.' /*46*/, '^' /*94*/, '_' /*95*/, '`' /*96*/, '|' /*124*/, '~' /*126*/, }; //Linear White Space characters private static readonly char[] s_linearWhiteSpaceChars = { ' ', // space - \x20 '\n', // new line - \x0A '\r', // carriage return - \x0D '\t' // horizontal tab - \x09 }; #endregion Private Members } }
//----------------------------------------------------------------------- // <copyright file="SystemDrive.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Computer { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>CheckDriveSpace</i> (<b>Required: </b>Drive, MinSpace <b>Optional: </b>Unit)</para> /// <para><i>GetDrives</i> (<b>Optional: </b>SkipDrives, Unit <b>Output: </b>Drives)</para> /// <para><b>Remote Execution Support:</b> Yes</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <ItemGroup> /// <DrivesToSkip Include="A:\"/> /// </ItemGroup> /// <Target Name="Default"> /// <!--- Check drive space --> /// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MachineName="AMachine" UserName="Administrator" UserPassword="APassword" MinSpace="46500" Unit="Mb" ContinueOnError="true"/> /// <!--- Check drive space on a remote machine --> /// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="GetDrives" SkipDrives="@(DrivesToSkip)" MachineName="AMachine" UserName="Administrator" UserPassword="APassword"> /// <Output TaskParameter="Drives" ItemName="SystemDrivesRemote"/> /// </MSBuild.ExtensionPack.Computer.SystemDrive> /// <Message Text="Remote Drive: %(SystemDrivesRemote.Identity), DriveType: %(SystemDrivesRemote.DriveType), Name: %(SystemDrivesRemote.Name), VolumeLabel: %(SystemDrivesRemote.VolumeLabel), DriveFormat: %(SystemDrivesRemote.DriveFormat), TotalSize: %(SystemDrivesRemote.TotalSize), TotalFreeSpace=%(SystemDrivesRemote.TotalFreeSpace), AvailableFreeSpace=%(SystemDrivesRemote.AvailableFreeSpace)IsReady=%(SystemDrivesRemote.IsReady), RootDirectory=%(SystemDrivesRemote.RootDirectory)"/> /// <!--- Check drive space using different units --> /// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MinSpace="46500" Unit="Mb" ContinueOnError="true"/> /// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MinSpace="1" Unit="Gb"/> /// <!-- Get the drives on a machine --> /// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="GetDrives" SkipDrives="@(DrivesToSkip)"> /// <Output TaskParameter="Drives" ItemName="SystemDrives"/> /// </MSBuild.ExtensionPack.Computer.SystemDrive> /// <Message Text="Drive: %(SystemDrives.Identity), DriveType: %(SystemDrives.DriveType), Name: %(SystemDrives.Name), VolumeLabel: %(SystemDrives.VolumeLabel), DriveFormat: %(SystemDrives.DriveFormat), TotalSize: %(SystemDrives.TotalSize), TotalFreeSpace=%(SystemDrives.TotalFreeSpace), AvailableFreeSpace=%(SystemDrives.AvailableFreeSpace)IsReady=%(SystemDrives.IsReady), RootDirectory=%(SystemDrives.RootDirectory)"/> /// </Target> /// </Project> /// ]]></code> /// </example> [HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/b223bca4-81ab-02df-11dc-2cea84238b91.htm")] public class SystemDrive : BaseTask { private const string CheckDriveSpaceTaskAction = "CheckDriveSpace"; private const string GetDrivesTaskAction = "GetDrives"; private List<ITaskItem> drives; private List<ITaskItem> skipDrives; [DropdownValue(CheckDriveSpaceTaskAction)] [DropdownValue(GetDrivesTaskAction)] public override string TaskAction { get { return base.TaskAction; } set { base.TaskAction = value; } } /// <summary> /// Sets the unit. Supports Kb, Mb(default), Gb, Tb /// </summary> [TaskAction(CheckDriveSpaceTaskAction, false)] [TaskAction(GetDrivesTaskAction, false)] public string Unit { get; set; } /// <summary> /// Sets the drive. /// </summary> [TaskAction(CheckDriveSpaceTaskAction, true)] public string Drive { get; set; } /// <summary> /// Sets the min space. /// </summary> [TaskAction(CheckDriveSpaceTaskAction, true)] public long MinSpace { get; set; } /// <summary> /// Sets the drives. ITaskItem /// <para/> /// Identity: Name /// <para/> /// Metadata: Name, VolumeLabel, AvailableFreeSpace, DriveFormat, TotalSize, TotalFreeSpace, IsReady (LocalMachine only), RootDirectory (LocalMachine only) /// </summary> [Output] [TaskAction(GetDrivesTaskAction, false)] public ITaskItem[] Drives { get { return this.drives.ToArray(); } set { this.drives = new List<ITaskItem>(value); } } /// <summary> /// Sets the drives to skip. ITaskItem /// </summary> [TaskAction(GetDrivesTaskAction, true)] public ITaskItem[] SkipDrives { get { return this.skipDrives.ToArray(); } set { this.skipDrives = new List<ITaskItem>(value); } } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { switch (this.TaskAction) { case "GetDrives": this.GetDrives(); break; case "CheckDriveSpace": this.CheckDriveSpace(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } /// <summary> /// Checks the drive space. /// </summary> private void CheckDriveSpace() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking Drive Space: {0} (min {1}{2}) on: {3}", this.Drive, this.MinSpace, this.Unit, this.MachineName)); long unitSize = this.ReadUnitSize(); if (this.MachineName == Environment.MachineName) { foreach (string drive1 in Environment.GetLogicalDrives()) { if (string.Compare(this.Drive, drive1, StringComparison.OrdinalIgnoreCase) == 0) { DriveInfo driveInfo = new DriveInfo(drive1); if (driveInfo.IsReady) { long freespace = driveInfo.AvailableFreeSpace; if ((freespace / unitSize) < this.MinSpace) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Insufficient free space. Drive {0} has {1}{2}", this.Drive, driveInfo.AvailableFreeSpace / unitSize, this.Unit)); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Free drive space on {0} is {1}{2}", this.Drive, driveInfo.AvailableFreeSpace / unitSize, this.Unit)); } } else { this.Log.LogWarning("Drive not ready to be read: {0}", drive1); } } } } else { this.GetManagementScope(@"\root\cimv2"); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query)) { ManagementObjectCollection moc = searcher.Get(); foreach (ManagementObject mo in moc) { if (mo == null) { Log.LogError("WMI Failed to get drives from: {0}", this.MachineName); return; } // only check fixed drives. if (mo["DriveType"] != null && mo["DriveType"].ToString() == "3") { if (mo["DriveLetter"] == null) { this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "WMI Failed to query the DriveLetter from: {0}", this.MachineName)); break; } string drive = mo["DriveLetter"].ToString(); double freeSpace = Convert.ToDouble(mo["FreeSpace"], CultureInfo.CurrentCulture) / unitSize; if (freeSpace < this.MinSpace) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Insufficient free space. Drive {0} has {1}{2}", drive, freeSpace, this.Unit)); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Free drive space on {0} is {1}{2}", drive, freeSpace, this.Unit)); } } } } } } private long ReadUnitSize() { if (string.IsNullOrEmpty(this.Unit)) { this.Unit = "Mb"; } long unitSize; switch (this.Unit.ToUpperInvariant()) { case "TB": unitSize = 1099511627776; break; case "GB": unitSize = 1073741824; break; case "KB": unitSize = 1024; break; default: unitSize = 1048576; break; } return unitSize; } /// <summary> /// Gets the drives. /// </summary> private void GetDrives() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Drives from: {0}", this.MachineName)); long unitSize = this.ReadUnitSize(); this.drives = new List<ITaskItem>(); if (this.MachineName == Environment.MachineName) { foreach (string drive1 in Environment.GetLogicalDrives()) { bool skip = false; if (this.skipDrives != null) { skip = this.SkipDrives.Any(driveToSkip => driveToSkip.ItemSpec == drive1); } if (skip == false) { DriveInfo driveInfo = new DriveInfo(drive1); if (driveInfo.IsReady) { ITaskItem item = new TaskItem(drive1); item.SetMetadata("DriveType", driveInfo.DriveType.ToString()); if (driveInfo.DriveType == DriveType.Fixed || driveInfo.DriveType == DriveType.Removable) { item.SetMetadata("Name", driveInfo.Name); item.SetMetadata("VolumeLabel", driveInfo.VolumeLabel); item.SetMetadata("AvailableFreeSpace", (driveInfo.AvailableFreeSpace / unitSize).ToString(CultureInfo.CurrentCulture)); item.SetMetadata("DriveFormat", driveInfo.DriveFormat); item.SetMetadata("TotalSize", (driveInfo.TotalSize / unitSize).ToString(CultureInfo.CurrentCulture)); item.SetMetadata("TotalFreeSpace", (driveInfo.TotalFreeSpace / unitSize).ToString(CultureInfo.CurrentCulture)); item.SetMetadata("IsReady", driveInfo.IsReady.ToString()); item.SetMetadata("RootDirectory", driveInfo.RootDirectory.ToString()); } this.drives.Add(item); } else { this.Log.LogWarning("Drive not ready to be read: {0}", drive1); } } } } else { this.GetManagementScope(@"\root\cimv2"); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query)) { ManagementObjectCollection moc = searcher.Get(); foreach (ManagementObject mo in moc) { if (mo == null) { Log.LogError("WMI Failed to get drives from: {0}", this.MachineName); return; } // only check fixed drives. if (mo["DriveType"] != null && mo["DriveType"].ToString() == "3") { bool skip = false; string drive1 = mo["DriveLetter"].ToString(); if (this.skipDrives != null) { skip = this.SkipDrives.Any(driveToSkip => driveToSkip.ItemSpec == drive1); } if (skip == false) { ITaskItem item = new TaskItem(drive1); item.SetMetadata("DriveType", mo["DriveType"].ToString()); if (mo["DriveType"].ToString() == "3" || mo["DriveType"].ToString() == "2") { item.SetMetadata("Name", mo["Name"].ToString()); item.SetMetadata("VolumeLabel", mo["Label"].ToString()); item.SetMetadata("AvailableFreeSpace", mo["FreeSpace"].ToString()); item.SetMetadata("DriveFormat", mo["FileSystem"].ToString()); item.SetMetadata("TotalSize", mo["Capacity"].ToString()); item.SetMetadata("TotalFreeSpace", mo["FreeSpace"].ToString()); } this.drives.Add(item); } } } } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Methods.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Methods { /// <summary> /// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpGet /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)] public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "GET"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpGet() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpGet(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpOptions /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)] public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "OPTIONS"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpOptions() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpOptions(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getAllowedMethods /// </java-name> [Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")] public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<string>); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPut /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)] public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "PUT"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPut() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPut(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpDelete /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)] public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "DELETE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpDelete() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpDelete(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)] public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpRequestBase() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] public virtual string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] public virtual global::System.Uri GetURI() /* MethodBuilder.Create */ { return default(global::System.Uri); } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IRequestLine); } /// <java-name> /// setURI /// </java-name> [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)] public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ { } /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)] public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ { } /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1)] public virtual void Abort() /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)] public virtual bool IsAborted() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetMethod(); } } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] get{ return GetProtocolVersion(); } } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> public global::System.Uri URI { [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] get{ return GetURI(); } [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] set{ SetURI(value); } } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } } /// <summary> /// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/AbortableHttpRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)] public partial interface IAbortableHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para> /// </summary> /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)] void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para> /// </summary> /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)] void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; } /// <summary> /// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpTrace /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)] public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "TRACE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpTrace() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpTrace(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpUriRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)] public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] string GetMethod() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)] global::System.Uri GetURI() /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts execution of the request.</para><para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)] bool IsAborted() /* MethodBuilder.Create */ ; } /// <summary> /// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpHead /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)] public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "HEAD"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpHead() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpHead(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpEntityEnclosingRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)] public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */ { } /// <java-name> /// getEntity /// </java-name> [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IHttpEntity); } /// <java-name> /// setEntity /// </java-name> [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para> /// </summary> /// <returns> /// <para>true if the expect continue handshake should be used, false if not. </para> /// </returns> /// <java-name> /// expectContinue /// </java-name> [Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)] public virtual bool ExpectContinue() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public override object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IRequestLine); } [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.ProtocolVersion); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <java-name> /// getEntity /// </java-name> public global::Org.Apache.Http.IHttpEntity Entity { [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] get{ return GetEntity(); } [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] set{ SetEntity(value); } } public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] get{ return GetProtocolVersion(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } } /// <summary> /// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPost /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)] public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "POST"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPost() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPost(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using JetBrains.Annotations; namespace Archichect { public class OptionAction { public Option Option { get; } public readonly Func<string[], int, int> Action; public OptionAction(Option option, Func<string[], int, int> action) { Option = option; Action = action; } } public class Option { public readonly string ShortName; public readonly string Name; public readonly string Usage; public readonly string Description; public readonly bool Multiple; public readonly string Default; public readonly string[] MoreNames; public readonly Option OrElse; public Option(string shortname, string name, string usage, string description, Option orElse, bool multiple = false, string[] moreNames = null) : this(shortname, name, usage, description, @default: "", multiple: multiple, moreNames: moreNames) { OrElse = orElse; // not yet used ... } public Option(string shortname, string name, string usage, string description, bool @default, bool multiple = false, string[] moreNames = null) : this(shortname, name, usage, description, @default: @default ? "true" : "false", multiple: multiple, moreNames: moreNames) { } public Option(string shortname, string name, string usage, string description, string @default, bool multiple = false, string[] moreNames = null) { ShortName = shortname; Name = name; Usage = usage; Description = description; Multiple = multiple; Default = @default; MoreNames = moreNames ?? new string[0]; } public string Opt => "-" + Name; public bool Required => Default == null; public override string ToString() { return "/" + ShortName; } public bool IsMatch(string arg) { return ArgMatches(arg, OneAndMore(ShortName, OneAndMore(Name, MoreNames))); } [NotNull] public static string CreateHelp(IEnumerable<Option> options, bool detailed, string filter) { var sb = new StringBuilder(); if (detailed) { sb.AppendLine(); } int lineLength = 0; foreach (var o in options.Where(o => ("/" + o.Name + " /" + o.ShortName + " -" + o.Name + " -" + o.ShortName + " " + o.Description) .IndexOf(filter ?? "", StringComparison.InvariantCultureIgnoreCase) >= 0)) { if (detailed) { sb.AppendLine("-" + o.Name + " or -" + o.ShortName + " " + o.Usage); sb.AppendLine(" " + o.Description); if (o.Required) { sb.AppendLine(o.Multiple ? " Required; can be specified more than once" : " Required"); } else if (o.Default == "") { if (o.Multiple) { sb.AppendLine(" Can be specified more than once"); } } else { sb.AppendLine(o.Multiple ? $" Default: {o.Default}; can be specified more than once" : $" Default: {o.Default}"); } } else { var optString = "-" + o.ShortName + " " + o.Usage; lineLength += optString.Length; if (lineLength > 60) { sb.AppendLine(); lineLength = 0; } sb.Append(o.Required ? " " + optString : " [" + optString + "]"); } } return sb.ToString(); } [NotNull] public OptionAction Action(Func<string[], int, int> action) { return new OptionAction(this, action); } private static IEnumerable<T> OneAndMore<T>(T first, IEnumerable<T> rest) { yield return first; foreach (var e in rest) { yield return e; } } public static bool ArgMatches([NotNull] string arg, string firstOption, params string[] moreOptions) { return ArgMatches(arg, OneAndMore(firstOption, moreOptions)); } private static bool ArgMatches(string arg, IEnumerable<string> options) { return options.Any(o => { string lower = arg.ToLowerInvariant(); if (lower.StartsWith("/" + o) || lower.StartsWith("-" + o)) { string rest = arg.Substring(1 + o.Length); return rest == "" || rest.StartsWith("="); } else { return false; } }); } [NotNull] public static string ExtractRequiredOptionValue(string[] args, ref int i, string message, bool allowOptionWithLeadingMinus = false, bool allowRedirection = false) { string optionValue = ExtractOptionValue(args, ref i, allowOptionWithLeadingMinus, allowRedirection); if (string.IsNullOrWhiteSpace(optionValue)) { throw new ArgumentException(message); } return optionValue; } /// <summary> /// Helper method to get option value of value /// </summary> [CanBeNull] public static string ExtractOptionValue(string[] args, ref int i, bool allowOptionWithLeadingMinus = false, bool allowRedirection = false) { string optionValue; string arg = args[i]; string[] argparts = arg.Split(new[] { '=' }, 2); var nextI = i; if (argparts.Length > 1 && argparts[1] != "") { // /#=value ==> optionValue: "value" optionValue = argparts[1]; } else { // /# value ==> optionValue: "value" // -# value ==> optionValue: "value" // /#= value ==> optionValue: "value" // /#= value ==> optionValue: "value" optionValue = nextI + 1 >= args.Length ? null : args[++nextI]; } if (optionValue == null) { i = nextI; return null; } else if (!allowOptionWithLeadingMinus && LooksLikeAnOption(optionValue)) { // This is the following option - i is not changed return null; } else if (!allowRedirection && LooksLikeRedirection(optionValue)) { // This is the following option - i is not changed return null; } else if (IsOptionGroupStart(optionValue)) { i = nextI; return CollectMultipleArgs(args, ref i); } else { i = nextI; return optionValue; } } public static bool IsOptionGroupStart(string optionValue) { return optionValue == "{" || optionValue == "<." || Regex.IsMatch(optionValue, @"^{\s+") || Regex.IsMatch(optionValue, @"^<\.\s+"); } public static bool IsOptionGroupEnd(string optionValue) { return optionValue == "}" || optionValue == ".>" || Regex.IsMatch(optionValue, @"\s+}$") || Regex.IsMatch(optionValue, @"\s+\.>$"); } private static bool LooksLikeAnOption(string s) { return !IsHelpOption(s) && s.Length > 1 && (s.StartsWith("-") || s.StartsWith("/") && !s.Substring(1).Contains("/") // this allows some paths with / as option value ); } private static bool LooksLikeRedirection(string s) { return s == ">" || s == ">>"; } public static bool IsHelpOption([CanBeNull] string s) { return ArgMatches(s ?? "", "?", "help") || s?.ToUpperInvariant() == "HELP"; } public static int ExtractIntOptionValue(string[] args, ref int j, string msg) { int value; if (!int.TryParse(ExtractOptionValue(args, ref j), out value)) { ThrowArgumentException(msg, string.Join(" ", args)); } return value; } [NotNull] private static string CollectMultipleArgs(string[] args, ref int i) { int inBracesDepth = 0; var argsList = new List<string>(); for (; ; i++) { if (i >= args.Length) { throw new ArgumentException("Missing } at end of options"); } ProcessLine(args[i], ref inBracesDepth, argsList); if (inBracesDepth <= 0) { break; } } return string.Join(Environment.NewLine, argsList); } [NotNull] public static string ExtractNextRequiredValue(string[] args, ref int i, string message, bool allowOptionWithLeadingMinus = false, bool allowRedirection = false) { string result = ExtractNextValue(args, ref i, allowOptionWithLeadingMinus, allowRedirection); if (result == null) { throw new ArgumentException(message); } return result; } [CanBeNull] public static string ExtractNextValue(string[] args, ref int i, bool allowOptionWithLeadingMinus = false, bool allowRedirection = false) { if (i >= args.Length - 1) { return null; } else { string value = args[++i]; if (IsOptionGroupStart(value)) { return CollectMultipleArgs(args, ref i); } else if (!allowOptionWithLeadingMinus && LooksLikeAnOption(value)) { --i; return null; } else if (!allowRedirection && LooksLikeRedirection(value)) { --i; return null; } else { return value; } } } public static string[] CollectArgsFromFile([NotNull] string fileName) { var argsList = new List<string>(); int inBracesDepth = 0; using (var sr = new StreamReader(fileName)) { for (;;) { string line = sr.ReadLine(); if (line == null) { break; } ProcessLine(line, ref inBracesDepth, argsList); } } return argsList.ToArray(); } private static void ProcessLine(string line, ref int inBracesDepth, List<string> argsList) { string trimmedLine = Regex.Replace(line, pattern: "//.*$", replacement: "").Trim(); string[] splitLine = trimmedLine.Split(' ', '\t').Select(s => s.Trim()).Where(s => s != "").ToArray(); if (trimmedLine == "") { // ignore } else { if (inBracesDepth > 0) { // lines are not split argsList.Add(line); } else { // on depth 0, lines are split argsList.AddRange(splitLine); } // We traverse the line and manage depth as well as single and concatenated args foreach (var s in splitLine) { if (IsOptionGroupStart(s)) { ++inBracesDepth; } else if (IsOptionGroupEnd(s)) { --inBracesDepth; } } } } internal static void ThrowArgumentException(string message, string argsAsString) { string singleLine = argsAsString.Replace(Environment.NewLine, " "); throw new ArgumentException(message + Environment.NewLine + "Provided options: " + (singleLine.Length > 305 ? singleLine.Substring(0, 300) + "..." : singleLine)); } internal static void Parse([NotNull] GlobalContext globalContext, [CanBeNull] string argsAsString, params OptionAction[] optionActions) { string[] args; if (string.IsNullOrWhiteSpace(argsAsString)) { args = new string[0]; } else if (IsOptionGroupStart(argsAsString.Trim())) { var argList = new List<string>(); Match prefixMatch = Regex.Match(argsAsString, @"^([{]|\s|<[.])*"); Match suffixMatch = Regex.Match(argsAsString, @"([}]|\s|[.]>)*$"); string trimmedArgs = argsAsString.Substring(prefixMatch.Length, Math.Max(0, argsAsString.Length - prefixMatch.Length - suffixMatch.Length)); using (var sr = new StringReader(trimmedArgs)) { for (;;) { string line = sr.ReadLine(); if (line == null) { break; } if (line == "") { // ignore; } else { argList.Add(line); } } } args = argList.ToArray(); } else { args = new[] { argsAsString }; } HashSet<Option> requiredOptions = new HashSet<Option>(optionActions.Where(oa => oa.Option != null && oa.Option.Required).Select(oa => oa.Option)); for (int i = 0; i < args.Length; i++) { string arg = args[i].Trim(); OptionAction optionAction = optionActions.FirstOrDefault(oa => oa.Option.IsMatch(arg)); if (optionAction != null) { requiredOptions.Remove(optionAction.Option); i = optionAction.Action(args, i); if (i == int.MaxValue) { break; } } else { string message; if (arg.Count(c => c == '/' || c == '-') > 1) { message = "Invalid option " + arg + ", maybe {...} missing"; } else { message = "Invalid option " + arg; } message += Environment.NewLine + "Allowed options: " + CreateHelp(optionActions.Select(oa => oa.Option), detailed: false, filter: ""); ThrowArgumentException(message, argsAsString); } } if (requiredOptions.Any()) { ThrowArgumentException("Missing required options: " + string.Join(", ", requiredOptions.OrderBy(o => o.Name).Select(o => o.Name)), argsAsString); } } [NotNull, ItemNotNull] public static IEnumerable<string> ExpandFilePatternFileNames(string pattern, IEnumerable<string> extensionsForDirectoryReading) { if (pattern.StartsWith("@")) { using (TextReader nameFile = new StreamReader(pattern.Substring(1))) { for (;;) { string name = nameFile.ReadLine(); if (name == null) { break; } name = name.Trim(); if (name != "") { yield return name; } } } } else if (pattern.Contains("*") || pattern.Contains("?")) { int sepPos = pattern.LastIndexOf(Path.DirectorySeparatorChar); string dir = sepPos < 0 ? "." : pattern.Substring(0, sepPos); string filePattern = sepPos < 0 ? pattern : pattern.Substring(sepPos + 1); if (!Directory.Exists(dir)) { throw new IOException($"Directory '{dir}' does not exist (current directory is '{Environment.CurrentDirectory}')"); } foreach (string name in Directory.GetFiles(dir, filePattern)) { yield return name; } } else if (Directory.Exists(pattern)) { foreach (var ext in extensionsForDirectoryReading) { foreach (string name in Directory.GetFiles(pattern, "*" + ext)) { yield return name; } } } else { yield return pattern; } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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; using System.Collections.Generic; using System.Linq; using System.Text; using Gallio.Common.Collections; using Gallio.Framework.Assertions; using MbUnit.Framework; namespace MbUnit.Tests.Framework { [TestsOn(typeof(Assert))] public class AssertTest_Collections : BaseAssertTest { #region AreElementsEqual [Test] public void AreElementsEqual_with_strings() { Assert.AreElementsEqual("12", "12"); } [Test] public void AreElementsEqual_with_different_types() { Assert.AreElementsEqual(new[] { 1, 2 }, new List<int> { 1, 2 }); } [Test] public void AreElementsEqual_with_custom_comparer() { Assert.AreElementsEqual("12", "34", (expected, actual) => expected + 2 == actual); } [Test] public void AreElementsEqual_fails_when_elements_are_in_different_order() { AssertionFailure[] failures = Capture(() => Assert.AreElementsEqual(new[] { 1, 2 }, new List<int> { 2, 1 })); Assert.Count(1, failures); Assert.AreEqual("Expected elements to be equal but they differ in at least one position.", failures[0].Description); Assert.AreEqual("Expected Sequence", failures[0].LabeledValues[0].Label); Assert.AreEqual("[1, 2]", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Actual Sequence", failures[0].LabeledValues[1].Label); Assert.AreEqual("[2, 1]", failures[0].LabeledValues[1].FormattedValue.ToString()); Assert.AreEqual("Element Index", failures[0].LabeledValues[2].Label); Assert.AreEqual("0", failures[0].LabeledValues[2].FormattedValue.ToString()); Assert.AreEqual("Expected Element", failures[0].LabeledValues[3].Label); Assert.AreEqual("1", failures[0].LabeledValues[3].FormattedValue.ToString()); Assert.AreEqual("Actual Element", failures[0].LabeledValues[4].Label); Assert.AreEqual("2", failures[0].LabeledValues[4].FormattedValue.ToString()); } [Test] public void AreElementsEqual_fails_with_custom_message() { AssertionFailure[] failures = Capture(() => Assert.AreElementsEqual("1", "2", "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region AreElementsNotEqual [Test] public void AreElementsNotEqual_with_strings() { Assert.AreElementsNotEqual("12", "1"); } [Test] public void AreElementsNotEqual_with_different_types() { Assert.AreElementsNotEqual(new[] { 1, 2 }, new List<int> { 1, 3 }); } [Test] public void AreElementsNotEqual_with_custom_comparer() { Assert.AreElementsNotEqual("12", "12", (expected, actual) => expected + 2 == actual); } [Test] public void AreElementsNotEqual_fails_when_elements_are_in_different_order() { AssertionFailure[] failures = Capture(() => Assert.AreElementsNotEqual(new[] { 1, 2 }, new List<int> { 1, 2 })); Assert.Count(1, failures); Assert.AreEqual("Expected the unexpected and actual sequence to have different elements but all elements were equal.", failures[0].Description); Assert.AreEqual("Unexpected Sequence", failures[0].LabeledValues[0].Label); Assert.AreEqual("[1, 2]", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Actual Sequence", failures[0].LabeledValues[1].Label); Assert.AreEqual("[1, 2]", failures[0].LabeledValues[1].FormattedValue.ToString()); } [Test] public void AreElementsNotEqual_fails_with_custom_message() { AssertionFailure[] failures = Capture(() => Assert.AreElementsNotEqual("2", "2", "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region AreElementsEqualIgnoringOrder [Test] public void AreElementsEqualIgnoringOrder_with_strings() { Assert.AreElementsEqualIgnoringOrder("122", "212"); } [Test] public void AreElementsEqualIgnoringOrder_with_different_types() { Assert.AreElementsEqualIgnoringOrder(new[] { 2, 2, 3, 1 }, new List<int> { 1, 3, 2, 2 }); } [Test] public void AreElementsEqualIgnoringOrder_with_custom_comparer() { Assert.AreElementsEqualIgnoringOrder("12", "43", (expected, actual) => expected + 2 == actual); } [Test] public void AreElementsEqualIgnoringOrder_fails_when_excess_or_missing_elements() { AssertionFailure[] failures = Capture(() => Assert.AreElementsEqualIgnoringOrder(new[] { 1, 2, 3, 2, 3, 1 }, new List<int> { 4, 2, 1, 1, 4, 1, 4 })); Assert.Count(1, failures); Assert.AreEqual("Expected elements to be equal but possibly in a different order.", failures[0].Description); Assert.AreEqual("Equal Elements", failures[0].LabeledValues[0].Label); Assert.AreEqual("[1, 1, 2]", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Excess Elements", failures[0].LabeledValues[1].Label); Assert.AreEqual("[1, 4, 4, 4]", failures[0].LabeledValues[1].FormattedValue.ToString()); Assert.AreEqual("Missing Elements", failures[0].LabeledValues[2].Label); Assert.AreEqual("[2, 3, 3]", failures[0].LabeledValues[2].FormattedValue.ToString()); } [Test] public void AreElementsEqualIgnoringOrder_fails_with_custom_message() { AssertionFailure[] failures = Capture(() => Assert.AreElementsEqualIgnoringOrder("1", "2", "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region AreElementsSame [Test] public void AreElementsSame_with_objects() { var o = new object(); Assert.AreElementsSame(new[] { o }, new[] { o }); } [Test] public void AreElementsSame_with_different_types() { var o1 = new object(); var o2 = new object(); Assert.AreElementsSame(new[] { o1, o2 }, new List<object> { o1, o2 }); } [Test] public void AreElementsSame_fails_when_elements_are_in_different_order() { var o1 = new object(); var o2 = new object(); AssertionFailure[] failures = Capture(() => Assert.AreElementsSame(new[] { o1, o2 }, new List<object> { o2, o1 })); Assert.Count(1, failures); Assert.AreEqual("Expected elements to be referentially equal but they differ in at least one position.", failures[0].Description); } [Test] public void AreElementsSame_fails_with_custom_message() { var o1 = new object(); var o2 = new object(); AssertionFailure[] failures = Capture(() => Assert.AreElementsSame(new[] { o1 }, new[] { o2 }, "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region AreElementsNotSame [Test] public void AreElementsNotSame_with_objects() { var o1 = new object(); var o2 = new object(); Assert.AreElementsNotSame(new[] { o1 }, new[] { o2 }); } [Test] public void AreElementsNotSame_with_different_types() { var o1 = new object(); var o2 = new object(); var o3 = new object(); Assert.AreElementsNotSame(new[] { o1, o2 }, new List<object> { o1, o3 }); } [Test] public void AreElementsNotSame_fails_with_custom_message() { var o = new object(); AssertionFailure[] failures = Capture(() => Assert.AreElementsNotSame(new[] { o }, new[] { o }, "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region AreElementsSameIgnoringOrder [Test] public void AreElementsSameIgnoringOrder_with_different_types() { var o1 = new object(); var o2 = new object(); var o3 = new object(); Assert.AreElementsSameIgnoringOrder(new[] { o2, o2, o3, o1 }, new List<object> { o1, o3, o2, o2 }); } [Test] public void AreElementsSameIgnoringOrder_fails_when_excess_or_missing_elements() { var o1 = new object(); var o2 = new object(); var o3 = new object(); var o4 = new object(); AssertionFailure[] failures = Capture(() => Assert.AreElementsSameIgnoringOrder(new[] { o1, o2, o3, o2, o3, o1 }, new List<object> { o4, o2, o1, o1, o4, o1, o4 })); Assert.Count(1, failures); Assert.AreEqual("Expected elements to be referentially equal but possibly in a different order.", failures[0].Description); } [Test] public void AreElementsSameIgnoringOrder_fails_with_custom_message() { var o1 = new object(); var o2 = new object(); AssertionFailure[] failures = Capture(() => Assert.AreElementsSameIgnoringOrder(new[] { o1 }, new[] { o2 }, "{0} message", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message", failures[0].Message); } #endregion #region Contains (for collections) [Test] public void Contains_generic_ICollection_int_test() { Assert.Contains(new List<int>(new[] { 1, 2, 3 }), 2); } [Test] [Row("2", new[] { "1", "2", "3" })] [Row(null, new[] { "1", "2", null, "3" })] public void Contains_list_string_test(string testValue, string[] list) { Assert.Contains(new List<string>(list), testValue); } [Test] [Row(new[] { 1, 2, 3 }, "[1, 2, 3]")] [Row(new[] { 1, 2 }, "[1, 2]")] [Row(new[] { 1, 2, 3, 5 }, "[1, 2, 3, 5]")] public void Contains_fails_when_test_value_is_not_in_the_list(int[] listItems, string expectedCollection) { AssertionFailure[] failures = Capture(() => Assert.Contains(new List<int>(listItems), 4)); Assert.Count(1, failures); Assert.AreEqual("Expected the value to appear within the enumeration.", failures[0].Description); Assert.AreEqual("Expected Value", failures[0].LabeledValues[0].Label); Assert.AreEqual("4", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Enumeration", failures[0].LabeledValues[1].Label); Assert.AreEqual(expectedCollection, failures[0].LabeledValues[1].FormattedValue.ToString()); } [Test] [Row("test", new[] { "1", "2", "3" }, "\"test\"", "[\"1\", \"2\", \"3\"]")] [Row(null, new[] { "1", "2", "3" }, "null", "[\"1\", \"2\", \"3\"]")] public void Contains_fails_when_test_value_is_not_in_the_string_list(string testValue, string[] listItems, string expectedLabledValue, string expectedCollection) { AssertionFailure[] failures = Capture(() => Assert.Contains(new List<string>(listItems), testValue)); Assert.Count(1, failures); Assert.AreEqual("Expected the value to appear within the enumeration.", failures[0].Description); Assert.AreEqual("Expected Value", failures[0].LabeledValues[0].Label); Assert.AreEqual(expectedLabledValue, failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Enumeration", failures[0].LabeledValues[1].Label); Assert.AreEqual(expectedCollection, failures[0].LabeledValues[1].FormattedValue.ToString()); } [Test] public void ContainsKey_dictionary_int_test() { Assert.ContainsKey(new Dictionary<int, int> { {1, 1}, {2, 2} }, 2); } [Test] public void ContainsKey_fails_when_test_value_is_not_in_the_dictionary() { var dictionary = new Dictionary<int, string> { { 1, "1" }, { 2, "2`" }, }; AssertionFailure[] failures = Capture(() => Assert.ContainsKey(dictionary, 0)); Assert.Count(1, failures); Assert.AreEqual("Expected the key to appear within the dictionary.", failures[0].Description); Assert.AreEqual("Expected Key", failures[0].LabeledValues[0].Label); Assert.AreEqual("0", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Dictionary", failures[0].LabeledValues[1].Label); Assert.AreEqual("[1: \"1\", 2: \"2`\"]", failures[0].LabeledValues[1].FormattedValue.ToString()); } [Test] public void Contains_fails_when_test_value_is_not_in_the_dictionary_key_is_reference_type() { var dictionary = new Dictionary<List<int>, string> { { new List<int>(new[] {1, 2}), "1" }, { new List<int>(new[] {3, 4}), "2`" }, }; AssertionFailure[] failures = Capture(() => Assert.ContainsKey(dictionary, new List<int>(new[] { 5 }))); Assert.Count(1, failures); Assert.AreEqual("Expected the key to appear within the dictionary.", failures[0].Description); Assert.AreEqual("Expected Key", failures[0].LabeledValues[0].Label); Assert.AreEqual("[5]", failures[0].LabeledValues[0].FormattedValue.ToString()); Assert.AreEqual("Dictionary", failures[0].LabeledValues[1].Label); Assert.AreEqual("[[1, 2]: \"1\", [3, 4]: \"2`\"]", failures[0].LabeledValues[1].FormattedValue.ToString()); } [Test] public void Contains_fails_with_custom_message() { AssertionFailure[] failures = Capture(() => Assert.Contains(new List<int>(new[] { 1, 2, 3 }), 5, "{0} message.", "custom")); Assert.Count(1, failures); Assert.AreEqual("custom message.", failures[0].Message); } #endregion #region ForAll [Test] public void ForAll_should_pass() { var data = new[] { "Athos", "Porthos", "Aramis" }; Assert.ForAll(data, x => x.Contains("a") || x.Contains("o")); } [Test] public void ForAll_should_fail() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.ForAll(data, x => x.StartsWith("A"))); Assert.Count(1, failures); Assert.AreEqual("Expected all the elements of the sequence to meet the specified condition, but at least one failed.", failures[0].Description); } [Test] public void ForAllAction_should_pass() { var data = new[] { "Athos", "Porthos", "Aramis" }; Assert.ForAll(data, x => { Assert.Contains(x, "s"); }); } [Test] public void ForAllAction_should_fail() { var data = new[] { "Athos", "Porthos", "Aramis", "D'Artagnan" }; AssertionFailure[] failures = Capture(() => Assert.ForAll(data, x => { Assert.StartsWith(x, "A"); })); Assert.Count(1, failures); Assert.AreEqual("Expected all the elements of the sequence to pass assert validations, but at least one failed.", failures[0].Description); Assert.Count(2, failures[0].InnerFailures); } [Test] public void ForAllActionIndex_should_fail() { var data = new[] { "Athos", "Porthos", "Aramis", "D'Artagnan" }; AssertionFailure[] failures = Capture(() => Assert.ForAll(data, (value, index) => { if (index < 3) Assert.StartsWith(value, "A"); })); Assert.Count(1, failures); Assert.AreEqual("Expected all the elements of the sequence to pass assert validations, but at least one failed.", failures[0].Description); Assert.Count(1, failures[0].InnerFailures); // The D'Artagnan should not be checked because only the first three entries are validated. } [Test] public void ForAll_should_fail_with_custom_message() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.ForAll(data, x => x.Contains("x"),"{0} message.","Custom")); Assert.Count(1, failures); Assert.AreEqual("Custom message.", failures[0].Message); } #endregion #region Exists [Test] public void Exists_should_pass() { var data = new[] { "Athos", "Porthos", "Aramis" }; Assert.Exists(data, x => x.Contains("th")); } [Test] public void Exists_should_fail() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.Exists(data, x => x == "D'Artagnan")); Assert.Count(1, failures); Assert.AreEqual("Expected at least one element of the sequence to meet the specified condition, but none passed.", failures[0].Description); } [Test] public void Exists_should_fail_with_custom_message() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.Exists(data, x => x == "D'Artagnan","{0} message.","Custom")); Assert.Count(1, failures); Assert.AreEqual("Custom message.", failures[0].Message); } #endregion #region DoesNotExist [Test] public void DoesNotExist_should_pass() { var data = new[] { "Athos", "Porthos", "Aramis" }; Assert.DoesNotExist(data, x => x.Contains("D'A")); } [Test] public void DoesNotExist_should_fail() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.DoesNotExist(data, x => x == "Porthos")); Assert.Count(1, failures); Assert.AreEqual("Expected none of the elements of the sequence to meet the specified condition, but one did.", failures[0].Description); } [Test] public void DoesNotExist_should_fail_with_custom_message() { var data = new[] { "Athos", "Porthos", "Aramis" }; AssertionFailure[] failures = Capture(() => Assert.DoesNotExist(data, x => x == "Porthos","{0} message.","Custom")); Assert.Count(1, failures); Assert.AreEqual("Custom message.", failures[0].Message); } [Test] [ExpectedArgumentNullException] public void DoesNotExist_throws_exception_with_null_values_argument() { string[] data = null; Assert.DoesNotExist(data, x => x == "Porthos", "{0} message.", "Custom"); } [Test] [ExpectedArgumentNullException] public void DoesNotExist_throws_exception_with_null_predicate_argument() { var data = new[] { "Athos", "Porthos", "Aramis" }; Assert.DoesNotExist(data, null); } #endregion #region IsEmpty private static IEnumerable GetEmptyEnumeration() { yield break; } [Test] public void IsEmpty_should_pass() { Assert.IsEmpty(EmptyArray<int>.Instance); Assert.IsEmpty(new List<int>()); Assert.IsEmpty(GetEmptyEnumeration()); } [Test] public void IsEmpty_should_fail() { AssertionFailure[] failures = Capture(() => Assert.IsEmpty(new[] { 123, 456, 789 })); Assert.Count(1, failures); Assert.Like(failures[0].Description, @"^Expected the sequence to be empty but \d+ counting strateg(y has|ies have) failed.$"); Assert.AreEqual("Expected Value", failures[0].LabeledValues[0].Label); Assert.AreEqual("0", failures[0].LabeledValues[0].FormattedValue.ToString()); for (int i = 1; i <= failures[0].LabeledValues.Count - 1; i++) { Assert.Like(failures[0].LabeledValues[i].Label, @"^Actual Value \([\w ]+\)?$"); Assert.AreEqual("3", failures[0].LabeledValues[i].FormattedValue.ToString()); } } [Test] public void IsEmpty_should_fail_with_custom_message() { AssertionFailure[] failures = Capture(() => Assert.IsEmpty(new[] { 13, 46, 79 }, "{0} message.", "Custom")); Assert.Count(1, failures); Assert.AreEqual("Custom message.", failures[0].Message); } #endregion } }
using System; using System.Text; namespace IngenuityMicro.Radius.Hardware { /// <summary> /// Extends the .NET Micro Framework SerialPort Class with additional methods from the Full .NET Framework SerialPort Class /// as well as other useful methods. /// </summary> public class SimpleSerial : System.IO.Ports.SerialPort { // CONSTRUCTORS -- Pass the Buck public SimpleSerial(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits) : base(portName, baudRate, parity, dataBits, stopBits) { } public SimpleSerial(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits) : base(portName, baudRate, parity, dataBits) { } public SimpleSerial(string portName, int baudRate, System.IO.Ports.Parity parity) : base(portName, baudRate, parity) { } public SimpleSerial(string portName, int baudRate) : base(portName, baudRate) { } public SimpleSerial(string portName) : base(portName) { } /// <summary> /// Writes the specified string to the serial port. /// </summary> /// <param name="txt"></param> public void Write(string txt) { base.Write(Encoding.UTF8.GetBytes(txt), 0, txt.Length); } //public void Write(byte[] buffer, int offset, int len) //{ // base.Write(buffer, offset, len); //} /// <summary> /// Writes the specified string and the NewLine value to the output buffer. /// </summary> /// <param name="txt"></param> public void WriteLine(string txt) { this.Write(txt + "\r\n"); } /// <summary> /// Reads all immediately available bytes, as binary data, in both the stream and the input buffer of the SerialPort object. /// </summary> /// <returns>byte[]</returns> public byte[] ReadExistingBinary() { int arraySize = this.BytesToRead; byte[] received = new byte[arraySize]; this.Read(received, 0, arraySize); return received; } /// <summary> /// Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object. /// </summary> /// <returns>String</returns> public string ReadExisting() { try { return new string(Encoding.UTF8.GetChars(this.ReadExistingBinary())); } catch (Exception) { return string.Empty; } } /// <summary> /// Opens a new serial port connection. /// </summary> public new void Open() { this._Remainder = string.Empty; // clear the remainder so it doesn't get mixed with data from the new session base.Open(); } /// <summary> /// Stores any incomplete message that hasn't yet been terminated with a delimiter. /// This will be concatenated with new data from the next DataReceived event to (hopefully) form a complete message. /// This property is only populated after the Deserialize() method has been called. /// </summary> private string _Remainder = string.Empty; public string Remainder { get { return this._Remainder; } } /// <summary> /// Splits data from a serial buffer into separate messages, provided that each message is delimited by one or more end-of-line character(s). /// </summary> /// <param name="delimiter">Character sequence that terminates a message line. Default is "\r\n".</param> /// <returns> /// An array of strings whose items correspond to individual messages, without the delimiters. /// Only complete, properly terminated messages are included. Incomplete message fragments are saved to be appended to /// the next received data. /// /// If no complete messages are found in the serial buffer, the output array will be empty with Length = 0. /// </returns> public string[] Deserialize(string delimiter = "\r\n") { string receivedData = string.Concat(this._Remainder, this.ReadExisting()); // attach the previous remainder to the new data return SplitString(receivedData, out this._Remainder, delimiter); // return itemized messages and store remainder for next pass } /// <summary> /// Splits a stream into separate lines, given a delimiter. /// </summary> /// <param name="input"> /// The string that will be deserialized. /// /// Example: /// Assume a device transmits serial messages, and each message is separated by \r\n (carriage return + line feed). /// /// For illustration, picture the following output from such a device: /// First message.\r\n /// Second message.\r\n /// Third message.\r\n /// Fourth message.\r\n /// /// Once a SerialPort object receives the first bytes, the DataReceived event will be fired, /// and the interrupt handler may read a string from the serial buffer like so: /// "First message.\r\nSecond message.\r\nThird message.\r\nFourth me" /// /// The message above has been cut off to simulate the DataReceived event being fired before the sender has finished /// transmitting all messages (the "ssage.\r\n" characters have not yet traveled down the wire, so to speak). /// At the moment the DataReceived event is fired, the interrupt handler only has access to the (truncated) /// input message above. /// /// In this example, the string from the serial buffer will be the input to this method. /// </param> /// <param name="remainder"> /// Any incomplete messages that have not yet been properly terminated will be returned via this output parameter. /// In the above example, this parameter will return "Fourth me". Ideally, this output parameter will be appended to the next /// transmission to reconstruct the next complete message. /// </param> /// <param name="delimiter"> /// A string specifying the delimiter between messages. /// If omitted, this defaults to "\r\n" (carriage return + line feed). /// </param> /// <param name="includeDelimiterInOutput"> /// Determines whether each item in the output array will include the specified delimiter. /// If True, the delimiter will be included at the end of each string in the output array. /// If False (default), the delimiter will be excluded from the output strings. /// </param> /// <returns> /// string[] /// Every item in this string array will be an individual, complete message. The first element /// in the array corresponds to the first message, and so forth. The length of the array will be equal to the number of /// complete messages extracted from the input string. /// /// From the above example, if includeDelimiterInOutput == True, this output will be: /// output[0] = "First message.\r\n" /// output[1] = "Second message.\r\n" /// output[2] = "Third message.\r\n" /// /// If no complete messages have been received, the output array will be empty with Length = 0. /// </returns> private static string[] SplitString(string input, out string remainder, string delimiter = "\r\n", bool includeDelimiterInOutput = false) { string[] prelimOutput = input.Split(delimiter.ToCharArray()); // Check last element of prelimOutput to determine if it was a delimiter. // We know that the last element was a delimiter if the string.Split() method makes it empty. if (prelimOutput[prelimOutput.Length - 1] == string.Empty) remainder = string.Empty; // input string terminated in a delimiter, so there is no remainder else { remainder = prelimOutput[prelimOutput.Length - 1]; // store the remainder prelimOutput[prelimOutput.Length - 1] = string.Empty; // remove the remainder string from prelimOutput to avoid redundancy } if (includeDelimiterInOutput == true) return ScrubStringArray(prelimOutput, removeString: string.Empty, delimiter: delimiter); else return ScrubStringArray(prelimOutput, removeString: string.Empty, delimiter: string.Empty); } /// <summary> /// Removes items in an input array that are equal to a specified string. /// </summary> /// <param name="input">String array to scrub.</param> /// <param name="removeString">String whose occurrences will be removed if an item consists of it. Default: string.Empty.</param> /// <param name="delimiter"> /// Delimiter that will be appended to the end of each element in the output array. Default: \r\n (carriage return + line feed). /// To omit delimiters from the end of each message, set this parameter to string.Empty. /// </param> /// <returns> /// String array containing only desired strings. The length of this output will likely be shorter than the input array. /// </returns> private static string[] ScrubStringArray(string[] input, string removeString = "", string delimiter = "\r\n") { // Note: I originally wanted to use a System.Collections.ArrayList object here and then run the ToArray() method, // but the compiler throws runtime exceptions for some reason, so I've resorted to this manual array-copying approach instead. int numOutputElements = 0; // Determine the bounds of the output array by looking for input elements that meet inclusion criterion for (int k = 0; k < input.Length; k++) { if (input[k] != removeString) numOutputElements++; } // Declare and populate output array string[] output = new string[numOutputElements]; int m = 0; // output index for (int k = 0; k < input.Length; k++) { if (input[k] != removeString) { output[m] = input[k] + delimiter; m++; } } return output; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { internal enum TriggerIdentifierKind { NotRenamable, RenamableDeclaration, RenamableReference, } /// <summary> /// Determines whether the original token was a renamable identifier on a background thread /// </summary> private class TrackingSession : ForegroundThreadAffinitizedObject { private static readonly Task<TriggerIdentifierKind> s_notRenamableTask = Task.FromResult(TriggerIdentifierKind.NotRenamable); private readonly Task<TriggerIdentifierKind> _isRenamableIdentifierTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly CancellationToken _cancellationToken; private readonly IAsynchronousOperationListener _asyncListener; private Task<bool> _newIdentifierBindsTask = Task.FromResult(false); private readonly string _originalName; public string OriginalName { get { return _originalName; } } private readonly ITrackingSpan _trackingSpan; public ITrackingSpan TrackingSpan { get { return _trackingSpan; } } public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener) { AssertIsForeground(); _asyncListener = asyncListener; _trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive); _cancellationTokenSource = new CancellationTokenSource(); _cancellationToken = _cancellationTokenSource.Token; if (snapshotSpan.Length > 0) { // If the snapshotSpan is nonempty, then the session began with a change that // was touching a word. Asynchronously determine whether that word was a // renamable identifier. If it is, alert the state machine so it can trigger // tagging. _originalName = snapshotSpan.GetText(); _isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true), _cancellationToken, TaskScheduler.Default); QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask); } else { // If the snapshotSpan is empty, that means text was added in a location that is // not touching an existing word, which happens a fair amount when writing new // code. In this case we already know that the user is not renaming an // identifier. _isRenamableIdentifierTask = s_notRenamableTask; } } private void QueueUpdateToStateMachine(StateMachine stateMachine, Task task) { var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); task.SafeContinueWith(t => { AssertIsForeground(); if (_isRenamableIdentifierTask.Result != TriggerIdentifierKind.NotRenamable) { stateMachine.OnTrackingSessionUpdated(this); } }, _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken); } internal void CheckNewIdentifier(StateMachine stateMachine, ITextSnapshot snapshot) { AssertIsForeground(); _newIdentifierBindsTask = _isRenamableIdentifierTask.SafeContinueWithFromAsync( async t => t.Result != TriggerIdentifierKind.NotRenamable && TriggerIdentifierKind.RenamableReference == await DetermineIfRenamableIdentifierAsync( TrackingSpan.GetSpan(snapshot), initialCheck: false).ConfigureAwait(false), _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); QueueUpdateToStateMachine(stateMachine, _newIdentifierBindsTask); } internal bool IsDefinitelyRenamableIdentifier() { // This needs to be able to run on a background thread for the CodeFix return IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult: false, cancellationToken: CancellationToken.None); } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } private async Task<TriggerIdentifierKind> DetermineIfRenamableIdentifierAsync(SnapshotSpan snapshotSpan, bool initialCheck) { AssertIsBackground(); var document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var syntaxTree = await document.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); var token = syntaxTree.GetTouchingWord(snapshotSpan.Start.Position, syntaxFactsService, _cancellationToken); // The OriginalName is determined with a simple textual check, so for a // statement such as "Dim [x = 1" the textual check will return a name of "[x". // The token found for "[x" is an identifier token, but only due to error // recovery (the "[x" is actually in the trailing trivia). If the OriginalName // found through the textual check has a different length than the span of the // touching word, then we cannot perform a rename. if (initialCheck && token.Span.Length != this.OriginalName.Length) { return TriggerIdentifierKind.NotRenamable; } if (syntaxFactsService.IsIdentifier(token)) { var semanticModel = await document.GetSemanticModelForNodeAsync(token.Parent, _cancellationToken).ConfigureAwait(false); var semanticFacts = document.GetLanguageService<ISemanticFactsService>(); var symbol = semanticFacts.GetDeclaredSymbol(semanticModel, token, _cancellationToken); symbol = symbol ?? semanticModel.GetSymbolInfo(token, _cancellationToken).Symbol; if (symbol != null) { // Get the source symbol if possible symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol; return symbol.Locations.All(loc => loc.IsInSource) ? symbol.Locations.Any(loc => loc == token.GetLocation()) ? TriggerIdentifierKind.RenamableDeclaration : TriggerIdentifierKind.RenamableReference : TriggerIdentifierKind.NotRenamable; } } } return TriggerIdentifierKind.NotRenamable; } internal bool CanInvokeRename(ISyntaxFactsService syntaxFactsService, bool isSmartTagCheck, bool waitForResult, CancellationToken cancellationToken) { if (IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult, cancellationToken)) { var isRenamingDeclaration = _isRenamableIdentifierTask.Result == TriggerIdentifierKind.RenamableDeclaration; var newName = TrackingSpan.GetText(TrackingSpan.TextBuffer.CurrentSnapshot); var comparison = isRenamingDeclaration || syntaxFactsService.IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if (!string.Equals(OriginalName, newName, comparison) && syntaxFactsService.IsValidIdentifier(newName)) { // At this point, we want to allow renaming if the user invoked Ctrl+. explicitly, but we // want to avoid showing a smart tag if we're renaming a reference that binds to an existing // symbol. if (!isSmartTagCheck || isRenamingDeclaration || !NewIdentifierDefinitelyBindsToReference()) { return true; } } } return false; } private bool NewIdentifierDefinitelyBindsToReference() { return _newIdentifierBindsTask.Status == TaskStatus.RanToCompletion && _newIdentifierBindsTask.Result; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace FoodServicesMenu.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudIAP.v1beta1 { /// <summary>The CloudIAP Service.</summary> public class CloudIAPService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudIAPService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudIAPService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { V1beta1 = new V1beta1Resource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "iap"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://iap.googleapis.com/"; #else "https://iap.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://iap.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Identity-Aware Proxy API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Identity-Aware Proxy API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the V1beta1 resource.</summary> public virtual V1beta1Resource V1beta1 { get; } } /// <summary>A base abstract class for CloudIAP requests.</summary> public abstract class CloudIAPBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudIAPBaseServiceRequest instance.</summary> protected CloudIAPBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudIAP parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "v1beta1" collection of methods.</summary> public class V1beta1Resource { private const string Resource = "v1beta1"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public V1beta1Resource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets the access control policy for an Identity-Aware Proxy protected resource. More information about /// managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual GetIamPolicyRequest GetIamPolicy(Google.Apis.CloudIAP.v1beta1.Data.GetIamPolicyRequest body, string resource) { return new GetIamPolicyRequest(service, body, resource); } /// <summary> /// Gets the access control policy for an Identity-Aware Proxy protected resource. More information about /// managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> public class GetIamPolicyRequest : CloudIAPBaseServiceRequest<Google.Apis.CloudIAP.v1beta1.Data.Policy> { /// <summary>Constructs a new GetIamPolicy request.</summary> public GetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIAP.v1beta1.Data.GetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudIAP.v1beta1.Data.GetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "getIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:getIamPolicy"; /// <summary>Initializes GetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^.*$", }); } } /// <summary> /// Sets the access control policy for an Identity-Aware Proxy protected resource. Replaces any existing policy. /// More information about managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CloudIAP.v1beta1.Data.SetIamPolicyRequest body, string resource) { return new SetIamPolicyRequest(service, body, resource); } /// <summary> /// Sets the access control policy for an Identity-Aware Proxy protected resource. Replaces any existing policy. /// More information about managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> public class SetIamPolicyRequest : CloudIAPBaseServiceRequest<Google.Apis.CloudIAP.v1beta1.Data.Policy> { /// <summary>Constructs a new SetIamPolicy request.</summary> public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIAP.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudIAP.v1beta1.Data.SetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "setIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:setIamPolicy"; /// <summary>Initializes SetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^.*$", }); } } /// <summary> /// Returns permissions that a caller has on the Identity-Aware Proxy protected resource. If the resource does /// not exist or the caller does not have Identity-Aware Proxy permissions a [google.rpc.Code.PERMISSION_DENIED] /// will be returned. More information about managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for /// the appropriate value for this field. /// </param> public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CloudIAP.v1beta1.Data.TestIamPermissionsRequest body, string resource) { return new TestIamPermissionsRequest(service, body, resource); } /// <summary> /// Returns permissions that a caller has on the Identity-Aware Proxy protected resource. If the resource does /// not exist or the caller does not have Identity-Aware Proxy permissions a [google.rpc.Code.PERMISSION_DENIED] /// will be returned. More information about managing access via IAP can be found at: /// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api /// </summary> public class TestIamPermissionsRequest : CloudIAPBaseServiceRequest<Google.Apis.CloudIAP.v1beta1.Data.TestIamPermissionsResponse> { /// <summary>Constructs a new TestIamPermissions request.</summary> public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIAP.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation /// for the appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudIAP.v1beta1.Data.TestIamPermissionsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "testIamPermissions"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:testIamPermissions"; /// <summary>Initializes TestIamPermissions parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^.*$", }); } } } } namespace Google.Apis.CloudIAP.v1beta1.Data { /// <summary>Associates `members` with a `role`.</summary> public class Binding : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding /// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to /// the current request. However, a different role binding might grant the same role to one or more of the /// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual Expr Condition { get; set; } /// <summary> /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following /// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a /// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated /// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific /// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that /// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: /// An email address that represents a Google group. For example, `admins@example.com`. * /// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that /// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is /// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * /// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a /// service account that has been recently deleted. For example, /// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, /// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the /// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing /// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. /// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role /// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that /// domain. For example, `google.com` or `example.com`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("members")] public virtual System.Collections.Generic.IList<string> Members { get; set; } /// <summary> /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression /// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example /// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" /// expression: "document.summary.size() &amp;lt; 100" Example (Equality): title: "Requestor is owner" description: /// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" /// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly /// visible" expression: "document.type != 'private' &amp;amp;&amp;amp; document.type != 'internal'" Example (Data /// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." /// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that /// may be referenced within an expression are determined by the service that evaluates it. See the service /// documentation for additional information. /// </summary> public class Expr : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when /// hovered over it in a UI. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Textual representation of an expression in Common Expression Language syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expression")] public virtual string Expression { get; set; } /// <summary> /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a /// position in the file. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs /// which allow to enter the expression. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `GetIamPolicy` method.</summary> public class GetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("options")] public virtual GetPolicyOptions Options { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Encapsulates settings provided to GetIamPolicy.</summary> public class GetPolicyOptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an /// invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3. /// Policies without any conditional bindings may specify any valid value or leave the field unset. To learn /// which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedPolicyVersion")] public virtual System.Nullable<int> RequestedPolicyVersion { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A /// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can /// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of /// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google /// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to /// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of /// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the /// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { /// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", /// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, /// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { /// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time /// &amp;lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** /// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - /// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - /// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable /// access description: Does not grant access after Sep 2020 expression: request.time &amp;lt; /// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features, /// see the [IAM documentation](https://cloud.google.com/iam/docs/). /// </summary> public class Policy : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and /// when the `bindings` are applied. Each of the `bindings` must contain at least one member. The `bindings` in /// a `Policy` can refer to up to 1,500 members; up to 250 of these members can be Google groups. Each /// occurrence of a member counts towards these limits. For example, if the `bindings` grant 50 different roles /// to `user:alice@example.com`, and not to any other member, then you can add another 1,450 members to the /// `bindings` in the `Policy`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("bindings")] public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; } /// <summary> /// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy /// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the /// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned /// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to /// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** /// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit /// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary> /// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid /// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This /// requirement applies to the following operations: * Getting a policy that includes a conditional role binding /// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing /// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you /// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this /// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on /// that policy may specify any valid version or leave the field unset. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual System.Nullable<int> Version { get; set; } } /// <summary>Request message for `SetIamPolicy` method.</summary> public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few /// 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might /// reject them. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("policy")] public virtual Policy Policy { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `TestIamPermissions` method.</summary> public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') /// are not allowed. For more information see [IAM /// Overview](https://cloud.google.com/iam/docs/overview#permissions). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("permissions")] public virtual System.Collections.Generic.IList<string> Permissions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for `TestIamPermissions` method.</summary> public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("permissions")] public virtual System.Collections.Generic.IList<string> Permissions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// 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.Runtime.InteropServices; using System.Threading; using Xunit; public partial class ThreadPoolBoundHandleTests { [Fact] public unsafe void AllocateNativeOverlapped_NullAsCallback_ThrowsArgumentNullException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentNullException>("callback", () => { handle.AllocateNativeOverlapped(null, new object(), new byte[256]); }); } } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_ThrowsArgumentNullException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentNullException>("preAllocated", () => { handle.AllocateNativeOverlapped((PreAllocatedOverlapped)null); }); } } [Fact] public unsafe void AllocateNativeOverlapped_NullAsContext_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, (object)null, new byte[256]); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] public unsafe void AllocateNativeOverlapped_NullAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), (byte[])null); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] public unsafe void AllocateNativeOverlapped_EmptyArrayAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[0]); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] public unsafe void AllocateNativeOverlapped_NonBlittableTypeAsPinData_Throws() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { Assert.Throws<ArgumentException>(() => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new NonBlittableType() { s = "foo" })); } } [Fact] public unsafe void AllocateNativeOverlapped_BlittableTypeAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new BlittableType() { i = 42 }); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] public unsafe void AllocateNativeOverlapped_ObjectArrayAsPinData_DoesNotThrow() { object[] array = new object[] { new BlittableType() { i = 1 }, new byte[5], }; using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] public unsafe void AllocateNativeOverlapped_ObjectArrayWithNonBlittableTypeAsPinData_Throws() { object[] array = new object[] { new NonBlittableType() { s = "foo" }, new byte[5], }; using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { Assert.Throws<ArgumentException>(() => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array)); } } [Fact] public unsafe void AllocateNativeOverlapped_ReturnedNativeOverlapped_AllFieldsZero() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_ReturnedNativeOverlapped_AllFieldsZero() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256])) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } } [Fact] public unsafe void AllocateNativeOverlapped_PossibleReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero() { // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); overlapped->OffsetHigh = 1; overlapped->OffsetLow = 1; handle.FreeNativeOverlapped(overlapped); overlapped = handle.AllocateNativeOverlapped((errorCode, numBytes, overlap) => { }, new object(), new byte[256]); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_ReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero() { // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256]); NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); overlapped->OffsetHigh = 1; overlapped->OffsetLow = 1; handle.FreeNativeOverlapped(overlapped); overlapped = handle.AllocateNativeOverlapped(preAlloc); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] public unsafe void AllocateNativeOverlapped_WhenDisposed_ThrowsObjectDisposedException() { ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle(); handle.Dispose(); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); }); } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_WhenDisposed_ThrowsObjectDisposedException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null); preAlloc.Dispose(); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped(preAlloc); }); } } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_WhenHandleDisposed_ThrowsObjectDisposedException() { ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle(); handle.Dispose(); PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped(preAlloc); }); } [Fact] public unsafe void AllocateNativeOverlapped_PreAllocated_WhenAlreadyAllocated_ThrowsArgumentException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null)) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); Assert.Throws<ArgumentException>(() => { handle.AllocateNativeOverlapped(preAlloc); }); handle.FreeNativeOverlapped(overlapped); } } } }
//--------------------------------------------------------------------- // <copyright file="Solver.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; namespace System.Data.Common.Utils.Boolean { using IfThenElseKey = Triple<Vertex, Vertex, Vertex>; using System.Diagnostics; /// <summary> /// Supports construction of canonical Boolean expressions as Reduced Ordered /// Boolean Decision Diagrams (ROBDD). As a side effect, supports simplification and SAT: /// /// - The canonical form of a valid expression is Solver.One /// - The canonical form of an unsatisfiable expression is Solver.Zero /// - The lack of redundancy in the trees allows us to produce compact representations /// of expressions /// /// Any method taking a Vertex argument requires that the argument is either /// a 'sink' (Solver.One or Solver.Zero) or generated by this Solver instance. /// </summary> internal sealed class Solver { #region Fields readonly Dictionary<IfThenElseKey, Vertex> _computedIfThenElseValues = new Dictionary<IfThenElseKey, Vertex>(); readonly Dictionary<Vertex, Vertex> _knownVertices = new Dictionary<Vertex, Vertex>(VertexValueComparer.Instance); int _variableCount; // a standard Boolean variable has children '1' and '0' internal readonly static Vertex[] BooleanVariableChildren = new Vertex[] { Vertex.One, Vertex.Zero }; #endregion #region Expression factory methods internal int CreateVariable() { return ++_variableCount; } internal Vertex Not(Vertex vertex) { // Not(v) iff. 'if v then 0 else 1' return IfThenElse(vertex, Vertex.Zero, Vertex.One); } internal Vertex And(IEnumerable<Vertex> children) { // assuming input vertices v1, v2, ..., vn: // // v1 // 0|\1 // | v2 // |/0 \1 // | ... // | /0 \1 // | vn // | /0 \1 // FALSE TRUE // // order the children to minimize churn when building tree bottom up return children .OrderByDescending(child => child.Variable) .Aggregate(Vertex.One, (left, right) => IfThenElse(left, right, Vertex.Zero)); } internal Vertex And(Vertex left, Vertex right) { // left AND right iff. if 'left' then 'right' else '0' return IfThenElse(left, right, Vertex.Zero); } internal Vertex Or(IEnumerable<Vertex> children) { // assuming input vertices v1, v2, ..., vn: // // v1 // 1|\0 // | v2 // |/1 \0 // | ... // | /1 \0 // | vn // | /1 \0 // TRUE FALSE // // order the children to minimize churn when building tree bottom up return children .OrderByDescending(child => child.Variable) .Aggregate(Vertex.Zero, (left, right) => IfThenElse(left, Vertex.One, right)); } /// <summary> /// Creates a leaf vertex; all children must be sinks /// </summary> internal Vertex CreateLeafVertex(int variable, Vertex[] children) { Debug.Assert(null != children, "children must be specified"); Debug.Assert(2 <= children.Length, "must be at least 2 children"); Debug.Assert(children.All(child => child != null), "children must not be null"); Debug.Assert(children.All(child => child.IsSink()), "children must be sinks"); Debug.Assert(variable <= _variableCount, "variable out of range"); return GetUniqueVertex(variable, children); } #endregion #region Private helper methods /// <summary> /// Returns a Vertex with the given configuration. If this configuration /// is known, returns the existing vertex. Otherwise, a new /// vertex is created. This ensures the vertex is unique in the context /// of this solver. /// </summary> private Vertex GetUniqueVertex(int variable, Vertex[] children) { AssertVerticesValid(children); Vertex result = new Vertex(variable, children); // see if we know this vertex already Vertex canonicalResult; if (_knownVertices.TryGetValue(result, out canonicalResult)) { return canonicalResult; } // remember the vertex (because it came first, it's canonical) _knownVertices.Add(result, result); return result; } /// <summary> /// Composes the given vertices to produce a new ROBDD. /// </summary> private Vertex IfThenElse(Vertex condition, Vertex then, Vertex @else) { AssertVertexValid(condition); AssertVertexValid(then); AssertVertexValid(@else); // check for terminal conditions in the recursion if (condition.IsOne()) { // if '1' then 'then' else '@else' iff. 'then' return then; } if (condition.IsZero()) { // if '0' then 'then' else '@else' iff. '@else' return @else; } if (then.IsOne() && @else.IsZero()) { // if 'condition' then '1' else '0' iff. condition return condition; } if (then.Equals(@else)) { // if 'condition' then 'x' else 'x' iff. x return then; } Vertex result; IfThenElseKey key = new IfThenElseKey(condition, then, @else); // check if we've already computed this result if (_computedIfThenElseValues.TryGetValue(key, out result)) { return result; } int topVariableDomainCount; int topVariable = DetermineTopVariable(condition, then, @else, out topVariableDomainCount); // Recursively compute the new BDD node // Note that we preserve the 'ordered' invariant since the child nodes // cannot contain references to variables < topVariable, and // the topVariable is eliminated from the children through // the call to EvaluateFor. Vertex[] resultCases = new Vertex[topVariableDomainCount]; bool allResultsEqual = true; for (int i = 0; i < topVariableDomainCount; i++) { resultCases[i] = IfThenElse( EvaluateFor(condition, topVariable, i), EvaluateFor(then, topVariable, i), EvaluateFor(@else, topVariable, i)); if (i > 0 && // first vertex is equivalent to itself allResultsEqual && // we've already found a mismatch !resultCases[i].Equals(resultCases[0])) { allResultsEqual = false; } } // if the results are identical, any may be returned if (allResultsEqual) { return resultCases[0]; } // create new vertex result = GetUniqueVertex(topVariable, resultCases); // remember result so that we don't try to compute this if-then-else pattern again _computedIfThenElseValues.Add(key, result); return result; } /// <summary> /// Given parts of an if-then-else statement, determines the top variable (nearest /// root). Used to determine which variable forms the root of a composed Vertex. /// </summary> private static int DetermineTopVariable(Vertex condition, Vertex then, Vertex @else, out int topVariableDomainCount) { int topVariable; if (condition.Variable < then.Variable) { topVariable = condition.Variable; topVariableDomainCount = condition.Children.Length; } else { topVariable = then.Variable; topVariableDomainCount = then.Children.Length; } if (@else.Variable < topVariable) { topVariable = @else.Variable; topVariableDomainCount = @else.Children.Length; } return topVariable; } /// <summary> /// Returns 'vertex' evaluated for the given value of 'variable'. Requires that /// the variable is less than or equal to vertex.Variable. /// </summary> private static Vertex EvaluateFor(Vertex vertex, int variable, int variableAssigment) { if (variable < vertex.Variable) { // If the variable we're setting is less than the vertex variable, the // the Vertex 'ordered' invariant ensures that the vertex contains no reference // to that variable. Binding the variable is therefore a no-op. return vertex; } Debug.Assert(variable == vertex.Variable, "variable must be less than or equal to vertex.Variable"); // If the 'vertex' is conditioned on the given 'variable', the children // represent the decompositions of the function for various assignments // to that variable. Debug.Assert(variableAssigment < vertex.Children.Length, "variable assignment out of range"); return vertex.Children[variableAssigment]; } /// <summary> /// Checks requirements for vertices. /// </summary> [Conditional("DEBUG")] private void AssertVerticesValid(IEnumerable<Vertex> vertices) { Debug.Assert(null != vertices); foreach (Vertex vertex in vertices) { AssertVertexValid(vertex); } } /// <summary> /// Checks requirements for a vertex argument (must not be null, and must be in scope /// for this solver) /// </summary> [Conditional("DEBUG")] private void AssertVertexValid(Vertex vertex) { Debug.Assert(vertex != null, "vertex must not be null"); // sinks are ok if (!vertex.IsSink()) { // so are vertices created by this solver Vertex comparisonVertex; Debug.Assert(_knownVertices.TryGetValue(vertex, out comparisonVertex) && comparisonVertex.Equals(vertex), "vertex not created by this solver"); } } #endregion /// <summary> /// Supports value comparison of vertices. In general, we use reference comparison /// since the Solver ensures a single instance of each canonical Vertex. The Solver /// needs this comparer to ensure a single instance of each canonical Vertex though... /// </summary> private class VertexValueComparer : IEqualityComparer<Vertex> { private VertexValueComparer() { } internal static readonly VertexValueComparer Instance = new VertexValueComparer(); public bool Equals(Vertex x, Vertex y) { if (x.IsSink()) { // [....] nodes '1' and '0' each have one static instance; use reference return x.Equals(y); } if (x.Variable != y.Variable || x.Children.Length != y.Children.Length) { return false; } for (int i = 0; i < x.Children.Length; i++) { // use reference comparison for the children (they must be // canonical already) if (!x.Children[i].Equals(y.Children[i])) { return false; } } return true; } public int GetHashCode(Vertex vertex) { // [....] nodes '1' and '0' each have one static instance; use reference if (vertex.IsSink()) { return vertex.GetHashCode(); } Debug.Assert(2 <= vertex.Children.Length, "internal vertices must have at least 2 children"); unchecked { return ((vertex.Children[0].GetHashCode() << 5) + 1) + vertex.Children[1].GetHashCode(); } } } } /// <summary> /// Record structure containing three values. /// </summary> struct Triple<T1, T2, T3> : IEquatable<Triple<T1, T2, T3>> where T1 : IEquatable<T1> where T2 : IEquatable<T2> where T3 : IEquatable<T3> { readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; internal Triple(T1 value1, T2 value2, T3 value3) { Debug.Assert(null != (object)value1, "null key element"); Debug.Assert(null != (object)value2, "null key element"); Debug.Assert(null != (object)value3, "null key element"); _value1 = value1; _value2 = value2; _value3 = value3; } public bool Equals(Triple<T1, T2, T3> other) { return _value1.Equals(other._value1) && _value2.Equals(other._value2) && _value3.Equals(other._value3); } public override bool Equals(object obj) { Debug.Fail("used typed Equals"); return base.Equals(obj); } public override int GetHashCode() { return _value1.GetHashCode() ^ _value2.GetHashCode() ^ _value3.GetHashCode(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // XmlTextEncoder // // This class does special handling of text content for XML. For example // it will replace special characters with entities whenever necessary. internal class XmlTextEncoder { // // Fields // // output text writer TextWriter textWriter; // true when writing out the content of attribute value bool inAttribute; // quote char of the attribute (when inAttribute) char quoteChar; // caching of attribute value StringBuilder attrValue; bool cacheAttrValue; // XmlCharType XmlCharType xmlCharType; // // Constructor // internal XmlTextEncoder(TextWriter textWriter) { this.textWriter = textWriter; this.quoteChar = '"'; this.xmlCharType = XmlCharType.Instance; } // // Internal methods and properties // internal char QuoteChar { set { this.quoteChar = value; } } internal void StartAttribute(bool cacheAttrValue) { this.inAttribute = true; this.cacheAttrValue = cacheAttrValue; if (cacheAttrValue) { if (attrValue == null) { attrValue = new StringBuilder(); } else { attrValue.Length = 0; } } } internal void EndAttribute() { if (cacheAttrValue) { attrValue.Length = 0; } this.inAttribute = false; this.cacheAttrValue = false; } internal string AttributeValue { get { if (cacheAttrValue) { return attrValue.ToString(); } else { return String.Empty; } } } internal void WriteSurrogateChar(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, highChar); } textWriter.Write(highChar); textWriter.Write(lowChar); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (cacheAttrValue) { attrValue.Append(array, offset, count); } int endPos = offset + count; int i = offset; char ch = (char)0; for (;;) { int startPos = i; unsafe { while (i < endPos && (xmlCharType.charProperties[ch = array[i]] & XmlCharType.fAttrValue) != 0) { i++; } } if (startPos < i) { textWriter.Write(array, startPos, i - startPos); } if (i == endPos) { break; } switch (ch) { case (char)0x9: textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (inAttribute) { WriteCharEntityImpl(ch); } else { textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("apos"); } else { textWriter.Write('\''); } break; case '"': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("quot"); } else { textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < endPos) { WriteSurrogateChar(array[++i], ch); } else { throw new ArgumentException(SR.Xml_SurrogatePairSplit); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; } } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, highChar); } int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar); if (cacheAttrValue) { attrValue.Append(highChar); attrValue.Append(lowChar); } textWriter.Write("&#x"); textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo)); textWriter.Write(';'); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(string text) { if (text == null) { return; } if (cacheAttrValue) { attrValue.Append(text); } // scan through the string to see if there are any characters to be escaped int len = text.Length; int i = 0; int startPos = 0; char ch = (char)0; for (;;) { unsafe { while (i < len && (xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { i++; } } if (i == len) { // reached the end of the string -> write it whole out textWriter.Write(text); return; } if (inAttribute) { if (ch == 0x9) { i++; continue; } } else { if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'') { i++; continue; } } // some character that needs to be escaped is found: break; } char[] helperBuffer = new char[256]; for (;;) { if (startPos < i) { WriteStringFragment(text, startPos, i - startPos, helperBuffer); } if (i == len) { break; } switch (ch) { case (char)0x9: textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (inAttribute) { WriteCharEntityImpl(ch); } else { textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("apos"); } else { textWriter.Write('\''); } break; case '"': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("quot"); } else { textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { WriteSurrogateChar(text[++i], ch); } else { throw XmlConvertEx.CreateInvalidSurrogatePairException(text[i], ch); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; startPos = i; unsafe { while (i < len && (xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { i++; } } } } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void WriteRawWithSurrogateChecking(string text) { if (text == null) { return; } if (cacheAttrValue) { attrValue.Append(text); } int len = text.Length; int i = 0; char ch = (char)0; for (;;) { unsafe { while (i < len && ((xmlCharType.charProperties[ch = text[i]] & XmlCharType.fCharData) != 0 || ch < 0x20)) { i++; } } if (i == len) { break; } if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { char lowChar = text[i + 1]; if (XmlCharType.IsLowSurrogate(lowChar)) { i += 2; continue; } else { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, ch); } } throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { i++; } } textWriter.Write(text); return; } internal void WriteRaw(string value) { if (cacheAttrValue) { attrValue.Append(value); } textWriter.Write(value); } internal void WriteRaw(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (cacheAttrValue) { attrValue.Append(array, offset, count); } textWriter.Write(array, offset, count); } internal void WriteCharEntity(char ch) { if (XmlCharType.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo); if (cacheAttrValue) { attrValue.Append("&#x"); attrValue.Append(strVal); attrValue.Append(';'); } WriteCharEntityImpl(strVal); } internal void WriteEntityRef(string name) { if (cacheAttrValue) { attrValue.Append('&'); attrValue.Append(name); attrValue.Append(';'); } WriteEntityRefImpl(name); } internal void Flush() { } // // Private implementation methods // // This is a helper method to woraround the fact that TextWriter does not have a Write method // for fragment of a string such as Write( string, offset, count). // The string fragment will be written out by copying into a small helper buffer and then // calling textWriter to write out the buffer. private void WriteStringFragment(string str, int offset, int count, char[] helperBuffer) { int bufferSize = helperBuffer.Length; while (count > 0) { int copyCount = count; if (copyCount > bufferSize) { copyCount = bufferSize; } str.CopyTo(offset, helperBuffer, 0, copyCount); textWriter.Write(helperBuffer, 0, copyCount); offset += copyCount; count -= copyCount; } } private void WriteCharEntityImpl(char ch) { WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo)); } private void WriteCharEntityImpl(string strVal) { textWriter.Write("&#x"); textWriter.Write(strVal); textWriter.Write(';'); } private void WriteEntityRefImpl(string name) { textWriter.Write('&'); textWriter.Write(name); textWriter.Write(';'); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using NodaTime; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Logging; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Instance base class that will provide methods for creating new <see cref="TimeSlice"/> /// </summary> public class TimeSliceFactory { private readonly DateTimeZone _timeZone; // performance: these collections are not always used so keep a reference to an empty // instance to use and avoid unnecessary constructors and allocations private readonly List<UpdateData<ISecurityPrice>> _emptyCustom = new List<UpdateData<ISecurityPrice>>(); private readonly TradeBars _emptyTradeBars = new TradeBars(); private readonly QuoteBars _emptyQuoteBars = new QuoteBars(); private readonly Ticks _emptyTicks = new Ticks(); private readonly Splits _emptySplits = new Splits(); private readonly Dividends _emptyDividends = new Dividends(); private readonly Delistings _emptyDelistings = new Delistings(); private readonly OptionChains _emptyOptionChains = new OptionChains(); private readonly FuturesChains _emptyFuturesChains = new FuturesChains(); private readonly SymbolChangedEvents _emptySymbolChangedEvents = new SymbolChangedEvents(); /// <summary> /// Creates a new instance /// </summary> /// <param name="timeZone">The time zone required for computing algorithm and slice time</param> public TimeSliceFactory(DateTimeZone timeZone) { _timeZone = timeZone; } /// <summary> /// Creates a new empty <see cref="TimeSlice"/> to be used as a time pulse /// </summary> /// <remarks>The objective of this method is to standardize the time pulse creation</remarks> /// <param name="utcDateTime">The UTC frontier date time</param> /// <returns>A new <see cref="TimeSlice"/> time pulse</returns> public TimeSlice CreateTimePulse(DateTime utcDateTime) { // setting all data collections to null, this time slice shouldn't be used // for its data, we want to see fireworks it someone tries return new TimeSlice(utcDateTime, 0, null, null, null, null, null, SecurityChanges.None, null, isTimePulse:true); } /// <summary> /// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data /// </summary> /// <param name="utcDateTime">The UTC frontier date time</param> /// <param name="data">The data in this <see cref="TimeSlice"/></param> /// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param> /// <param name="universeData"></param> /// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns> public TimeSlice Create(DateTime utcDateTime, List<DataFeedPacket> data, SecurityChanges changes, Dictionary<Universe, BaseDataCollection> universeData) { int count = 0; var security = new List<UpdateData<ISecurityPrice>>(data.Count); List<UpdateData<ISecurityPrice>> custom = null; var consolidator = new List<UpdateData<SubscriptionDataConfig>>(data.Count); var allDataForAlgorithm = new List<BaseData>(data.Count); var optionUnderlyingUpdates = new Dictionary<Symbol, BaseData>(); Split split; Dividend dividend; Delisting delisting; SymbolChangedEvent symbolChange; // we need to be able to reference the slice being created in order to define the // evaluation of option price models, so we define a 'future' that can be referenced // in the option price model evaluation delegates for each contract Slice slice = null; var sliceFuture = new Lazy<Slice>(() => slice); var algorithmTime = utcDateTime.ConvertFromUtc(_timeZone); TradeBars tradeBars = null; QuoteBars quoteBars = null; Ticks ticks = null; Splits splits = null; Dividends dividends = null; Delistings delistings = null; OptionChains optionChains = null; FuturesChains futuresChains = null; SymbolChangedEvents symbolChanges = null; UpdateEmptyCollections(algorithmTime); if (universeData.Count > 0) { // count universe data foreach (var kvp in universeData) { count += kvp.Value.Data.Count; } } // ensure we read equity data before option data, so we can set the current underlying price foreach (var packet in data) { // filter out packets for removed subscriptions if (packet.IsSubscriptionRemoved) { continue; } var list = packet.Data; var symbol = packet.Configuration.Symbol; if (list.Count == 0) continue; // keep count of all data points if (list.Count == 1 && list[0] is BaseDataCollection) { var baseDataCollectionCount = ((BaseDataCollection)list[0]).Data.Count; if (baseDataCollectionCount == 0) { continue; } count += baseDataCollectionCount; } else { count += list.Count; } if (!packet.Configuration.IsInternalFeed && packet.Configuration.IsCustomData) { if (custom == null) { custom = new List<UpdateData<ISecurityPrice>>(1); } // This is all the custom data custom.Add(new UpdateData<ISecurityPrice>(packet.Security, packet.Configuration.Type, list, packet.Configuration.IsInternalFeed)); } var securityUpdate = new List<BaseData>(list.Count); var consolidatorUpdate = new List<BaseData>(list.Count); var containsFillForwardData = false; for (var i = 0; i < list.Count; i++) { var baseData = list[i]; if (!packet.Configuration.IsInternalFeed) { // this is all the data that goes into the algorithm allDataForAlgorithm.Add(baseData); } containsFillForwardData |= baseData.IsFillForward; // don't add internal feed data to ticks/bars objects if (baseData.DataType != MarketDataType.Auxiliary) { var tick = baseData as Tick; if (!packet.Configuration.IsInternalFeed) { // populate data dictionaries switch (baseData.DataType) { case MarketDataType.Tick: if (ticks == null) { ticks = new Ticks(algorithmTime); } ticks.Add(baseData.Symbol, (Tick)baseData); break; case MarketDataType.TradeBar: if (tradeBars == null) { tradeBars = new TradeBars(algorithmTime); } var newTradeBar = (TradeBar)baseData; TradeBar existingTradeBar; // if we have an existing bar keep the highest resolution one // e.g Hour and Minute resolution subscriptions for the same symbol // see CustomUniverseWithBenchmarkRegressionAlgorithm if (!tradeBars.TryGetValue(baseData.Symbol, out existingTradeBar) || existingTradeBar.Period > newTradeBar.Period) { tradeBars[baseData.Symbol] = newTradeBar; } break; case MarketDataType.QuoteBar: if (quoteBars == null) { quoteBars = new QuoteBars(algorithmTime); } var newQuoteBar = (QuoteBar)baseData; QuoteBar existingQuoteBar; // if we have an existing bar keep the highest resolution one // e.g Hour and Minute resolution subscriptions for the same symbol // see CustomUniverseWithBenchmarkRegressionAlgorithm if (!quoteBars.TryGetValue(baseData.Symbol, out existingQuoteBar) || existingQuoteBar.Period > newQuoteBar.Period) { quoteBars[baseData.Symbol] = newQuoteBar; } break; case MarketDataType.OptionChain: if (optionChains == null) { optionChains = new OptionChains(algorithmTime); } optionChains[baseData.Symbol] = (OptionChain)baseData; break; case MarketDataType.FuturesChain: if (futuresChains == null) { futuresChains = new FuturesChains(algorithmTime); } futuresChains[baseData.Symbol] = (FuturesChain)baseData; break; } // this is data used to update consolidators // do not add it if it is a Suspicious tick if (tick == null || !tick.Suspicious) { consolidatorUpdate.Add(baseData); } } // special handling of options data to build the option chain if (symbol.SecurityType.IsOption()) { // internal feeds, like open interest, will not create the chain but will update it if it exists // this is because the open interest could arrive at some closed market hours in which there is no other data and we don't // want to generate a chain object in this case if (optionChains == null && !packet.Configuration.IsInternalFeed) { optionChains = new OptionChains(algorithmTime); } if (baseData.DataType == MarketDataType.OptionChain) { optionChains[baseData.Symbol] = (OptionChain)baseData; } else if (optionChains != null && !HandleOptionData(algorithmTime, baseData, optionChains, packet.Security, sliceFuture, optionUnderlyingUpdates)) { continue; } } // special handling of futures data to build the futures chain. Don't push canonical continuous contract if (symbol.SecurityType == SecurityType.Future && !symbol.IsCanonical()) { // internal feeds, like open interest, will not create the chain but will update it if it exists // this is because the open interest could arrive at some closed market hours in which there is no other data and we don't // want to generate a chain object in this case if (futuresChains == null && !packet.Configuration.IsInternalFeed) { futuresChains = new FuturesChains(algorithmTime); } if (baseData.DataType == MarketDataType.FuturesChain) { futuresChains[baseData.Symbol] = (FuturesChain)baseData; } else if (futuresChains != null && !HandleFuturesData(algorithmTime, baseData, futuresChains, packet.Security)) { continue; } } // this is the data used set market prices // do not add it if it is a Suspicious tick if (tick != null && tick.Suspicious) continue; securityUpdate.Add(baseData); // option underlying security update if (!packet.Configuration.IsInternalFeed) { optionUnderlyingUpdates[symbol] = baseData; } } else if (!packet.Configuration.IsInternalFeed) { // include checks for various aux types so we don't have to construct the dictionaries in Slice if ((delisting = baseData as Delisting) != null) { if (delistings == null) { delistings = new Delistings(algorithmTime); } delistings[symbol] = delisting; } else if ((dividend = baseData as Dividend) != null) { if (dividends == null) { dividends = new Dividends(algorithmTime); } dividends[symbol] = dividend; } else if ((split = baseData as Split) != null) { if (splits == null) { splits = new Splits(algorithmTime); } splits[symbol] = split; } else if ((symbolChange = baseData as SymbolChangedEvent) != null) { if (symbolChanges == null) { symbolChanges = new SymbolChangedEvents(algorithmTime); } // symbol changes is keyed by the requested symbol symbolChanges[packet.Configuration.Symbol] = symbolChange; } } } if (securityUpdate.Count > 0) { security.Add(new UpdateData<ISecurityPrice>(packet.Security, packet.Configuration.Type, securityUpdate, packet.Configuration.IsInternalFeed, containsFillForwardData)); } if (consolidatorUpdate.Count > 0) { consolidator.Add(new UpdateData<SubscriptionDataConfig>(packet.Configuration, packet.Configuration.Type, consolidatorUpdate, packet.Configuration.IsInternalFeed, containsFillForwardData)); } } slice = new Slice(algorithmTime, allDataForAlgorithm, tradeBars ?? _emptyTradeBars, quoteBars ?? _emptyQuoteBars, ticks ?? _emptyTicks, optionChains ?? _emptyOptionChains, futuresChains ?? _emptyFuturesChains, splits ?? _emptySplits, dividends ?? _emptyDividends, delistings ?? _emptyDelistings, symbolChanges ?? _emptySymbolChangedEvents, allDataForAlgorithm.Count > 0); return new TimeSlice(utcDateTime, count, slice, data, security, consolidator, custom ?? _emptyCustom, changes, universeData); } private void UpdateEmptyCollections(DateTime algorithmTime) { // just in case _emptyTradeBars.Clear(); _emptyQuoteBars.Clear(); _emptyTicks.Clear(); _emptySplits.Clear(); _emptyDividends.Clear(); _emptyDelistings.Clear(); _emptyOptionChains.Clear(); _emptyFuturesChains.Clear(); _emptySymbolChangedEvents.Clear(); #pragma warning disable 0618 // DataDictionary.Time is deprecated, ignore until removed entirely _emptyTradeBars.Time = _emptyQuoteBars.Time = _emptyTicks.Time = _emptySplits.Time = _emptyDividends.Time = _emptyDelistings.Time = _emptyOptionChains.Time = _emptyFuturesChains.Time = _emptySymbolChangedEvents.Time = algorithmTime; #pragma warning restore 0618 } private bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, ISecurityPrice security, Lazy<Slice> sliceFuture, IReadOnlyDictionary<Symbol, BaseData> optionUnderlyingUpdates) { var symbol = baseData.Symbol; OptionChain chain; var canonical = symbol.Canonical; if (!optionChains.TryGetValue(canonical, out chain)) { chain = new OptionChain(canonical, algorithmTime); optionChains[canonical] = chain; } // set the underlying current data point in the option chain var option = security as IOptionPrice; if (option != null) { if (option.Underlying == null) { Log.Error($"TimeSlice.HandleOptionData(): {algorithmTime}: Option underlying is null"); return false; } BaseData underlyingData; if (!optionUnderlyingUpdates.TryGetValue(option.Underlying.Symbol, out underlyingData)) { underlyingData = option.Underlying.GetLastData(); } if (underlyingData == null) { Log.Error($"TimeSlice.HandleOptionData(): {algorithmTime}: Option underlying GetLastData returned null"); return false; } chain.Underlying = underlyingData; } var universeData = baseData as OptionChainUniverseDataCollection; if (universeData != null) { if (universeData.Underlying != null) { foreach (var addedContract in chain.Contracts) { addedContract.Value.UnderlyingLastPrice = chain.Underlying.Price; } } foreach (var contractSymbol in universeData.FilteredContracts) { chain.FilteredContracts.Add(contractSymbol); } return false; } OptionContract contract; if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract)) { contract = OptionContract.Create(baseData, security, chain.Underlying.Price); chain.Contracts[baseData.Symbol] = contract; if (option != null) { contract.SetOptionPriceModel(() => option.EvaluatePriceModel(sliceFuture.Value, contract)); } } // populate ticks and tradebars dictionaries with no aux data switch (baseData.DataType) { case MarketDataType.Tick: var tick = (Tick)baseData; chain.Ticks.Add(tick.Symbol, tick); UpdateContract(contract, tick); break; case MarketDataType.TradeBar: var tradeBar = (TradeBar)baseData; chain.TradeBars[symbol] = tradeBar; UpdateContract(contract, tradeBar); break; case MarketDataType.QuoteBar: var quote = (QuoteBar)baseData; chain.QuoteBars[symbol] = quote; UpdateContract(contract, quote); break; case MarketDataType.Base: chain.AddAuxData(baseData); break; } return true; } private bool HandleFuturesData(DateTime algorithmTime, BaseData baseData, FuturesChains futuresChains, ISecurityPrice security) { var symbol = baseData.Symbol; FuturesChain chain; var canonical = symbol.Canonical; if (!futuresChains.TryGetValue(canonical, out chain)) { chain = new FuturesChain(canonical, algorithmTime); futuresChains[canonical] = chain; } var universeData = baseData as FuturesChainUniverseDataCollection; if (universeData != null) { foreach (var contractSymbol in universeData.FilteredContracts) { chain.FilteredContracts.Add(contractSymbol); } return false; } FuturesContract contract; if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract)) { var underlyingSymbol = baseData.Symbol.Underlying; contract = new FuturesContract(baseData.Symbol, underlyingSymbol) { Time = baseData.EndTime, LastPrice = security.Close, Volume = (long)security.Volume, BidPrice = security.BidPrice, BidSize = (long)security.BidSize, AskPrice = security.AskPrice, AskSize = (long)security.AskSize, OpenInterest = security.OpenInterest }; chain.Contracts[baseData.Symbol] = contract; } // populate ticks and tradebars dictionaries with no aux data switch (baseData.DataType) { case MarketDataType.Tick: var tick = (Tick)baseData; chain.Ticks.Add(tick.Symbol, tick); UpdateContract(contract, tick); break; case MarketDataType.TradeBar: var tradeBar = (TradeBar)baseData; chain.TradeBars[symbol] = tradeBar; UpdateContract(contract, tradeBar); break; case MarketDataType.QuoteBar: var quote = (QuoteBar)baseData; chain.QuoteBars[symbol] = quote; UpdateContract(contract, quote); break; case MarketDataType.Base: chain.AddAuxData(baseData); break; } return true; } private static void UpdateContract(OptionContract contract, QuoteBar quote) { if (quote.Ask != null && quote.Ask.Close != 0m) { contract.AskPrice = quote.Ask.Close; contract.AskSize = (long)quote.LastAskSize; } if (quote.Bid != null && quote.Bid.Close != 0m) { contract.BidPrice = quote.Bid.Close; contract.BidSize = (long)quote.LastBidSize; } } private static void UpdateContract(OptionContract contract, Tick tick) { if (tick.TickType == TickType.Trade) { contract.LastPrice = tick.Price; } else if (tick.TickType == TickType.Quote) { if (tick.AskPrice != 0m) { contract.AskPrice = tick.AskPrice; contract.AskSize = (long)tick.AskSize; } if (tick.BidPrice != 0m) { contract.BidPrice = tick.BidPrice; contract.BidSize = (long)tick.BidSize; } } else if (tick.TickType == TickType.OpenInterest) { if (tick.Value != 0m) { contract.OpenInterest = tick.Value; } } } private static void UpdateContract(OptionContract contract, TradeBar tradeBar) { if (tradeBar.Close == 0m) return; contract.LastPrice = tradeBar.Close; contract.Volume = (long)tradeBar.Volume; } private static void UpdateContract(FuturesContract contract, QuoteBar quote) { if (quote.Ask != null && quote.Ask.Close != 0m) { contract.AskPrice = quote.Ask.Close; contract.AskSize = (long)quote.LastAskSize; } if (quote.Bid != null && quote.Bid.Close != 0m) { contract.BidPrice = quote.Bid.Close; contract.BidSize = (long)quote.LastBidSize; } } private static void UpdateContract(FuturesContract contract, Tick tick) { if (tick.TickType == TickType.Trade) { contract.LastPrice = tick.Price; } else if (tick.TickType == TickType.Quote) { if (tick.AskPrice != 0m) { contract.AskPrice = tick.AskPrice; contract.AskSize = (long)tick.AskSize; } if (tick.BidPrice != 0m) { contract.BidPrice = tick.BidPrice; contract.BidSize = (long)tick.BidSize; } } else if (tick.TickType == TickType.OpenInterest) { if (tick.Value != 0m) { contract.OpenInterest = tick.Value; } } } private static void UpdateContract(FuturesContract contract, TradeBar tradeBar) { if (tradeBar.Close == 0m) return; contract.LastPrice = tradeBar.Close; contract.Volume = (long)tradeBar.Volume; } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Speech.Tts.cs // // 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. #pragma warning disable 1717 namespace Android.Speech.Tts { /// <summary> /// <para>Synthesizes speech from text for immediate playback or to create a sound file. </para><para>A TextToSpeech instance can only be used to synthesize text once it has completed its initialization. Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization.<br></br> When you are done using the TextToSpeech instance, call the shutdown() method to release the native resources used by the TextToSpeech engine. </para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech", AccessFlags = 33)] public partial class TextToSpeech /* scope: __dot42__ */ { /// <summary> /// <para>Denotes a successful operation. </para> /// </summary> /// <java-name> /// SUCCESS /// </java-name> [Dot42.DexImport("SUCCESS", "I", AccessFlags = 25)] public const int SUCCESS = 0; /// <summary> /// <para>Denotes a generic operation failure. </para> /// </summary> /// <java-name> /// ERROR /// </java-name> [Dot42.DexImport("ERROR", "I", AccessFlags = 25)] public const int ERROR = -1; /// <summary> /// <para>Queue mode where all entries in the playback queue (media to be played and text to be synthesized) are dropped and replaced by the new entry. Queues are flushed with respect to a given calling app. Entries in the queue from other callees are not discarded. </para> /// </summary> /// <java-name> /// QUEUE_FLUSH /// </java-name> [Dot42.DexImport("QUEUE_FLUSH", "I", AccessFlags = 25)] public const int QUEUE_FLUSH = 0; /// <summary> /// <para>Queue mode where the new entry is added at the end of the playback queue. </para> /// </summary> /// <java-name> /// QUEUE_ADD /// </java-name> [Dot42.DexImport("QUEUE_ADD", "I", AccessFlags = 25)] public const int QUEUE_ADD = 1; /// <summary> /// <para>Denotes the language is available exactly as specified by the locale. </para> /// </summary> /// <java-name> /// LANG_COUNTRY_VAR_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_COUNTRY_VAR_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_COUNTRY_VAR_AVAILABLE = 2; /// <summary> /// <para>Denotes the language is available for the language and country specified by the locale, but not the variant. </para> /// </summary> /// <java-name> /// LANG_COUNTRY_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_COUNTRY_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_COUNTRY_AVAILABLE = 1; /// <summary> /// <para>Denotes the language is available for the language by the locale, but not the country and variant. </para> /// </summary> /// <java-name> /// LANG_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_AVAILABLE = 0; /// <summary> /// <para>Denotes the language data is missing. </para> /// </summary> /// <java-name> /// LANG_MISSING_DATA /// </java-name> [Dot42.DexImport("LANG_MISSING_DATA", "I", AccessFlags = 25)] public const int LANG_MISSING_DATA = -1; /// <summary> /// <para>Denotes the language is not supported. </para> /// </summary> /// <java-name> /// LANG_NOT_SUPPORTED /// </java-name> [Dot42.DexImport("LANG_NOT_SUPPORTED", "I", AccessFlags = 25)] public const int LANG_NOT_SUPPORTED = -2; /// <summary> /// <para>Broadcast Action: The TextToSpeech synthesizer has completed processing of all the text in the speech queue.</para><para>Note that this notifies callers when the <b>engine</b> has finished has processing text data. Audio playback might not have completed (or even started) at this point. If you wish to be notified when this happens, see OnUtteranceCompletedListener. </para> /// </summary> /// <java-name> /// ACTION_TTS_QUEUE_PROCESSING_COMPLETED /// </java-name> [Dot42.DexImport("ACTION_TTS_QUEUE_PROCESSING_COMPLETED", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_TTS_QUEUE_PROCESSING_COMPLETED = "android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED"; /// <summary> /// <para>The constructor for the TextToSpeech class, using the default TTS engine. This will also initialize the associated TextToSpeech engine if it isn't already running.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V", AccessFlags = 1)] public TextToSpeech(global::Android.Content.Context context, global::Android.Speech.Tts.TextToSpeech.IOnInitListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Releases the resources used by the TextToSpeech engine. It is good practice for instance to call this method in the onDestroy() method of an Activity so the TextToSpeech engine can be cleanly stopped. </para> /// </summary> /// <java-name> /// shutdown /// </java-name> [Dot42.DexImport("shutdown", "()V", AccessFlags = 1)] public virtual void Shutdown() /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds a mapping between a string of text and a sound resource in a package. After a call to this method, subsequent calls to speak(String, int, HashMap) will play the specified sound resource if it is available, or synthesize the text it is missing.</para><para><code>&lt;manifest xmlns:android="..." package="<b>com.google.marvin.compass</b>"&gt;</code> </para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addSpeech /// </java-name> [Dot42.DexImport("addSpeech", "(Ljava/lang/String;Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int AddSpeech(string text, string packagename, int resourceId) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound file. Using this, it is possible to add custom pronounciations for a string of text. After a call to this method, subsequent calls to speak(String, int, HashMap) will play the specified sound resource if it is available, or synthesize the text it is missing.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addSpeech /// </java-name> [Dot42.DexImport("addSpeech", "(Ljava/lang/String;Ljava/lang/String;)I", AccessFlags = 1)] public virtual int AddSpeech(string text, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound resource in a package. Use this to add custom earcons.</para><para><para>#playEarcon(String, int, HashMap)</para><code>&lt;manifest xmlns:android="..." package="<b>com.google.marvin.compass</b>"&gt;</code> </para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addEarcon /// </java-name> [Dot42.DexImport("addEarcon", "(Ljava/lang/String;Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int AddEarcon(string earcon, string packagename, int resourceId) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound file. Use this to add custom earcons.</para><para><para>#playEarcon(String, int, HashMap)</para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addEarcon /// </java-name> [Dot42.DexImport("addEarcon", "(Ljava/lang/String;Ljava/lang/String;)I", AccessFlags = 1)] public virtual int AddEarcon(string earcon, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Speaks the string using the specified queuing strategy and speech parameters. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the speak operation. </para> /// </returns> /// <java-name> /// speak /// </java-name> [Dot42.DexImport("speak", "(Ljava/lang/String;ILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;ILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int Speak(string text, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Plays the earcon using the specified queueing mode and parameters. The earcon must already have been added with addEarcon(String, String) or addEarcon(String, String, int). This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the playEarcon operation. </para> /// </returns> /// <java-name> /// playEarcon /// </java-name> [Dot42.DexImport("playEarcon", "(Ljava/lang/String;ILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;ILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int PlayEarcon(string earcon, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Plays silence for the specified amount of time using the specified queue mode. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the playSilence operation. </para> /// </returns> /// <java-name> /// playSilence /// </java-name> [Dot42.DexImport("playSilence", "(JILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(JILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int PlaySilence(long durationInMs, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Checks whether the TTS engine is busy speaking. Note that a speech item is considered complete once it's audio data has been sent to the audio mixer, or written to a file. There might be a finite lag between this point, and when the audio hardware completes playback.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if the TTS engine is speaking. </para> /// </returns> /// <java-name> /// isSpeaking /// </java-name> [Dot42.DexImport("isSpeaking", "()Z", AccessFlags = 1)] public virtual bool IsSpeaking() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Interrupts the current utterance (whether played or rendered to file) and discards other utterances in the queue.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// stop /// </java-name> [Dot42.DexImport("stop", "()I", AccessFlags = 1)] public virtual int Stop() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the speech rate.</para><para>This has no effect on any pre-recorded speech.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// setSpeechRate /// </java-name> [Dot42.DexImport("setSpeechRate", "(F)I", AccessFlags = 1)] public virtual int SetSpeechRate(float speechRate) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the speech pitch for the TextToSpeech engine.</para><para>This has no effect on any pre-recorded speech.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// setPitch /// </java-name> [Dot42.DexImport("setPitch", "(F)I", AccessFlags = 1)] public virtual int SetPitch(float pitch) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the text-to-speech language. The TTS engine will try to use the closest match to the specified language as represented by the Locale, but there is no guarantee that the exact same Locale will be used. Use isLanguageAvailable(Locale) to check the level of support before choosing the language to use for the next utterances.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating the support status for the locale. See LANG_AVAILABLE, LANG_COUNTRY_AVAILABLE, LANG_COUNTRY_VAR_AVAILABLE, LANG_MISSING_DATA and LANG_NOT_SUPPORTED. </para> /// </returns> /// <java-name> /// setLanguage /// </java-name> [Dot42.DexImport("setLanguage", "(Ljava/util/Locale;)I", AccessFlags = 1)] public virtual int SetLanguage(global::Java.Util.Locale loc) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns a Locale instance describing the language currently being used for synthesis requests sent to the TextToSpeech engine.</para><para>In Android 4.2 and before (API &lt;= 17) this function returns the language that is currently being used by the TTS engine. That is the last language set by this or any other client by a TextToSpeech#setLanguage call to the same engine.</para><para>In Android versions after 4.2 this function returns the language that is currently being used for the synthesis requests sent from this client. That is the last language set by a TextToSpeech#setLanguage call on this instance.</para><para></para> /// </summary> /// <returns> /// <para>language, country (if any) and variant (if any) used by the client stored in a Locale instance, or <c> null </c> on error. </para> /// </returns> /// <java-name> /// getLanguage /// </java-name> [Dot42.DexImport("getLanguage", "()Ljava/util/Locale;", AccessFlags = 1)] public virtual global::Java.Util.Locale GetLanguage() /* MethodBuilder.Create */ { return default(global::Java.Util.Locale); } /// <summary> /// <para>Checks if the specified language as represented by the Locale is available and supported.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating the support status for the locale. See LANG_AVAILABLE, LANG_COUNTRY_AVAILABLE, LANG_COUNTRY_VAR_AVAILABLE, LANG_MISSING_DATA and LANG_NOT_SUPPORTED. </para> /// </returns> /// <java-name> /// isLanguageAvailable /// </java-name> [Dot42.DexImport("isLanguageAvailable", "(Ljava/util/Locale;)I", AccessFlags = 1)] public virtual int IsLanguageAvailable(global::Java.Util.Locale loc) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Synthesizes the given text to a file using the specified parameters. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the synthesizeToFile operation. </para> /// </returns> /// <java-name> /// synthesizeToFile /// </java-name> [Dot42.DexImport("synthesizeToFile", "(Ljava/lang/String;Ljava/util/HashMap;Ljava/lang/String;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;Ljava" + "/lang/String;)I")] public virtual int SynthesizeToFile(string text, global::Java.Util.HashMap<string, string> @params, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the listener that will be notified when synthesis of an utterance completes.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use setOnUtteranceProgressListener(UtteranceProgressListener) instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS.</para> /// </returns> /// <java-name> /// setOnUtteranceCompletedListener /// </java-name> [Dot42.DexImport("setOnUtteranceCompletedListener", "(Landroid/speech/tts/TextToSpeech$OnUtteranceCompletedListener;)I", AccessFlags = 1)] public virtual int SetOnUtteranceCompletedListener(global::Android.Speech.Tts.TextToSpeech.IOnUtteranceCompletedListener listener) /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal TextToSpeech() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns a Locale instance describing the language currently being used for synthesis requests sent to the TextToSpeech engine.</para><para>In Android 4.2 and before (API &lt;= 17) this function returns the language that is currently being used by the TTS engine. That is the last language set by this or any other client by a TextToSpeech#setLanguage call to the same engine.</para><para>In Android versions after 4.2 this function returns the language that is currently being used for the synthesis requests sent from this client. That is the last language set by a TextToSpeech#setLanguage call on this instance.</para><para></para> /// </summary> /// <returns> /// <para>language, country (if any) and variant (if any) used by the client stored in a Locale instance, or <c> null </c> on error. </para> /// </returns> /// <java-name> /// getLanguage /// </java-name> public global::Java.Util.Locale Language { [Dot42.DexImport("getLanguage", "()Ljava/util/Locale;", AccessFlags = 1)] get{ return GetLanguage(); } } /// <summary> /// <para>Constants and parameter names for controlling text-to-speech. These include:</para><para><ul><li><para>Intents to ask engine to install data or check its data and extras for a TTS engine's check data activity. </para></li><li><para>Keys for the parameters passed with speak commands, e.g. Engine#KEY_PARAM_UTTERANCE_ID, Engine#KEY_PARAM_STREAM. </para></li><li><para>A list of feature strings that engines might support, e.g Engine#KEY_FEATURE_NETWORK_SYNTHESIS). These values may be passed in to TextToSpeech#speak and TextToSpeech#synthesizeToFile to modify engine behaviour. The engine can be queried for the set of features it supports through TextToSpeech#getFeatures(java.util.Locale). </para></li></ul></para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$Engine /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$Engine", AccessFlags = 1)] public partial class Engine /* scope: __dot42__ */ { /// <summary> /// <para>Default audio stream used when playing synthesized speech. </para> /// </summary> /// <java-name> /// DEFAULT_STREAM /// </java-name> [Dot42.DexImport("DEFAULT_STREAM", "I", AccessFlags = 25)] public const int DEFAULT_STREAM = 3; /// <summary> /// <para>Indicates success when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent. </para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_PASS /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_PASS", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_PASS = 1; /// <summary> /// <para>Indicates failure when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent. </para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_FAIL /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_FAIL", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_FAIL = 0; /// <summary> /// <para>Indicates erroneous data when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_BAD_DATA /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_BAD_DATA", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_BAD_DATA = -1; /// <summary> /// <para>Indicates missing resources when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_MISSING_DATA /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_MISSING_DATA", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_MISSING_DATA = -2; /// <summary> /// <para>Indicates missing storage volume when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_MISSING_VOLUME /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_MISSING_VOLUME", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_MISSING_VOLUME = -3; /// <summary> /// <para>Activity Action: Triggers the platform TextToSpeech engine to start the activity that installs the resource files on the device that are required for TTS to be operational. Since the installation of the data can be interrupted or declined by the user, the application shouldn't expect successful installation upon return from that intent, and if need be, should check installation status with ACTION_CHECK_TTS_DATA. </para> /// </summary> /// <java-name> /// ACTION_INSTALL_TTS_DATA /// </java-name> [Dot42.DexImport("ACTION_INSTALL_TTS_DATA", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_INSTALL_TTS_DATA = "android.speech.tts.engine.INSTALL_TTS_DATA"; /// <summary> /// <para>Broadcast Action: broadcast to signal the change in the list of available languages or/and their features. </para> /// </summary> /// <java-name> /// ACTION_TTS_DATA_INSTALLED /// </java-name> [Dot42.DexImport("ACTION_TTS_DATA_INSTALLED", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_TTS_DATA_INSTALLED = "android.speech.tts.engine.TTS_DATA_INSTALLED"; /// <summary> /// <para>Activity Action: Starts the activity from the platform TextToSpeech engine to verify the proper installation and availability of the resource files on the system. Upon completion, the activity will return one of the following codes: CHECK_VOICE_DATA_PASS, CHECK_VOICE_DATA_FAIL, </para><para>Moreover, the data received in the activity result will contain the following fields: <ul><li><para>EXTRA_AVAILABLE_VOICES which contains an ArrayList&lt;String&gt; of all the available voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para></li><li><para>EXTRA_UNAVAILABLE_VOICES which contains an ArrayList&lt;String&gt; of all the unavailable voices (ones that user can install). The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para></li></ul></para> /// </summary> /// <java-name> /// ACTION_CHECK_TTS_DATA /// </java-name> [Dot42.DexImport("ACTION_CHECK_TTS_DATA", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_CHECK_TTS_DATA = "android.speech.tts.engine.CHECK_TTS_DATA"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the path to its resources.</para><para>It may be used by language packages to find out where to put their data.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_ROOT_DIRECTORY /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_ROOT_DIRECTORY", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the file names of its resources under the resource path.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_FILES /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_FILES", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_FILES = "dataFiles"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the locale associated with each resource file.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_FILES_INFO /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_FILES_INFO", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo"; /// <summary> /// <para>Extra information received with the ACTION_TTS_DATA_INSTALLED intent result. It indicates whether the data files for the synthesis engine were successfully installed. The installation was initiated with the ACTION_INSTALL_TTS_DATA intent. The possible values for this extra are TextToSpeech#SUCCESS and TextToSpeech#ERROR.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>No longer in use. If client ise interested in information about what changed, is should send ACTION_CHECK_TTS_DATA intent to discover available voices. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_TTS_DATA_INSTALLED /// </java-name> [Dot42.DexImport("EXTRA_TTS_DATA_INSTALLED", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_TTS_DATA_INSTALLED = "dataInstalled"; /// <summary> /// <para>Parameter key to specify the audio stream type to be used when speaking text or playing back a file. The value should be one of the STREAM_ constants defined in AudioManager.</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_STREAM /// </java-name> [Dot42.DexImport("KEY_PARAM_STREAM", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_STREAM = "streamType"; /// <summary> /// <para>Parameter key to identify an utterance in the TextToSpeech.OnUtteranceCompletedListener after text has been spoken, a file has been played back or a silence duration has elapsed.</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::synthesizeToFile(String, HashMap, String) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_UTTERANCE_ID /// </java-name> [Dot42.DexImport("KEY_PARAM_UTTERANCE_ID", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_UTTERANCE_ID = "utteranceId"; /// <java-name> /// this$0 /// </java-name> [Dot42.DexImport("this$0", "Landroid/speech/tts/TextToSpeech;", AccessFlags = 4112)] internal readonly global::Android.Speech.Tts.TextToSpeech This_0; [Dot42.DexImport("<init>", "(Landroid/speech/tts/TextToSpeech;)V", AccessFlags = 1)] public Engine(global::Android.Speech.Tts.TextToSpeech textToSpeech) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Engine() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Listener that will be called when the TTS service has completed synthesizing an utterance. This is only called if the utterance has an utterance ID (see TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID).</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use UtteranceProgressListener instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$OnUtteranceCompletedListener /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$OnUtteranceCompletedListener", AccessFlags = 1545)] public partial interface IOnUtteranceCompletedListener /* scope: __dot42__ */ { /// <summary> /// <para>Called when an utterance has been synthesized.</para><para></para> /// </summary> /// <java-name> /// onUtteranceCompleted /// </java-name> [Dot42.DexImport("onUtteranceCompleted", "(Ljava/lang/String;)V", AccessFlags = 1025)] void OnUtteranceCompleted(string utteranceId) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Interface definition of a callback to be invoked indicating the completion of the TextToSpeech engine initialization. </para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$OnInitListener /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$OnInitListener", AccessFlags = 1545)] public partial interface IOnInitListener /* scope: __dot42__ */ { /// <summary> /// <para>Called to signal the completion of the TextToSpeech engine initialization.</para><para></para> /// </summary> /// <java-name> /// onInit /// </java-name> [Dot42.DexImport("onInit", "(I)V", AccessFlags = 1025)] void OnInit(int status) /* MethodBuilder.Create */ ; } } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.SqlSyntax; namespace Umbraco.Core.Persistence.Migrations.Initial { /// <summary> /// Represents the initial database schema creation by running CreateTable for all DTOs against the db. /// </summary> public class DatabaseSchemaCreation { /// <summary> /// Constructor /// </summary> /// <param name="database"></param> /// <param name="logger"></param> /// <param name="sqlSyntaxProvider"></param> public DatabaseSchemaCreation(Database database, ILogger logger, ISqlSyntaxProvider sqlSyntaxProvider) { _database = database; _logger = logger; _sqlSyntaxProvider = sqlSyntaxProvider; _schemaHelper = new DatabaseSchemaHelper(database, logger, sqlSyntaxProvider); } #region Private Members private readonly DatabaseSchemaHelper _schemaHelper; private readonly Database _database; private readonly ILogger _logger; private readonly ISqlSyntaxProvider _sqlSyntaxProvider; private static readonly Dictionary<int, Type> OrderedTables = new Dictionary<int, Type> { {0, typeof (NodeDto)}, {1, typeof (ContentTypeDto)}, {2, typeof (TemplateDto)}, {3, typeof (ContentDto)}, {4, typeof (ContentVersionDto)}, {5, typeof (DocumentDto)}, {6, typeof (MediaDto)}, {7, typeof (ContentTypeTemplateDto)}, {8, typeof (DataTypeDto)}, {9, typeof (DataTypePreValueDto)}, {10, typeof (DictionaryDto)}, {11, typeof (LanguageDto)}, {12, typeof (LanguageTextDto)}, {13, typeof (DomainDto)}, {14, typeof (LogDto)}, {15, typeof (MacroDto)}, {16, typeof (MacroPropertyDto)}, {17, typeof (MemberTypeDto)}, {18, typeof (MemberDto)}, {19, typeof (Member2MemberGroupDto)}, {20, typeof (ContentXmlDto)}, {21, typeof (PreviewXmlDto)}, {22, typeof (PropertyTypeGroupDto)}, {23, typeof (PropertyTypeDto)}, {24, typeof (PropertyDataDto)}, {25, typeof (RelationTypeDto)}, {26, typeof (RelationDto)}, {28, typeof (TagDto)}, {29, typeof (TagRelationshipDto)}, // Removed in 7.6 {31, typeof (UserTypeDto)}, {32, typeof (UserDto)}, {33, typeof (TaskTypeDto)}, {34, typeof (TaskDto)}, {35, typeof (ContentType2ContentTypeDto)}, {36, typeof (ContentTypeAllowedContentTypeDto)}, // Removed in 7.6 {37, typeof (User2AppDto)}, {38, typeof (User2NodeNotifyDto)}, // Removed in 7.6 {39, typeof (User2NodePermissionDto)}, {40, typeof (ServerRegistrationDto)}, {41, typeof (AccessDto)}, {42, typeof (AccessRuleDto)}, {43, typeof (CacheInstructionDto)}, {44, typeof (ExternalLoginDto)}, {45, typeof (MigrationDto)}, //46, removed: UmbracoDeployChecksumDto //47, removed: UmbracoDeployDependencyDto {48, typeof (RedirectUrlDto) }, {49, typeof (LockDto) }, {50, typeof (UserGroupDto) }, {51, typeof (User2UserGroupDto) }, {52, typeof (UserGroup2NodePermissionDto) }, {53, typeof (UserGroup2AppDto) }, {54, typeof (UserStartNodeDto) }, {55, typeof (UserLoginDto)}, {56, typeof (ConsentDto)}, {57, typeof (AuditEntryDto)} }; #endregion /// <summary> /// Drops all Umbraco tables in the db /// </summary> internal void UninstallDatabaseSchema() { _logger.Info<DatabaseSchemaCreation>("Start UninstallDatabaseSchema"); foreach (var item in OrderedTables.OrderByDescending(x => x.Key)) { var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>(); string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value; _logger.Info<DatabaseSchemaCreation>("Uninstall" + tableName); try { if (_schemaHelper.TableExist(tableName)) { _schemaHelper.DropTable(tableName); } } catch (Exception ex) { //swallow this for now, not sure how best to handle this with diff databases... though this is internal // and only used for unit tests. If this fails its because the table doesn't exist... generally! _logger.Error<DatabaseSchemaCreation>("Could not drop table " + tableName, ex); } } } /// <summary> /// Initialize the database by creating the umbraco db schema /// </summary> public void InitializeDatabaseSchema() { var e = new DatabaseCreationEventArgs(); FireBeforeCreation(e); if (!e.Cancel) { foreach (var item in OrderedTables.OrderBy(x => x.Key)) { _schemaHelper.CreateTable(false, item.Value); } } FireAfterCreation(e); } /// <summary> /// Validates the schema of the current database /// </summary> public DatabaseSchemaResult ValidateSchema() { var result = new DatabaseSchemaResult(); //get the db index defs result.DbIndexDefinitions = _sqlSyntaxProvider.GetDefinedIndexes(_database) .Select(x => new DbIndexDefinition(x)).ToArray(); foreach (var item in OrderedTables.OrderBy(x => x.Key)) { var tableDefinition = DefinitionFactory.GetTableDefinition(_sqlSyntaxProvider, item.Value); result.TableDefinitions.Add(tableDefinition); } ValidateDbTables(result); ValidateDbColumns(result); ValidateDbIndexes(result); ValidateDbConstraints(result); return result; } /// <summary> /// This validates the Primary/Foreign keys in the database /// </summary> /// <param name="result"></param> /// <remarks> /// This does not validate any database constraints that are not PKs or FKs because Umbraco does not create a database with non PK/FK contraints. /// Any unique "constraints" in the database are done with unique indexes. /// </remarks> private void ValidateDbConstraints(DatabaseSchemaResult result) { //MySql doesn't conform to the "normal" naming of constraints, so there is currently no point in doing these checks. //TODO: At a later point we do other checks for MySql, but ideally it should be necessary to do special checks for different providers. // ALso note that to get the constraints for MySql we have to open a connection which we currently have not. if (_sqlSyntaxProvider is MySqlSyntaxProvider) return; //Check constraints in configured database against constraints in schema var constraintsInDatabase = _sqlSyntaxProvider.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList(); var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")).Select(x => x.Item3).ToList(); var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")).Select(x => x.Item3).ToList(); var unknownConstraintsInDatabase = constraintsInDatabase.Where( x => x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false && x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList(); var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList(); var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName)) .Where(x => x.IsNullOrWhiteSpace() == false).ToList(); //Add valid and invalid foreign key differences to the result object // We'll need to do invariant contains with case insensitivity because foreign key, primary key, and even index naming w/ MySQL is not standardized // In theory you could have: FK_ or fk_ ...or really any standard that your development department (or developer) chooses to use. foreach (var unknown in unknownConstraintsInDatabase) { if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown)) { result.ValidConstraints.Add(unknown); } else { result.Errors.Add(new Tuple<string, string>("Unknown", unknown)); } } //Foreign keys: var validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var foreignKey in validForeignKeyDifferences) { result.ValidConstraints.Add(foreignKey); } var invalidForeignKeyDifferences = foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var foreignKey in invalidForeignKeyDifferences) { result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey)); } //Primary keys: //Add valid and invalid primary key differences to the result object var validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var primaryKey in validPrimaryKeyDifferences) { result.ValidConstraints.Add(primaryKey); } var invalidPrimaryKeyDifferences = primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var primaryKey in invalidPrimaryKeyDifferences) { result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey)); } } private void ValidateDbColumns(DatabaseSchemaResult result) { //Check columns in configured database against columns in schema var columnsInDatabase = _sqlSyntaxProvider.GetColumnsInSchema(_database); var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList(); var columnsPerTableInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList(); //Add valid and invalid column differences to the result object var validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var column in validColumnDifferences) { result.ValidColumns.Add(column); } var invalidColumnDifferences = columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var column in invalidColumnDifferences) { result.Errors.Add(new Tuple<string, string>("Column", column)); } } private void ValidateDbTables(DatabaseSchemaResult result) { //Check tables in configured database against tables in schema var tablesInDatabase = _sqlSyntaxProvider.GetTablesInSchema(_database).ToList(); var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList(); //Add valid and invalid table differences to the result object var validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var tableName in validTableDifferences) { result.ValidTables.Add(tableName); } var invalidTableDifferences = tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var tableName in invalidTableDifferences) { result.Errors.Add(new Tuple<string, string>("Table", tableName)); } } private void ValidateDbIndexes(DatabaseSchemaResult result) { //These are just column indexes NOT constraints or Keys //var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList(); var colIndexesInDatabase = result.DbIndexDefinitions.Select(x => x.IndexName).ToList(); var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList(); //Add valid and invalid index differences to the result object var validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var index in validColIndexDifferences) { result.ValidIndexes.Add(index); } var invalidColIndexDifferences = colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var index in invalidColIndexDifferences) { result.Errors.Add(new Tuple<string, string>("Index", index)); } } #region Events /// <summary> /// The save event handler /// </summary> internal delegate void DatabaseEventHandler(DatabaseCreationEventArgs e); /// <summary> /// Occurs when [before save]. /// </summary> internal static event DatabaseEventHandler BeforeCreation; /// <summary> /// Raises the <see cref="BeforeCreation"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> internal virtual void FireBeforeCreation(DatabaseCreationEventArgs e) { if (BeforeCreation != null) { BeforeCreation(e); } } /// <summary> /// Occurs when [after save]. /// </summary> internal static event DatabaseEventHandler AfterCreation; /// <summary> /// Raises the <see cref="AfterCreation"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> internal virtual void FireAfterCreation(DatabaseCreationEventArgs e) { if (AfterCreation != null) { AfterCreation(e); } } #endregion } }