context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Diagnostics; using System.Linq; using Ripple.Core.Binary; using Ripple.Core.Hashing; using Ripple.Core.Types; namespace Ripple.Core.ShaMapTree { public class ShaMapInner : ShaMapNode { public int Depth; internal int SlotBits; internal int Version; internal bool DoCoW; protected internal ShaMapNode[] Branches = new ShaMapNode[16]; public ShaMapInner(int depth) : this(false, depth, 0) { } public ShaMapInner(bool isCopy, int depth, int version) { DoCoW = isCopy; Depth = depth; Version = version; } protected internal ShaMapInner Copy(int version) { var copy = MakeInnerOfSameClass(Depth); Array.Copy(Branches, 0, copy.Branches, 0, Branches.Length); copy.SlotBits = SlotBits; copy.CachedHash = CachedHash; copy.Version = version; DoCoW = true; return copy; } protected internal virtual ShaMapInner MakeInnerOfSameClass(int depth) { return new ShaMapInner(true, depth, Version); } protected internal ShaMapInner MakeInnerChild() { var childDepth = Depth + 1; if (childDepth >= 64) { throw new InvalidOperationException(); } return new ShaMapInner(DoCoW, childDepth, Version); } // Descend into the tree, find the leaf matching this index // and if the tree has it. protected internal void SetLeaf(ShaMapLeaf leaf) { if (leaf.Version == -1) { leaf.Version = Version; } SetBranch(leaf.Index, leaf); } private void RemoveBranch(Hash256 index) { RemoveBranch(SelectBranch(index)); } public void WalkLeaves(OnLeaf leafWalker) { foreach (var branch in Branches.Where(branch => branch != null)) { if (branch.IsInner) { branch.AsInner().WalkLeaves(leafWalker); } else if (branch.IsLeaf) { leafWalker(branch.AsLeaf()); } } } public virtual void WalkTree(ITreeWalker treeWalker) { treeWalker.OnInner(this); foreach (var branch in Branches.Where(branch => branch != null)) { if (branch.IsLeaf) { treeWalker.OnLeaf(branch.AsLeaf()); } else if (branch.IsInner) { branch.AsInner().WalkTree(treeWalker); } } } /// <returns> the `only child` leaf or null if other children </returns> public ShaMapLeaf OnlyChildLeaf() { ShaMapLeaf leaf = null; var leaves = 0; foreach (var branch in Branches.Where(branch => branch != null)) { if (branch.IsInner) { leaf = null; break; } if (++leaves == 1) { leaf = branch.AsLeaf(); } else { leaf = null; break; } } return leaf; } public bool RemoveLeaf(Hash256 index) { var path = PathToIndex(index); if (!path.HasMatchedLeaf()) return false; var top = path.DirtyOrCopyInners(); top.RemoveBranch(index); path.CollapseOnlyLeafChildInners(); return true; } public IShaMapItem<object> GetItem(Hash256 index) { return GetLeaf(index)?.Item; } public bool AddItem(Hash256 index, IShaMapItem<object> item) { return AddLeaf(new ShaMapLeaf(index, item)); } public bool UpdateItem(Hash256 index, IShaMapItem<object> item) { return UpdateLeaf(new ShaMapLeaf(index, item)); } public bool HasLeaf(Hash256 index) { return PathToIndex(index).HasMatchedLeaf(); } public ShaMapLeaf GetLeaf(Hash256 index) { var stack = PathToIndex(index); return stack.HasMatchedLeaf() ? stack.Leaf : null; } public bool AddLeaf(ShaMapLeaf leaf) { var stack = PathToIndex(leaf.Index); if (stack.HasMatchedLeaf()) { return false; } var top = stack.DirtyOrCopyInners(); top.AddLeafToTerminalInner(leaf); return true; } public bool UpdateLeaf(ShaMapLeaf leaf) { var stack = PathToIndex(leaf.Index); if (!stack.HasMatchedLeaf()) return false; var top = stack.DirtyOrCopyInners(); // Why not update in place? Because of structural sharing top.SetLeaf(leaf); return true; } public PathToIndex PathToIndex(Hash256 index) { return new PathToIndex(this, index); } /// <summary> /// This should only be called on the deepest inners, as it /// does not do any dirtying. </summary> /// <param name="leaf"> to add to inner </param> internal void AddLeafToTerminalInner(ShaMapLeaf leaf) { var branch = GetBranch(leaf.Index); if (branch == null) { SetLeaf(leaf); } else if (branch.IsInner) { throw new InvalidOperationException(); } else if (branch.IsLeaf) { var inner = MakeInnerChild(); SetBranch(leaf.Index, inner); inner.AddLeafToTerminalInner(leaf); inner.AddLeafToTerminalInner(branch.AsLeaf()); } } protected internal void SetBranch(Hash256 index, ShaMapNode node) { SetBranch(SelectBranch(index), node); } protected internal ShaMapNode GetBranch(Hash256 index) { return GetBranch(index.Nibblet(Depth)); } public ShaMapNode GetBranch(int i) { return Branches[i]; } public ShaMapNode Branch(int i) { return Branches[i]; } protected internal int SelectBranch(Hash256 index) { return index.Nibblet(Depth); } public bool HasLeaf(int i) { return Branches[i].IsLeaf; } public bool HasInner(int i) { return Branches[i].IsInner; } public bool HasNone(int i) { return Branches[i] == null; } private void SetBranch(int slot, ShaMapNode node) { SlotBits = SlotBits | (1 << slot); Branches[slot] = node; Invalidate(); } private void RemoveBranch(int slot) { Branches[slot] = null; SlotBits = SlotBits & ~(1 << slot); } public bool Empty() { return SlotBits == 0; } public override bool IsInner => true; public override bool IsLeaf => false; internal override HashPrefix Prefix() { return HashPrefix.InnerNode; } public override void ToBytesSink(IBytesSink sink) { foreach (var branch in Branches) { if (branch != null) { branch.Hash().ToBytes(sink); } else { Hash256.Zero.ToBytes(sink); } } } public override Hash256 Hash() { if (Empty()) { // empty inners have a hash of all Zero // it's only valid for a root node to be empty // any other inner node, must contain at least a // single leaf Debug.Assert(Depth == 0); return Hash256.Zero; } // hash the hashPrefix() and toBytesSink return base.Hash(); } public ShaMapLeaf GetLeafForUpdating(Hash256 leaf) { var path = PathToIndex(leaf); if (path.HasMatchedLeaf()) { return path.InvalidatedPossiblyCopiedLeafForUpdating(); } return null; } public int BranchCount() { return Branches.Count(branch => branch != null); } } }
// 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.Insights { using Azure; using Management; using Rest; using 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> /// LogProfilesOperations operations. /// </summary> internal partial class LogProfilesOperations : IServiceOperations<MonitorManagementClient>, ILogProfilesOperations { /// <summary> /// Initializes a new instance of the LogProfilesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LogProfilesOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Deletes the log profile. /// </summary> /// <param name='logProfileName'> /// The name of the log profile. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string logProfileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (logProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-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("logProfileName", logProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString(); _url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName)); _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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the log profile. /// </summary> /// <param name='logProfileName'> /// The name of the log profile. /// </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<LogProfileResource>> GetWithHttpMessagesAsync(string logProfileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (logProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-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("logProfileName", logProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString(); _url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName)); _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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (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<LogProfileResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LogProfileResource>(_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> /// Create or update a log profile in Azure Monitoring REST API. /// </summary> /// <param name='logProfileName'> /// The name of the log profile. /// </param> /// <param name='parameters'> /// Parameters supplied 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> /// <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<LogProfileResource>> CreateOrUpdateWithHttpMessagesAsync(string logProfileName, LogProfileResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (logProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-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("logProfileName", logProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString(); _url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName)); _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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (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<LogProfileResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LogProfileResource>(_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> /// List the log profiles. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<LogProfileResource>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-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("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}/providers/microsoft.insights/logprofiles").ToString(); _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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (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<IEnumerable<LogProfileResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<LogProfileResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field01.field01 { // <Title> Compound operator in field.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; char c = (char)2; d.field *= c; int i = 5; d.field /= Method(i); sbyte s = 3; d.field %= t[s]; if (d.field != 1) return 1; MyDel md = Method; dynamic dmd = new MyDel(Method); d.field += md(2); if (d.field != 3) return 1; d.field -= dmd(2); if (d.field != 1) return 1; return (int)(d.field -= LongPro); } public long field = 10; public static int Method(int i) { return i; } public dynamic this[object o] { get { return o; } } public static long LongPro { protected get { return 1L; } set { } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field02.field02 { // <Title> Compound operator in field.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; dynamic c = (char)2; dynamic c0 = c; d.field *= c0; c = 5; d.field /= Method(c); sbyte s = 3; c = s; d.field %= t[c]; if (d.field != 1) return 1; MyDel md = Method; dynamic dmd = new MyDel(Method); c = 2; d.field += md(c); if (d.field != 3) return 1; d.field -= dmd(2); if (d.field != 1) return 1; return (int)(d.field -= d.LongPro); } public long field = 10; public static int Method(int i) { return i; } public dynamic this[object o] { get { return o; } } public long LongPro { protected get { return 1L; } set { } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field03.field03 { public class Test { public static dynamic count1 = 1; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { count1 = count1 + 1; count1 += 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property01.property01 { // <Title> Compound operator in property.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; d.StringProp = "a"; d.StringProp += "b"; d.StringProp += t.StringProp; d.StringProp += t.Method(1); var temp = 10.1M; d.StringProp += t[temp]; if (d.StringProp != "abab1" + temp.ToString()) return 1; return 0; } public string StringProp { get; set; } public int Method(int i) { return i; } public dynamic this[object o] { get { return o; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property02.property02 { // <Title> Compound operator in property.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; dynamic c = "a"; d.StringProp = c; c = "b"; d.StringProp += c; d.StringProp += d.StringProp; c = 1; d.StringProp += d.Method(c); c = 10.1M; d.StringProp += d[c]; if (d.StringProp != "abab1" + c.ToString()) return 1; return 0; } public string StringProp { get; set; } public int Method(int i) { return i; } public dynamic this[object o] { get { return o; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property03.property03 { // <Title> Compound operator with property.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class C { public dynamic P { get; set; } public static dynamic operator +(C lhs, int rhs) { lhs.P = lhs.P + rhs; return lhs; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C c = new C() { P = 0 } ; c += 2; return c.P == 2 ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer01.indexer01 { // <Title> Compound operator in indexer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; char c = (char)2; d[null] *= c; int i = 5; d[1] /= Method(i); sbyte s = 3; d[default(long)] %= t[s, ""]; if (d[default(string)] != 1) return 1; MyDel md = Method; dynamic dmd = new MyDel(Method); d[default(dynamic)] += md(2); if (d[12.34f] != 3) return 1; d[typeof(Test)] -= dmd(2); if (d[""] != 1) return 1; return (int)(d[new Test()] -= LongPro); } private long _field = 10; public long this[dynamic d] { get { return _field; } set { _field = value; } } public static int Method(int i) { return i; } public dynamic this[object o, string m] { get { return o; } } public static long LongPro { protected get { return 1L; } set { } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer02.indexer02 { // <Title> Compound operator in indexer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); dynamic d = t; char c = (char)2; dynamic c0 = c; d[null] *= c0; dynamic i = 5; d[1] /= Method(i); sbyte s = 3; dynamic s0 = s; d[default(long)] %= t[s0, ""]; if (d[default(string)] != 1) return 1; MyDel md = Method; dynamic dmd = new MyDel(Method); dynamic md0 = 2; d[default(dynamic)] += md(md0); if (d[12.34f] != 3) return 1; d[typeof(Test)] -= dmd(2); if (d[""] != 1) return 1; return (int)(d[new Test()] -= LongPro); } private long _field = 10; public long this[dynamic d] { get { return _field; } set { _field = value; } } public static int Method(int i) { return i; } public dynamic this[object o, string m] { get { return o; } } public static long LongPro { protected get { return 1L; } set { } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order01.order01 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic t = new Test(); t.field *= t.field += t.field; if (t.field != 200) return 1; return 0; } public long field = 10; } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order02.order02 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic t = new Test(); dynamic b = (byte)2; t.MyPro = 7; t.field = 8; t.MyPro %= t.field >>= b; if (t.MyPro != 1 || t.field != 2) return 1; return 0; } public byte field = 10; public short myProvalue; public short MyPro { internal get { return myProvalue; } set { myProvalue = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order03.order03 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic t = new Test(); dynamic b = (byte)2; t[null] += t[b] *= t[""]; if (t[null] != 110) return 1; return 0; } public dynamic myvalue = 10; public dynamic this[object o] { get { return myvalue; } set { this.myvalue = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order04.order04 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); MyDel md = new MyDel(Method); t.field *= t.LongPro %= t[(sbyte)10] -= md(3); if (t.field != 40 || t.LongPro != 4 || t[null] != 5) return 1; return 0; } public long field = 10; public static int Method(int i) { return i; } private long _this0 = 8; public long this[object o] { get { return _this0; } set { _this0 = value; } } private long _longvalue = 9; public long LongPro { protected get { return _longvalue; } set { _longvalue = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order05.order05 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test t = new Test(); MyDel md = new MyDel(Method); t.field *= t.LongPro += t[(int)10] -= md(3); if (t.field != 50 || t.LongPro != 5 || t[null] != 5) return 1; return 0; } public long field = 10; public static int Method(int i) { return i; } private dynamic _this0 = 8; public dynamic this[object o] { get { return _this0; } set { _this0 = value; } } private long _longvalue = 0; public long LongPro { protected get { return _longvalue; } set { _longvalue = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order06.order06 { // <Title> Compound operator execute orders.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public delegate int MyDel(int i); public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic t = new Test(); MyDel md = new MyDel(Method); t.field *= t.LongPro += t[(int)10] -= md(3); if (t.field != 50 || t.LongPro != 5 || t[null] != 5) return 1; return 0; } public long field = 10; public static int Method(int i) { return i; } private dynamic _this0 = 8; public dynamic this[object o] { get { return _this0; } set { _this0 = value; } } private long _longvalue = 0; public long LongPro { protected get { return _longvalue; } set { _longvalue = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context01.context01 { // <Title> Compound operator</Title> // <Description>context // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> using System; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var obj = new Test(); // dynamic v1 = obj.Prop; //100 dynamic v2 = obj.Method((short)(v1 -= 80)); v1 += 80; dynamic v3 = obj[v2 *= (s_field -= 6)]; v2 /= s_field; dynamic val = 0; for (int i = v2; i < checked(v1 += v3 -= v2); i++) { val += 1; } // System.Console.WriteLine("{0}, {1}, {2} {3}", v1, v2, v3, field); dynamic ret = 7 == val; // v1 *= obj.Prop -= 15; // 120 v2 *= (s_field += 1.1); v3 = obj[v2 %= (s_field *= 3.4)] + 100; dynamic arr = new[] { v1 <<= (int)(v1 >>= 10), v2 *= v2 *= 2, v3 *= v1 * (v1 -= s_field)} ; // System.Console.WriteLine("{0}, {1}, {2}", arr[0], arr[1], arr[2]); ret &= 3400 == arr[0]; ret &= (468.18 - arr[1]) < Double.Epsilon; ret &= (1326070373.2 - arr[2]) < Double.Epsilon; v1 = 1.1f; v2 = -2.2f; v3 = 5.5f; arr = new { a1 = v3 -= v1 += v2, a2 = v1 *= v2 + 1, a3 = v3 /= 1.1f } ; System.Console.WriteLine("{0}, {1}, {2}", (object)arr.a1, (object)arr.a2, (object)arr.a3); ret &= (6.6 - arr.a1) < 0.0000001f; // delta ~ 0.00000009f ret &= (1.23 - arr.a2) < Double.Epsilon; ret &= (6 - arr.a3) < Double.Epsilon; System.Console.WriteLine((object)ret); return ret ? 0 : 1; } private static dynamic s_field = 10; public dynamic Prop { get { return 100L; } set { } } public dynamic Method(short i) { return i; } public dynamic this[object o] { get { return o; } } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02b.context02b { // <Title> Compound operator</Title> // <Description>context // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var obj = new Test(); bool ret = obj.RunTest(); return ret ? 0 : 1; } public struct MySt { public MySt(ulong? f) { field = f; } public ulong? field; } public dynamic RunTest() { dynamic[] darr = new[] { "X", "0", "Y" } ; List<dynamic> list = new List<dynamic>(); list.AddRange(darr); bool ret = "X0X0Y" == Method()(list[0] += list[1], list[2]); ret &= "YX" == this[list[2]](null, darr[0]); var va = new List<dynamic> { new MySt(null), new MySt(3), new MySt(5), new MySt(7), new MySt(11), new MySt(13)} ; var q = from i in new[] { va[1].field *= 11, va[2].field *= va[2].field %= 19, va[3].field += va[4].field *= va[5].field } where (0 < (va[5].field += va[3].field -= 2)) select i; dynamic idx = 0; foreach (var v in q) { if (0 == idx) { ret &= (33 == v); // System.Console.WriteLine("v1 {0}", v); } else if (idx == 1) { // System.Console.WriteLine("v2 {0}", v); ret &= (25 == v); } else if (idx == 2) { // System.Console.WriteLine("v3 {0}", v); ret &= (150 == v); } idx++; } return ret; } public delegate dynamic MyDel(dynamic p1, dynamic p2 = default(object), long p3 = 100); public dynamic Method() { MyDel md = delegate (dynamic d, object o, long n) { d += d += o; return d; } ; return md; } public dynamic this[dynamic o] { get { return new MyDel((x, y, z) => { return o + y; } ); } } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02c.context02c { // <Title> Compound operator</Title> // <Description>context // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var obj = new Test(); bool ret = obj.RunTest(); return ret ? 0 : 1; } public struct MySt { public MySt(ulong? f) { field = f; } public ulong? field; } public dynamic RunTest() { dynamic[] darr = new[] { "X", "0", "Y" } ; List<dynamic> list = new List<dynamic>(); list.AddRange(darr); bool ret = "X0YY" == Method()(list[0] += list[1], list[2]); ret &= "YX" == this[list[2]](null, darr[0]); var va = new List<dynamic> { new MySt(null), new MySt(3), new MySt(5), new MySt(7), new MySt(11), new MySt(13)} ; var q = from i in new[] { va[1].field *= 11, va[2].field *= va[2].field %= 19, va[3].field += va[4].field *= va[5].field } where (0 < (va[5].field += va[3].field -= 2)) select i; dynamic idx = 0; foreach (var v in q) { if (0 == idx) { ret &= (33 == v); // System.Console.WriteLine("v1 {0}", v); } else if (idx == 1) { // System.Console.WriteLine("v2 {0}", v); ret &= (25 == v); } else if (idx == 2) { // System.Console.WriteLine("v3 {0}", v); ret &= (150 == v); } idx++; } return ret; } public delegate dynamic MyDel(dynamic p1, dynamic p2 = default(object), long p3 = 100); public dynamic Method() { MyDel md = delegate (dynamic d, dynamic o, long n) { d += o += o; return d; } ; return md; } public dynamic this[dynamic o] { get { return new MyDel((x, y, z) => { return o + y; } ); } } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context03.context03 { // <Title> Compound operator (Regression) </Title> // <Description>context // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic[] da = new[] { "X", "Y" } ; var v = M()(da[0] += "Z"); return (v == "XZ") ? 0 : 1; } public delegate string MyDel(string s); public static MyDel M() { return new MyDel(x => { return x; } ); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.bug741491array.bug741491array { // <Title> Compound operator (Regression) </Title> // <Description>LHS of compound op with dynamic array/index access // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> public class Test { public dynamic this[int i] { get { return 0; } set { } } public int this[int i, int j] { get { return i + j; } set { } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { bool ret = true; var x = new Test(); x[i: 0] += null; // [IL] stack overflow x[i: 1] -= 1; x[i: -0]++; // ICE x[i: -1]--; // ICE dynamic d = 3; x[0, j: 1] += d; x[i: 1, j: -1] -= d; ret &= x.Test01(); ret &= x.Test02(); ret &= x.Test03(); return ret ? 0 : 1; } private bool Test01() { bool ret = true; dynamic[] dary = new dynamic[] { 100, 200, 300 } ; dary[0]++; ret &= 101 == dary[0]; dary[1]--; ret &= 199 == dary[1]; if (!ret) System.Console.WriteLine("Test01 fail - ++/--"); return ret; } private bool Test02() { bool ret = true; dynamic[] dary = new dynamic[] { 0, -1, 1 } ; dary[0] += null; dary[1] += 2; ret &= 1 == dary[1]; dary[2] -= 1; ret &= 0 == dary[2]; if (!ret) System.Console.WriteLine("Test02 fail - +=/-="); return ret; } private bool Test03() { bool ret = true; int[] iary = new[] { -1, -2, -3 } ; dynamic d = 3; iary[0] += d; ret &= 2 == iary[0]; iary[1] -= d; ret &= -5 == iary[1]; if (!ret) System.Console.WriteLine("Test03 fail - +=/-="); return ret; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.using01.using01 { // <Title> Dynamic modification of a using variable </Title> // <Description> // Different from static behavior, no exception. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> //<Expects Status=warning>\(13,16\).*CS0649</Expects> using System; public class TestClass { [Fact] public void RunTest() { A.DynamicCSharpRunTest(); } } public struct A : IDisposable { public int X; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { using (dynamic a = new A()) { a.X++; //no Exception here in dynamic call. } return 0; } public void Dispose() { } } }
using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Linq; using System.Reflection; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BaseDirectoryWrapper = Lucene.Net.Store.BaseDirectoryWrapper; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using IBits = Lucene.Net.Util.IBits; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; [TestFixture] public class TestFilterAtomicReader : LuceneTestCase { private class TestReader : FilterAtomicReader { /// <summary> /// Filter that only permits terms containing 'e'. </summary> private class TestFields : FilterFields { internal TestFields(Fields @in) : base(@in) { } public override Terms GetTerms(string field) { return new TestTerms(base.GetTerms(field)); } } private class TestTerms : FilterTerms { internal TestTerms(Terms @in) : base(@in) { } public override TermsEnum GetEnumerator() { return new TestTermsEnum(base.GetEnumerator()); } public override TermsEnum GetEnumerator(TermsEnum reuse) { return new TestTermsEnum(base.GetEnumerator(reuse)); } } private class TestTermsEnum : FilterTermsEnum { public TestTermsEnum(TermsEnum @in) : base(@in) { } /// <summary> /// Scan for terms containing the letter 'e'. </summary> public override bool MoveNext() { while (m_input.MoveNext()) { if (m_input.Term.Utf8ToString().IndexOf('e') != -1) return true; } return false; } /// <summary> /// Scan for terms containing the letter 'e'. </summary> [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (MoveNext()) return m_input.Term; return null; } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { return new TestPositions(base.DocsAndPositions(liveDocs, reuse is null ? null : ((FilterDocsAndPositionsEnum)reuse).m_input, flags)); } } /// <summary> /// Filter that only returns odd numbered documents. </summary> private class TestPositions : FilterDocsAndPositionsEnum { public TestPositions(DocsAndPositionsEnum input) : base(input) { } /// <summary> /// Scan for odd numbered documents. </summary> public override int NextDoc() { int doc; while ((doc = m_input.NextDoc()) != NO_MORE_DOCS) { if ((doc % 2) == 1) { return doc; } } return NO_MORE_DOCS; } } public TestReader(IndexReader reader) : base(SlowCompositeReaderWrapper.Wrap(reader)) { } public override Fields Fields => new TestFields(base.Fields); } /// <summary> /// Tests the IndexReader.getFieldNames implementation </summary> /// <exception cref="Exception"> on error </exception> [Test] public virtual void TestFilterIndexReader() { Directory directory = NewDirectory(); IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document d1 = new Document(); d1.Add(NewTextField("default", "one two", Field.Store.YES)); writer.AddDocument(d1); Document d2 = new Document(); d2.Add(NewTextField("default", "one three", Field.Store.YES)); writer.AddDocument(d2); Document d3 = new Document(); d3.Add(NewTextField("default", "two four", Field.Store.YES)); writer.AddDocument(d3); writer.Dispose(); Directory target = NewDirectory(); // We mess with the postings so this can fail: ((BaseDirectoryWrapper)target).CrossCheckTermVectorsOnDispose = false; writer = new IndexWriter(target, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); IndexReader reader = new TestReader(DirectoryReader.Open(directory)); writer.AddIndexes(reader); writer.Dispose(); reader.Dispose(); reader = DirectoryReader.Open(target); TermsEnum terms = MultiFields.GetTerms(reader, "default").GetEnumerator(); while (terms.MoveNext()) { Assert.IsTrue(terms.Term.Utf8ToString().IndexOf('e') != -1); } Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(new BytesRef("one"))); DocsAndPositionsEnum positions = terms.DocsAndPositions(MultiFields.GetLiveDocs(reader), null); while (positions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { Assert.IsTrue((positions.DocID % 2) == 1); } reader.Dispose(); directory.Dispose(); target.Dispose(); } private static void CheckOverrideMethods(Type clazz) { Type superClazz = clazz.BaseType; foreach (MethodInfo m in superClazz.GetMethods()) { // LUCENENET specific - since we changed to using a property for Attributes rather than a method, // we need to reflect that as get_Attributes here. if (m.IsStatic || m.IsAbstract || m.IsFinal || /*m.Synthetic ||*/ m.Name.Equals("get_Attributes", StringComparison.Ordinal) // LUCENENET specific - we only override GetEnumerator(reuse) in specific cases. Also, GetIterator() has a default implementation // that will be removed before the release. || m.Name.Equals("GetEnumerator") && m.GetParameters().Length == 1 && m.GetParameters()[0].Name == "reuse" || m.Name.Equals("GetIterator")) { continue; } // The point of these checks is to ensure that methods that have a default // impl through other methods are not overridden. this makes the number of // methods to override to have a working impl minimal and prevents from some // traps: for example, think about having getCoreCacheKey delegate to the // filtered impl by default MethodInfo subM = clazz.GetMethod(m.Name, m.GetParameters().Select(p => p.ParameterType).ToArray()); if (subM.DeclaringType == clazz && m.DeclaringType != typeof(object) && m.DeclaringType != subM.DeclaringType) { Assert.Fail(clazz + " overrides " + m + " although it has a default impl"); } } } [Test] public virtual void TestOverrideMethods() { CheckOverrideMethods(typeof(FilterAtomicReader)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterFields)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterTerms)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterTermsEnum)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterDocsEnum)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterDocsAndPositionsEnum)); } } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.Config.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Config.Api.Tests { public class MenuTests { public static ConfigMenuController Fixture() { ConfigMenuController controller = new ConfigMenuController(new MenuRepository(), "", new LoginView()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Config.Entities.Menu menu = Fixture().Get(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void First() { Frapid.Config.Entities.Menu menu = Fixture().GetFirst(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Config.Entities.Menu menu = Fixture().GetPrevious(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Config.Entities.Menu menu = Fixture().GetNext(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Config.Entities.Menu menu = Fixture().GetLast(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Config.Entities.Menu> menus = Fixture().Get(new int[] { }); Assert.NotNull(menus); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
// Copyright 2017, Google LLC 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary> /// Settings for a <see cref="ErrorStatsServiceClient"/>. /// </summary> public sealed partial class ErrorStatsServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ErrorStatsServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ErrorStatsServiceSettings"/>. /// </returns> public static ErrorStatsServiceSettings GetDefault() => new ErrorStatsServiceSettings(); /// <summary> /// Constructs a new <see cref="ErrorStatsServiceSettings"/> object with default settings. /// </summary> public ErrorStatsServiceSettings() { } private ErrorStatsServiceSettings(ErrorStatsServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListGroupStatsSettings = existing.ListGroupStatsSettings; ListEventsSettings = existing.ListEventsSettings; DeleteEventsSettings = existing.DeleteEventsSettings; OnCopy(existing); } partial void OnCopy(ErrorStatsServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListGroupStats</c> and <c>ErrorStatsServiceClient.ListGroupStatsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.ListGroupStats</c> and /// <c>ErrorStatsServiceClient.ListGroupStatsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListGroupStatsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListEvents</c> and <c>ErrorStatsServiceClient.ListEventsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.ListEvents</c> and /// <c>ErrorStatsServiceClient.ListEventsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListEventsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.DeleteEvents</c> and <c>ErrorStatsServiceClient.DeleteEventsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.DeleteEvents</c> and /// <c>ErrorStatsServiceClient.DeleteEventsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings DeleteEventsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ErrorStatsServiceSettings"/> object.</returns> public ErrorStatsServiceSettings Clone() => new ErrorStatsServiceSettings(this); } /// <summary> /// ErrorStatsService client wrapper, for convenient use. /// </summary> public abstract partial class ErrorStatsServiceClient { /// <summary> /// The default endpoint for the ErrorStatsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443); /// <summary> /// The default ErrorStatsService scopes. /// </summary> /// <remarks> /// The default ErrorStatsService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="ErrorStatsServiceClient"/>.</returns> public static async Task<ErrorStatsServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create(ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ErrorStatsServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create(Channel channel, ErrorStatsServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); ErrorStatsService.ErrorStatsServiceClient grpcClient = new ErrorStatsService.ErrorStatsServiceClient(channel); return new ErrorStatsServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ErrorStatsServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ErrorStatsServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ErrorStatsServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ErrorStatsServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ErrorStatsService client. /// </summary> public virtual ErrorStatsService.ErrorStatsServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as &lt;code&gt;projects/&lt;/code&gt; plus the /// &lt;a href="https://support.google.com/cloud/answer/6158840"&gt;Google Cloud /// Platform project ID&lt;/a&gt;. /// /// Example: &lt;code&gt;projects/my-project-123&lt;/code&gt;. /// </param> /// <param name="timeRange"> /// [Optional] List data for the given time range. /// If not set a default time range is used. The field time_range_begin /// in the response will specify the beginning of this time range. /// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit group_id list. /// If a group_id list is given, also &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero /// occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListGroupStatsAsync( new ListGroupStatsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as &lt;code&gt;projects/&lt;/code&gt; plus the /// &lt;a href="https://support.google.com/cloud/answer/6158840"&gt;Google Cloud /// Platform project ID&lt;/a&gt;. /// /// Example: &lt;code&gt;projects/my-project-123&lt;/code&gt;. /// </param> /// <param name="timeRange"> /// [Optional] List data for the given time range. /// If not set a default time range is used. The field time_range_begin /// in the response will specify the beginning of this time range. /// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit group_id list. /// If a group_id list is given, also &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero /// occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListGroupStats( new ListGroupStatsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( ListGroupStatsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( ListGroupStatsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// [Required] The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListEventsAsync( new ListEventsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// [Required] The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListEvents( new ListEventsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( ListEventsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( ListEventsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<DeleteEventsResponse> DeleteEventsAsync( ProjectName projectName, CallSettings callSettings = null) => DeleteEventsAsync( new DeleteEventsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<DeleteEventsResponse> DeleteEventsAsync( ProjectName projectName, CancellationToken cancellationToken) => DeleteEventsAsync( projectName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DeleteEventsResponse DeleteEvents( ProjectName projectName, CallSettings callSettings = null) => DeleteEvents( new DeleteEventsRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<DeleteEventsResponse> DeleteEventsAsync( DeleteEventsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DeleteEventsResponse DeleteEvents( DeleteEventsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// ErrorStatsService client wrapper implementation, for convenient use. /// </summary> public sealed partial class ErrorStatsServiceClientImpl : ErrorStatsServiceClient { private readonly ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> _callListGroupStats; private readonly ApiCall<ListEventsRequest, ListEventsResponse> _callListEvents; private readonly ApiCall<DeleteEventsRequest, DeleteEventsResponse> _callDeleteEvents; /// <summary> /// Constructs a client wrapper for the ErrorStatsService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ErrorStatsServiceSettings"/> used within this client </param> public ErrorStatsServiceClientImpl(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings settings) { GrpcClient = grpcClient; ErrorStatsServiceSettings effectiveSettings = settings ?? ErrorStatsServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callListGroupStats = clientHelper.BuildApiCall<ListGroupStatsRequest, ListGroupStatsResponse>( GrpcClient.ListGroupStatsAsync, GrpcClient.ListGroupStats, effectiveSettings.ListGroupStatsSettings); _callListEvents = clientHelper.BuildApiCall<ListEventsRequest, ListEventsResponse>( GrpcClient.ListEventsAsync, GrpcClient.ListEvents, effectiveSettings.ListEventsSettings); _callDeleteEvents = clientHelper.BuildApiCall<DeleteEventsRequest, DeleteEventsResponse>( GrpcClient.DeleteEventsAsync, GrpcClient.DeleteEvents, effectiveSettings.DeleteEventsSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC ErrorStatsService client. /// </summary> public override ErrorStatsService.ErrorStatsServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_ListGroupStatsRequest(ref ListGroupStatsRequest request, ref CallSettings settings); partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref CallSettings settings); partial void Modify_DeleteEventsRequest(ref DeleteEventsRequest request, ref CallSettings settings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public override PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( ListGroupStatsRequest request, CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new GrpcPagedAsyncEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public override PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( ListGroupStatsRequest request, CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new GrpcPagedEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources. /// </returns> public override PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( ListEventsRequest request, CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new GrpcPagedAsyncEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorEvent"/> resources. /// </returns> public override PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( ListEventsRequest request, CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new GrpcPagedEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<DeleteEventsResponse> DeleteEventsAsync( DeleteEventsRequest request, CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Async(request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override DeleteEventsResponse DeleteEvents( DeleteEventsRequest request, CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListGroupStatsRequest : IPageRequest { } public partial class ListGroupStatsResponse : IPageResponse<ErrorGroupStats> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<ErrorGroupStats> GetEnumerator() => ErrorGroupStats.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class ListEventsRequest : IPageRequest { } public partial class ListEventsResponse : IPageResponse<ErrorEvent> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<ErrorEvent> GetEnumerator() => ErrorEvents.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
/* * File Name: PrefixTree.cs * Author : Chi-En Wu * Date : 2012/01/04 */ using System; using System.Collections.Generic; namespace Utils.DataStructure { /// <summary> /// Implements the prefix tree data structure that supports longest prefix matching. /// </summary> /// <typeparam name="TKey">The type of the keys in the prefix tree.</typeparam> /// <typeparam name="TValue">The type of the values in the prefix tree.</typeparam> public class PrefixTree<TKey, TValue> { #region [Constructor(s)] /// <summary> /// Initializes a new instance of the <see cref="PrefixTree&lt;TKey, TValue&gt;"/> class. /// </summary> public PrefixTree() { this.collection = new PrefixTreeNodeCollection<TKey, TValue>(); } #endregion #region [Field(s)] private PrefixTreeNodeCollection<TKey, TValue> collection; #endregion #region [Public Method(s)] /// <summary> /// Removes all nodes from the prefix tree. /// </summary> public void Clear() { this.collection.Clear(); } /// <summary> /// Removes the prefix node with the specified path from the tree. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node to remove.</param> /// <returns>True if the node is successfully found and removed; otherwise, false. This method returns false if the specified node is not found in the tree.</returns> public bool Remove(IEnumerable<TKey> enumerable) { Stack<KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>>> track = new Stack<KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>>>(); foreach (KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> pair in this.PrefixNodePath(enumerable)) { if (!pair.Value.ContainsKey(pair.Key)) { return false; } track.Push(pair); } if (track.Count == 0) { return false; } KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> top = track.Pop(); bool hasChild = top.Value[top.Key].Children.Count > 0; top.Value[top.Key].ResetValue(); if (!hasChild) { while (track.Count > 0) { KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> pair = track.Pop(); if (pair.Value.Count > 1 || pair.Value[pair.Key].HasValue) { break; } pair.Value.Remove(pair.Key); } } return true; } /// <summary> /// Determines whether the tree contains the specified node. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node.</param> /// <returns>True if the tree contains the specified node; otherwise, false.</returns> public bool HasValue(IEnumerable<TKey> enumerable) { PrefixTreeNode<TKey, TValue> currentNode = this.GetMatchedNode(enumerable); return currentNode != null && currentNode.HasValue; } /// <summary> /// Gets the node value associated with the specified path. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node to get.</param> /// <returns>The node value associated with the specified path</returns> public TValue GetValue(IEnumerable<TKey> enumerable) { PrefixTreeNode<TKey, TValue> currentNode = this.GetMatchedNode(enumerable); return currentNode.Value; } /// <summary> /// Gets the node value associated with the specified path. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node to get.</param> /// <param name="value">When this method returns, contains the node value associated with the specified path, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param> /// <returns>True if the tree contains the specified node; otherwise, false.</returns> public bool TryGetValue(IEnumerable<TKey> enumerable, out TValue value) { PrefixTreeNode<TKey, TValue> currentNode = this.GetMatchedNode(enumerable); bool hasValue = currentNode != null && currentNode.HasValue; value = hasValue ? currentNode.Value : default(TValue); return hasValue; } /// <summary> /// Sets the node value associated with the specified path. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node to set.</param> /// <param name="value">The value of the node to set.</param> public void SetValue(IEnumerable<TKey> enumerable, TValue value) { PrefixTreeNode<TKey, TValue> currentNode = this.GetMatchedNode(enumerable, true); currentNode.Value = value; } /// <summary> /// Sets the node value associated with the specified path if that node doesn't exist. /// </summary> /// <param name="enumerable">An enumerable object that specifies the path of the node to set.</param> /// <param name="value">The value of the node to set.</param> /// <returns>True if the set operation is success; otherwise, false. This method returns false if the specified node is already existed in the tree.</returns> public bool TrySetValue(IEnumerable<TKey> enumerable, TValue value) { PrefixTreeNode<TKey, TValue> currentNode = this.GetMatchedNode(enumerable, true); if (currentNode.HasValue) { return false; } currentNode.Value = value; return true; } /// <summary> /// Applies the longest prefix match algorithm to the given enumerable object. /// </summary> /// <param name="enumerable">An enumerable to find a longest matching in the prefix tree.</param> /// <returns>A <see cref="PrefixMatch&lt;TKey, TValue&gt;"/> that represents the result of the longest prefix matching.</returns> public PrefixMatch<TKey, TValue> LongestPrefixMatch(IEnumerable<TKey> enumerable) { PrefixTreeNode<TKey, TValue> longestNode = null; int currentLength = 1, longestLength = 0; foreach (KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> pair in this.PrefixNodePath(enumerable)) { if (!pair.Value.ContainsKey(pair.Key)) { break; } if (pair.Value[pair.Key].HasValue) { longestNode = pair.Value[pair.Key]; longestLength = currentLength; } currentLength++; } return new PrefixMatch<TKey, TValue>(longestNode, longestLength); } #endregion #region [Private Method(s)] private PrefixTreeNode<TKey, TValue> GetMatchedNode(IEnumerable<TKey> enumerable) { return this.GetMatchedNode(enumerable, false); } private PrefixTreeNode<TKey, TValue> GetMatchedNode(IEnumerable<TKey> enumerable, bool createNew) { PrefixTreeNode<TKey, TValue> currentNode = null; foreach (KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> pair in this.PrefixNodePath(enumerable)) { if (!pair.Value.ContainsKey(pair.Key)) { if (!createNew) { return null; } pair.Value[pair.Key] = new PrefixTreeNode<TKey, TValue>(); } currentNode = pair.Value[pair.Key]; } return currentNode; } private IEnumerable<KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>>> PrefixNodePath(IEnumerable<TKey> enumerable) { PrefixTreeNodeCollection<TKey, TValue> currentNodeCollection = this.collection; IEnumerator<TKey> enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { TKey prefix = enumerator.Current; yield return new KeyValuePair<TKey, PrefixTreeNodeCollection<TKey, TValue>> (prefix, currentNodeCollection); if (!currentNodeCollection.ContainsKey(prefix)) { yield break; } currentNodeCollection = currentNodeCollection[prefix].Children; } } #endregion } /// <summary> /// Represents the result of the longest prefix matching. /// </summary> /// <typeparam name="TKey">The type of the keys in the prefix tree.</typeparam> /// <typeparam name="TValue">The type of the values in the prefix tree.</typeparam> public class PrefixMatch<TKey, TValue> { #region [Constructor(s)] internal PrefixMatch(PrefixTreeNode<TKey, TValue> node, int length) { this.node = node; this.length = length; } #endregion #region [Field(s)] private int length; private PrefixTreeNode<TKey, TValue> node; #endregion #region [Property(ies)] /// <summary> /// The length of the longest path that matches the prefix of content. /// </summary> public int Length { get { return this.length; } } /// <summary> /// The value of node that matches the longest prefix. /// </summary> public TValue Value { get { return this.node.Value; } set { this.node.Value = value; } } #endregion } class PrefixTreeNode<TKey, TValue> { #region [Constructor(s)] public PrefixTreeNode() : this(default(TValue), false) { // do nothing } public PrefixTreeNode(TValue value) : this(value, true) { // do nothing } private PrefixTreeNode(TValue value, bool hasValue) { this.children = new PrefixTreeNodeCollection<TKey, TValue>(); this.value = value; this.hasValue = hasValue; } #endregion #region [Field(s)] private bool hasValue; private TValue value; private PrefixTreeNodeCollection<TKey, TValue> children; #endregion #region [Property(ies)] public bool HasValue { get { return this.hasValue; } } public TValue Value { get { if (!this.hasValue) throw new InvalidOperationException(); return this.value; } set { this.hasValue = true; this.value = value; } } public PrefixTreeNodeCollection<TKey, TValue> Children { get { return this.children; } } #endregion #region [Public Method(s)] public void ResetValue() { this.hasValue = false; } #endregion } class PrefixTreeNodeCollection<TKey, TValue> : AbstractDictionary<TKey, PrefixTreeNode<TKey, TValue>> { #region [Constructor(s)] public PrefixTreeNodeCollection() { this.collection = new Dictionary<TKey, PrefixTreeNode<TKey, TValue>>(); } public PrefixTreeNodeCollection(PrefixTreeNodeCollection<TKey, TValue> collection) { this.collection = collection.collection; } #endregion #region [Field(s)] private Dictionary<TKey, PrefixTreeNode<TKey, TValue>> collection; #endregion #region [Property(ies)] public override PrefixTreeNode<TKey, TValue> this[TKey key] { get { return this.collection[key]; } set { this.collection[key] = value; } } public override ICollection<TKey> Keys { get { return this.collection.Keys; } } public override ICollection<PrefixTreeNode<TKey, TValue>> Values { get { return this.collection.Values; } } public override int Count { get { return this.collection.Count; } } #endregion #region [Public Method(s)] public override void Add(TKey key, PrefixTreeNode<TKey, TValue> value) { this.collection.Add(key, value); } public override void Clear() { this.collection.Clear(); } public override bool ContainsKey(TKey key) { return this.collection.ContainsKey(key); } public override bool Remove(TKey key) { return this.collection.Remove(key); } public override bool TryGetValue(TKey key, out PrefixTreeNode<TKey, TValue> value) { return this.collection.TryGetValue(key, out value); } public override IEnumerator<KeyValuePair<TKey, PrefixTreeNode<TKey, TValue>>> GetEnumerator() { return this.collection.GetEnumerator(); } #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 Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum ACCESSERROR { ACCESSERROR_NOACCESS, ACCESSERROR_NOACCESSTHRU, ACCESSERROR_NOERROR }; // // Semantic check methods on SymbolLoader // internal abstract class CSemanticChecker { // Generate an error if CType is static. public bool CheckForStaticClass(Symbol symCtx, CType CType, ErrorCode err) { if (!CType.isStaticClass()) return false; ReportStaticClassError(symCtx, CType, err); return true; } public virtual ACCESSERROR CheckAccess2(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate()); Debug.Assert(typeThru == null || typeThru.IsAggregateType() || typeThru.IsTypeParameterType() || typeThru.IsArrayType() || typeThru.IsNullableType() || typeThru.IsErrorType()); #if DEBUG switch (symCheck.getKind()) { default: break; case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_FieldSymbol: case SYMKIND.SK_EventSymbol: Debug.Assert(atsCheck != null); break; } #endif // DEBUG ACCESSERROR error = CheckAccessCore(symCheck, atsCheck, symWhere, typeThru); if (ACCESSERROR.ACCESSERROR_NOERROR != error) { return error; } // Check the accessibility of the return CType. CType CType = symCheck.getType(); if (CType == null) { return ACCESSERROR.ACCESSERROR_NOERROR; } // For members of AGGSYMs, atsCheck should always be specified! Debug.Assert(atsCheck != null); if (atsCheck.getAggregate().IsSource()) { // We already check the "at least as accessible as" rules. // Does this always work for generics? // Could we get a bad CType argument in typeThru? // Maybe call CheckTypeAccess on typeThru? return ACCESSERROR.ACCESSERROR_NOERROR; } // Substitute on the CType. if (atsCheck.GetTypeArgsAll().Count > 0) { CType = SymbolLoader.GetTypeManager().SubstType(CType, atsCheck); } return CheckTypeAccess(CType, symWhere) ? ACCESSERROR.ACCESSERROR_NOERROR : ACCESSERROR.ACCESSERROR_NOACCESS; } public virtual bool CheckTypeAccess(CType type, Symbol symWhere) { Debug.Assert(type != null); // Array, Ptr, Nub, etc don't matter. type = type.GetNakedType(true); if (!type.IsAggregateType()) { Debug.Assert(type.IsVoidType() || type.IsErrorType() || type.IsTypeParameterType()); return true; } for (AggregateType ats = type.AsAggregateType(); ats != null; ats = ats.outerType) { if (ACCESSERROR.ACCESSERROR_NOERROR != CheckAccessCore(ats.GetOwningAggregate(), ats.outerType, symWhere, null)) { return false; } } TypeArray typeArgs = type.AsAggregateType().GetTypeArgsAll(); for (int i = 0; i < typeArgs.Count; i++) { if (!CheckTypeAccess(typeArgs[i], symWhere)) return false; } return true; } // Generates an error for static classes public void ReportStaticClassError(Symbol symCtx, CType CType, ErrorCode err) { if (symCtx != null) ErrorContext.Error(err, CType, new ErrArgRef(symCtx)); else ErrorContext.Error(err, CType); } public abstract SymbolLoader SymbolLoader { get; } public abstract SymbolLoader GetSymbolLoader(); ///////////////////////////////////////////////////////////////////////////////// // SymbolLoader forwarders (begin) // private ErrorHandling ErrorContext { get { return SymbolLoader.ErrorContext; } } public ErrorHandling GetErrorContext() { return ErrorContext; } public NameManager GetNameManager() { return SymbolLoader.GetNameManager(); } public TypeManager GetTypeManager() { return SymbolLoader.GetTypeManager(); } public BSYMMGR getBSymmgr() { return SymbolLoader.getBSymmgr(); } public SymFactory GetGlobalSymbolFactory() { return SymbolLoader.GetGlobalSymbolFactory(); } public MiscSymFactory GetGlobalMiscSymFactory() { return SymbolLoader.GetGlobalMiscSymFactory(); } //protected CompilerPhase GetCompPhase() { return SymbolLoader.CompPhase(); } //protected void SetCompPhase(CompilerPhase compPhase) { SymbolLoader.compPhase = compPhase; } public PredefinedTypes getPredefTypes() { return SymbolLoader.getPredefTypes(); } // // SymbolLoader forwarders (end) ///////////////////////////////////////////////////////////////////////////////// // // Utility methods // private ACCESSERROR CheckAccessCore(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate()); Debug.Assert(typeThru == null || typeThru.IsAggregateType() || typeThru.IsTypeParameterType() || typeThru.IsArrayType() || typeThru.IsNullableType() || typeThru.IsErrorType()); switch (symCheck.GetAccess()) { default: throw Error.InternalCompilerError(); //return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_UNKNOWN: return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_PUBLIC: return ACCESSERROR.ACCESSERROR_NOERROR; case ACCESS.ACC_PRIVATE: case ACCESS.ACC_PROTECTED: if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; case ACCESS.ACC_INTERNAL: case ACCESS.ACC_INTERNALPROTECTED: // Check internal, then protected. if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } if (symWhere.SameAssemOrFriend(symCheck)) { return ACCESSERROR.ACCESSERROR_NOERROR; } if (symCheck.GetAccess() == ACCESS.ACC_INTERNAL) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; } // Should always have atsCheck for private and protected access check. // We currently don't need it since access doesn't respect instantiation. // We just use symWhere.parent.AsAggregateSymbol() instead. AggregateSymbol aggCheck = symCheck.parent.AsAggregateSymbol(); // Find the inner-most enclosing AggregateSymbol. AggregateSymbol aggWhere = null; for (Symbol symT = symWhere; symT != null; symT = symT.parent) { if (symT.IsAggregateSymbol()) { aggWhere = symT.AsAggregateSymbol(); break; } if (symT.IsAggregateDeclaration()) { aggWhere = symT.AsAggregateDeclaration().Agg(); break; } } if (aggWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // First check for private access. for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { if (agg == aggCheck) { return ACCESSERROR.ACCESSERROR_NOERROR; } } if (symCheck.GetAccess() == ACCESS.ACC_PRIVATE) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // Handle the protected case - which is the only real complicated one. Debug.Assert(symCheck.GetAccess() == ACCESS.ACC_PROTECTED || symCheck.GetAccess() == ACCESS.ACC_INTERNALPROTECTED); // Check if symCheck is in aggWhere or a base of aggWhere, // or in an outer agg of aggWhere or a base of an outer agg of aggWhere. AggregateType atsThru = null; if (typeThru != null && !symCheck.isStatic) { atsThru = SymbolLoader.GetAggTypeSym(typeThru); } // Look for aggCheck among the base classes of aggWhere and outer aggs. bool found = false; for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { Debug.Assert(agg != aggCheck); // We checked for this above. // Look for aggCheck among the base classes of agg. if (agg.FindBaseAgg(aggCheck)) { found = true; // aggCheck is a base class of agg. Check atsThru. // For non-static protected access to be legal, atsThru must be an instantiation of // agg or a CType derived from an instantiation of agg. In this case // all that matters is that agg is in the base AggregateSymbol chain of atsThru. The // actual AGGTYPESYMs involved don't matter. if (atsThru == null || atsThru.getAggregate().FindBaseAgg(agg)) { return ACCESSERROR.ACCESSERROR_NOERROR; } } } // the CType in which the method is being called has no relationship with the // CType on which the method is defined surely this is NOACCESS and not NOACCESSTHRU if (found == false) return ACCESSERROR.ACCESSERROR_NOACCESS; return (atsThru == null) ? ACCESSERROR.ACCESSERROR_NOACCESS : ACCESSERROR.ACCESSERROR_NOACCESSTHRU; } public bool CheckBogus(Symbol sym) { if (sym == null) { return false; } if (!sym.hasBogus()) { bool fBogus = sym.computeCurrentBogusState(); if (fBogus) { // Only set this if everything is declared or // at least 1 declared thing is bogus sym.setBogus(fBogus); } } return sym.hasBogus() && sym.checkBogus(); } public bool CheckBogus(CType pType) { if (pType == null) { return false; } if (!pType.hasBogus()) { bool fBogus = pType.computeCurrentBogusState(); if (fBogus) { // Only set this if everything is declared or // at least 1 declared thing is bogus pType.setBogus(fBogus); } } return pType.hasBogus() && pType.checkBogus(); } public void ReportAccessError(SymWithType swtBad, Symbol symWhere, CType typeQual) { Debug.Assert(!CheckAccess(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) || !CheckTypeAccess(swtBad.GetType(), symWhere)); if (CheckAccess2(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) == ACCESSERROR.ACCESSERROR_NOACCESSTHRU) { ErrorContext.Error(ErrorCode.ERR_BadProtectedAccess, swtBad, typeQual, symWhere); } else { ErrorContext.ErrorRef(ErrorCode.ERR_BadAccess, swtBad); } } public bool CheckAccess(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { return CheckAccess2(symCheck, atsCheck, symWhere, typeThru) == ACCESSERROR.ACCESSERROR_NOERROR; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cluster { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute; using Apache.Ignite.Core.Impl.Events; using Apache.Ignite.Core.Impl.Messaging; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Ignite projection implementation. /// </summary> internal class ClusterGroupImpl : PlatformTarget, IClusterGroupEx { /** Attribute: platform. */ private const string AttrPlatform = "org.apache.ignite.platform"; /** Platform. */ private const string Platform = "dotnet"; /** Initial topver; invalid from Java perspective, so update will be triggered when this value is met. */ private const int TopVerInit = 0; /** */ private const int OpAllMetadata = 1; /** */ private const int OpForAttribute = 2; /** */ private const int OpForCache = 3; /** */ private const int OpForClient = 4; /** */ private const int OpForData = 5; /** */ private const int OpForHost = 6; /** */ private const int OpForNodeIds = 7; /** */ private const int OpMetadata = 8; /** */ private const int OpMetrics = 9; /** */ private const int OpMetricsFiltered = 10; /** */ private const int OpNodeMetrics = 11; /** */ private const int OpNodes = 12; /** */ private const int OpPingNode = 13; /** */ private const int OpTopology = 14; /** */ private const int OpSchema = 15; /** Initial Ignite instance. */ private readonly Ignite _ignite; /** Predicate. */ private readonly Func<IClusterNode, bool> _pred; /** Topology version. */ private long _topVer = TopVerInit; /** Nodes for the given topology version. */ private volatile IList<IClusterNode> _nodes; /** Processor. */ private readonly IUnmanagedTarget _proc; /** Compute. */ private readonly Lazy<Compute> _comp; /** Messaging. */ private readonly Lazy<Messaging> _msg; /** Events. */ private readonly Lazy<Events> _events; /** Services. */ private readonly Lazy<IServices> _services; /// <summary> /// Constructor. /// </summary> /// <param name="proc">Processor.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="ignite">Grid.</param> /// <param name="pred">Predicate.</param> [SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")] public ClusterGroupImpl(IUnmanagedTarget proc, IUnmanagedTarget target, Marshaller marsh, Ignite ignite, Func<IClusterNode, bool> pred) : base(target, marsh) { _proc = proc; _ignite = ignite; _pred = pred; _comp = new Lazy<Compute>(() => new Compute(new ComputeImpl(UU.ProcessorCompute(proc, target), marsh, this, false))); _msg = new Lazy<Messaging>(() => new Messaging(UU.ProcessorMessage(proc, target), marsh, this)); _events = new Lazy<Events>(() => new Events(UU.ProcessorEvents(proc, target), marsh, this)); _services = new Lazy<IServices>(() => new Services(UU.ProcessorServices(proc, target), marsh, this, false, false)); } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ public ICompute GetCompute() { return _comp.Value; } /** <inheritDoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /// <summary> /// Internal routine to get projection for specific node IDs. /// </summary> /// <param name="items">Items.</param> /// <param name="func">Function to transform item to Guid (optional).</param> /// <returns></returns> private IClusterGroup ForNodeIds0<T>(IEnumerable<T> items, Func<T, Guid> func) { Debug.Assert(items != null); IUnmanagedTarget prj = DoProjetionOutOp(OpForNodeIds, writer => { WriteEnumerable(writer, items, func); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { var newPred = _pred == null ? p : node => _pred(node) && p(node); return new ClusterGroupImpl(_proc, Target, Marshaller, _ignite, newPred); } /** <inheritDoc /> */ public IClusterGroup ForAttribute(string name, string val) { IgniteArgumentCheck.NotNull(name, "name"); IUnmanagedTarget prj = DoProjetionOutOp(OpForAttribute, writer => { writer.WriteString(name); writer.WriteString(val); }); return GetClusterGroup(prj); } /// <summary> /// Creates projection with a specified op. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <param name="op">Operation id.</param> /// <returns> /// Projection over nodes that have specified cache running. /// </returns> private IClusterGroup ForCacheNodes(string name, int op) { IUnmanagedTarget prj = DoProjetionOutOp(op, writer => { writer.WriteString(name); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForCacheNodes(string name) { return ForCacheNodes(name, OpForCache); } /** <inheritDoc /> */ public IClusterGroup ForDataNodes(string name) { return ForCacheNodes(name, OpForData); } /** <inheritDoc /> */ public IClusterGroup ForClientNodes(string name) { return ForCacheNodes(name, OpForClient); } /** <inheritDoc /> */ public IClusterGroup ForRemotes() { return GetClusterGroup(UU.ProjectionForRemotes(Target)); } /** <inheritDoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); IUnmanagedTarget prj = DoProjetionOutOp(OpForHost, writer => { writer.WriteGuid(node.Id); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForRandom() { return GetClusterGroup(UU.ProjectionForRandom(Target)); } /** <inheritDoc /> */ public IClusterGroup ForOldest() { return GetClusterGroup(UU.ProjectionForOldest(Target)); } /** <inheritDoc /> */ public IClusterGroup ForYoungest() { return GetClusterGroup(UU.ProjectionForYoungest(Target)); } /** <inheritDoc /> */ public IClusterGroup ForDotNet() { return ForAttribute(AttrPlatform, Platform); } /** <inheritDoc /> */ public ICollection<IClusterNode> GetNodes() { return RefreshNodes(); } /** <inheritDoc /> */ public IClusterNode GetNode(Guid id) { return GetNodes().FirstOrDefault(node => node.Id == id); } /** <inheritDoc /> */ public IClusterNode GetNode() { return GetNodes().FirstOrDefault(); } /** <inheritDoc /> */ public IClusterMetrics GetMetrics() { if (_pred == null) { return DoInOp(OpMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } return DoOutInOp(OpMetricsFiltered, writer => { WriteEnumerable(writer, GetNodes().Select(node => node.Id)); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } /** <inheritDoc /> */ public IMessaging GetMessaging() { return _msg.Value; } /** <inheritDoc /> */ public IEvents GetEvents() { return _events.Value; } /** <inheritDoc /> */ public IServices GetServices() { return _services.Value; } /// <summary> /// Pings a remote node. /// </summary> /// <param name="nodeId">ID of a node to ping.</param> /// <returns>True if node for a given ID is alive, false otherwise.</returns> internal bool PingNode(Guid nodeId) { return DoOutOp(OpPingNode, nodeId) == True; } /// <summary> /// Predicate (if any). /// </summary> public Func<IClusterNode, bool> Predicate { get { return _pred; } } /// <summary> /// Refresh cluster node metrics. /// </summary> /// <param name="nodeId">Node</param> /// <param name="lastUpdateTime"></param> /// <returns></returns> internal ClusterMetricsImpl RefreshClusterNodeMetrics(Guid nodeId, long lastUpdateTime) { return DoOutInOp(OpNodeMetrics, writer => { writer.WriteGuid(nodeId); writer.WriteLong(lastUpdateTime); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; } ); } /// <summary> /// Gets a topology by version. Returns null if topology history storage doesn't contain /// specified topology version (history currently keeps the last 1000 snapshots). /// </summary> /// <param name="version">Topology version.</param> /// <returns>Collection of Ignite nodes which represented by specified topology version, /// if it is present in history storage, {@code null} otherwise.</returns> /// <exception cref="IgniteException">If underlying SPI implementation does not support /// topology history. Currently only {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi} /// supports topology history.</exception> internal ICollection<IClusterNode> Topology(long version) { return DoOutInOp(OpTopology, writer => writer.WriteLong(version), input => IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(input))); } /// <summary> /// Topology version. /// </summary> internal long TopologyVersion { get { RefreshNodes(); return Interlocked.Read(ref _topVer); } } /// <summary> /// Update topology. /// </summary> /// <param name="newTopVer">New topology version.</param> /// <param name="newNodes">New nodes.</param> internal void UpdateTopology(long newTopVer, List<IClusterNode> newNodes) { lock (this) { // If another thread already advanced topology version further, we still // can safely return currently received nodes, but we will not assign them. if (_topVer < newTopVer) { Interlocked.Exchange(ref _topVer, newTopVer); _nodes = newNodes.AsReadOnly(); } } } /// <summary> /// Get current nodes without refreshing the topology. /// </summary> /// <returns>Current nodes.</returns> internal IList<IClusterNode> NodesNoRefresh() { return _nodes; } /// <summary> /// Creates new Cluster Group from given native projection. /// </summary> /// <param name="prj">Native projection.</param> /// <returns>New cluster group.</returns> private IClusterGroup GetClusterGroup(IUnmanagedTarget prj) { return new ClusterGroupImpl(_proc, prj, Marshaller, _ignite, _pred); } /// <summary> /// Refresh projection nodes. /// </summary> /// <returns>Nodes.</returns> private IList<IClusterNode> RefreshNodes() { long oldTopVer = Interlocked.Read(ref _topVer); List<IClusterNode> newNodes = null; DoOutInOp(OpNodes, writer => { writer.WriteLong(oldTopVer); }, input => { BinaryReader reader = Marshaller.StartUnmarshal(input); if (reader.ReadBoolean()) { // Topology has been updated. long newTopVer = reader.ReadLong(); newNodes = IgniteUtils.ReadNodes(reader, _pred); UpdateTopology(newTopVer, newNodes); } }); if (newNodes != null) return newNodes; // No topology changes. Debug.Assert(_nodes != null, "At least one topology update should have occurred."); return _nodes; } /// <summary> /// Perform synchronous out operation returning value. /// </summary> /// <param name="type">Operation type.</param> /// <param name="action">Action.</param> /// <returns>Native projection.</returns> private IUnmanagedTarget DoProjetionOutOp(int type, Action<BinaryWriter> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); action(writer); FinishMarshal(writer); return UU.ProjectionOutOpRet(Target, type, stream.SynchronizeOutput()); } } /** <inheritDoc /> */ public IBinaryType GetBinaryType(int typeId) { return DoOutInOp<IBinaryType>(OpMetadata, writer => writer.WriteInt(typeId), stream => { var reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new BinaryType(reader) : null; } ); } /// <summary> /// Gets metadata for all known types. /// </summary> public List<IBinaryType> GetBinaryTypes() { return DoInOp(OpAllMetadata, s => { var reader = Marshaller.StartUnmarshal(s); var size = reader.ReadInt(); var res = new List<IBinaryType>(size); for (var i = 0; i < size; i++) res.Add(reader.ReadBoolean() ? new BinaryType(reader) : null); return res; }); } /// <summary> /// Gets the schema. /// </summary> public int[] GetSchema(int typeId, int schemaId) { return DoOutInOp<int[]>(OpSchema, writer => { writer.WriteInt(typeId); writer.WriteInt(schemaId); }); } } }
using System; using System.Collections.Generic; using Umbraco.Core.Models; namespace Umbraco.Core.Services { /// <summary> /// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/> /// </summary> public interface IContentService : IService { /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IContent"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(int id); /// <summary> /// Gets an <see cref="IContent"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentOfContentType(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Content from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetByLevel(int level); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildren(int id); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects versions by its Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetVersions(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetRootContent(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForExpiration(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForRelease(); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentInRecycleBin(); /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="contentTypeId">Id of the <see cref="IContentType"/></param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteContentOfType(int contentTypeId, int userId = 0); /// <summary> /// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes a specific version from an <see cref="IContent"/> object. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin /// </summary> /// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void MoveToRecycleBin(IContent content, int userId = 0); /// <summary> /// Moves an <see cref="IContent"/> object to a new location /// </summary> /// <param name="content">The <see cref="IContent"/> to move</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="userId">Optional Id of the User moving the Content</param> void Move(IContent content, int parentId, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Rollback an <see cref="IContent"/> object to a previous version. /// This will create a new version, which is a copy of all the old data. /// </summary> /// <param name="id">Id of the <see cref="IContent"/>being rolled back</param> /// <param name="versionId">Id of the version to rollback to</param> /// <param name="userId">Optional Id of the User issueing the rollback of the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Rollback(int id, Guid versionId, int userId = 0); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by its name or partial name /// </summary> /// <param name="parentId">Id of the Parent to retrieve Children from</param> /// <param name="name">Full or partial name of the children</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildrenByName(int parentId, string name); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(IContent content); /// <summary> /// Gets a specific version of an <see cref="IContent"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetByVersion(Guid versionId); /// <summary> /// Gets the published version of an <see cref="IContent"/> item /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetPublishedVersion(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any published versions /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any published version otherwise False</returns> bool HasPublishedVersion(int id); /// <summary> /// Re-Publishes all Content /// </summary> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool RePublishAll(int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool Publish(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool PublishWithChildren(IContent content, int userId = 0); /// <summary> /// UnPublishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if unpublishing succeeded, otherwise False</returns> bool UnPublish(IContent content, int userId = 0); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Permanently deletes an <see cref="IContent"/> object. /// </summary> /// <remarks> /// This method will also delete associated media files, child content and possibly associated domains. /// </remarks> /// <remarks>Please note that this method will completely remove the Content from the database</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void Delete(IContent content, int userId = 0); /// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy which is returned. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0); /// <summary> /// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state. /// </summary> /// <param name="content"><see cref="IContent"/> to check if anscestors are published</param> /// <returns>True if the Content can be published, otherwise False</returns> bool IsPublishable(IContent content); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(IContent content); /// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <remarks> /// Using this method will ensure that the Published-state is maintained upon sorting /// so the cache is updated accordingly - as needed. /// </remarks> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(int id); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(IContent content); /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit.Abstractions; using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; public enum NodeFlags { None = 0, EmptyElement = 1, HasValue = 2, SingleQuote = 4, DefaultAttribute = 8, UnparsedEntities = 16, IsWhitespace = 32, DocumentRoot = 64, AttributeTextNode = 128, MixedContent = 256, Indent = 512 } abstract public class CXmlBase { protected XmlNodeType _nType; protected string _strName; protected string _strLocalName; protected string _strPrefix; protected string _strNamespace; internal int _nDepth; internal NodeFlags _eFlags = NodeFlags.None; internal CXmlBase _rNextNode = null; internal CXmlBase _rParentNode = null; internal CXmlBase _rFirstChildNode = null; internal CXmlBase _rLastChildNode = null; internal int _nChildNodes = 0; // // Constructors // public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace) { _strPrefix = strPrefix; _strName = strName; _strLocalName = strLocalName; _nType = NodeType; _strNamespace = strNamespace; } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace) : this(strPrefix, strName, strName, NodeType, strNamespace) { } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType) : this(strPrefix, strName, strName, NodeType, "") { } public CXmlBase(string strName, XmlNodeType NodeType) : this("", strName, strName, NodeType, "") { } // // Virtual Methods and Properties // abstract public void Write(XmlWriter rXmlWriter); abstract public void WriteXml(TextWriter rTW); abstract public string Value { get; } // // Public Methods and Properties // public string Name { get { return _strName; } } public string LocalName { get { return _strLocalName; } } public string Prefix { get { return _strPrefix; } } public string Namespace { get { return _strNamespace; } } public int Depth { get { return _nDepth; } } public XmlNodeType NodeType { get { return _nType; } } public NodeFlags Flags { get { return _eFlags; } } public int ChildNodeCount { get { return _nChildNodes; } } public void InsertNode(CXmlBase rNode) { if (_rFirstChildNode == null) { _rFirstChildNode = _rLastChildNode = rNode; } else { _rLastChildNode._rNextNode = rNode; _rLastChildNode = rNode; } if ((this._eFlags & NodeFlags.IsWhitespace) == 0) _nChildNodes++; rNode._rParentNode = this; } // // Internal Methods and Properties // internal CXmlBase _Child(int n) { int i; int j; CXmlBase rChild = _rFirstChildNode; for (i = 0, j = 0; rChild != null; i++, rChild = rChild._rNextNode) { if ((rChild._eFlags & NodeFlags.IsWhitespace) == 0) { if (j++ == n) break; } } return rChild; } internal CXmlBase _Child(string str) { CXmlBase rChild; for (rChild = _rFirstChildNode; rChild != null; rChild = rChild._rNextNode) if (rChild.Name == str) break; return rChild; } } public class CXmlAttribute : CXmlBase { // // Constructor // public CXmlAttribute(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { if (rXmlReader.IsDefault) _eFlags |= NodeFlags.DefaultAttribute; if (rXmlReader.QuoteChar == '\'') _eFlags |= NodeFlags.SingleQuote; } // // Public Methods and Properties (Override) // override public void Write(XmlWriter rXmlWriter) { CXmlBase rNode; if ((this._eFlags & NodeFlags.DefaultAttribute) == 0) { if (rXmlWriter is XmlTextWriter) ((XmlTextWriter)rXmlWriter).QuoteChar = this.Quote; rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace); for (rNode = this._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) { rNode.Write(rXmlWriter); } rXmlWriter.WriteEndAttribute(); } } override public void WriteXml(TextWriter rTW) { if ((this._eFlags & NodeFlags.DefaultAttribute) == 0) { CXmlBase rNode; rTW.Write(' ' + this.Name + '=' + this.Quote); for (rNode = this._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) { rNode.WriteXml(rTW); } rTW.Write(this.Quote); } } // // Public Methods and Properties // override public string Value { get { CXmlNode rNode; string strValue = string.Empty; for (rNode = (CXmlNode)this._rFirstChildNode; rNode != null; rNode = rNode.NextNode) strValue += rNode.Value; return strValue; } } public CXmlAttribute NextAttribute { get { return (CXmlAttribute)this._rNextNode; } } public char Quote { get { return ((base._eFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); } set { if (value == '\'') base._eFlags |= NodeFlags.SingleQuote; else base._eFlags &= ~NodeFlags.SingleQuote; } } public CXmlNode FirstChild { get { return (CXmlNode)base._rFirstChildNode; } } public CXmlNode Child(int n) { return (CXmlNode)base._Child(n); } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } } public class CXmlNode : CXmlBase { internal string _strValue = null; private CXmlAttribute _rFirstAttribute = null; private CXmlAttribute _rLastAttribute = null; private int _nAttributeCount = 0; // // Constructors // public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType) : base(strPrefix, strName, NodeType) { } public CXmlNode(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { _eFlags |= CXmlCache._eDefaultFlags; if (NodeType == XmlNodeType.Whitespace || NodeType == XmlNodeType.SignificantWhitespace) { _eFlags |= NodeFlags.IsWhitespace; } if (rXmlReader.IsEmptyElement) { _eFlags |= NodeFlags.EmptyElement; } if (rXmlReader.HasValue) { _eFlags |= NodeFlags.HasValue; _strValue = rXmlReader.Value; } } // // Public Methods and Properties (Override) // override public void Write(XmlWriter rXmlWriter) { CXmlBase rNode; CXmlAttribute rAttribute; string DocTypePublic = null; string DocTypeSystem = null; switch (this.NodeType) { case XmlNodeType.CDATA: rXmlWriter.WriteCData(this._strValue); break; case XmlNodeType.Comment: rXmlWriter.WriteComment(this._strValue); break; case XmlNodeType.DocumentType: for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == "PUBLIC") { DocTypePublic = rAttribute.Value; } if (rAttribute.Name == "SYSTEM") { DocTypeSystem = rAttribute.Value; } } rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, this._strValue); break; case XmlNodeType.EntityReference: rXmlWriter.WriteEntityRef(this.Name); break; case XmlNodeType.ProcessingInstruction: rXmlWriter.WriteProcessingInstruction(this.Name, this._strValue); break; case XmlNodeType.Text: if (this.Name == string.Empty) { if ((this.Flags & NodeFlags.UnparsedEntities) == 0) { rXmlWriter.WriteString(this._strValue); } else { rXmlWriter.WriteRaw(this._strValue.ToCharArray(), 0, this._strValue.Length); } } else { if (this._strName[0] == '#') rXmlWriter.WriteCharEntity(this._strValue[0]); else rXmlWriter.WriteEntityRef(this.Name); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if ((this._rParentNode._eFlags & NodeFlags.DocumentRoot) != 0) rXmlWriter.WriteRaw(this._strValue.ToCharArray(), 0, this._strValue.Length); else rXmlWriter.WriteString(this._strValue); break; case XmlNodeType.Element: rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null); for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.Write(rXmlWriter); } if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteString(string.Empty); for (rNode = base._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) { rNode.Write(rXmlWriter); } // Should only produce empty tag if the original document used empty tag if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteFullEndElement(); else rXmlWriter.WriteEndElement(); break; case XmlNodeType.XmlDeclaration: rXmlWriter.WriteRaw("<?xml " + this._strValue + "?>"); break; default: throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString())); } } override public void WriteXml(TextWriter rTW) { string strXml; CXmlAttribute rAttribute; CXmlBase rNode; switch (this._nType) { case XmlNodeType.Text: if (this._strName == "") { rTW.Write(this._strValue); } else { if (this._strName.StartsWith("#")) { rTW.Write("&" + Convert.ToString(Convert.ToInt32(this._strValue[0])) + ";"); } else { rTW.Write("&" + this.Name + ";"); } } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.DocumentType: rTW.Write(this._strValue); break; case XmlNodeType.Element: strXml = this.Name; rTW.Write('<' + strXml); //Put in all the Attributes for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.WriteXml(rTW); } //If there is children, put those in, otherwise close the tag. if ((base._eFlags & NodeFlags.EmptyElement) == 0) { rTW.Write('>'); for (rNode = base._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) { rNode.WriteXml(rTW); } rTW.Write("</" + strXml + ">"); } else { rTW.Write(" />"); } break; case XmlNodeType.EntityReference: rTW.Write("&" + this._strName + ";"); break; case XmlNodeType.Notation: rTW.Write("<!NOTATION " + this._strValue + ">"); break; case XmlNodeType.CDATA: rTW.Write("<![CDATA[" + this._strValue + "]]>"); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: rTW.Write("<?" + this._strName + " " + this._strValue + "?>"); break; case XmlNodeType.Comment: rTW.Write("<!--" + this._strValue + "-->"); break; default: throw (new Exception("Unhandled NodeType " + this._nType.ToString())); } } // // Public Methods and Properties // public string NodeValue { get { return _strValue; } } override public string Value { get { string strValue = ""; CXmlNode rChild; if ((this._eFlags & NodeFlags.HasValue) != 0) { char chEnt; int nIndexAmp = 0; int nIndexSem = 0; if ((this._eFlags & NodeFlags.UnparsedEntities) == 0) return this._strValue; strValue = this._strValue; while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1) { nIndexSem = strValue.IndexOf(';', nIndexAmp); chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1)); if (chEnt != char.MinValue) { strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1); nIndexAmp++; } else nIndexAmp = nIndexSem; } return strValue; } for (rChild = (CXmlNode)this._rFirstChildNode; rChild != null; rChild = (CXmlNode)rChild._rNextNode) { strValue = strValue + rChild.Value; } return strValue; } } public CXmlNode NextNode { get { CXmlBase rNode = this._rNextNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode._rNextNode; return (CXmlNode)rNode; } } public CXmlNode FirstChild { get { CXmlBase rNode = this._rFirstChildNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode._rNextNode; return (CXmlNode)rNode; } } public CXmlNode Child(int n) { int i; CXmlNode rChild; i = 0; for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode) if (i++ == n) break; return rChild; } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } public int Type { get { return Convert.ToInt32(base._nType); } } public CXmlAttribute FirstAttribute { get { return _rFirstAttribute; } } public int AttributeCount { get { return _nAttributeCount; } } public CXmlAttribute Attribute(int n) { int i; CXmlAttribute rAttribute; i = 0; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) if (i++ == n) break; return rAttribute; } public CXmlAttribute Attribute(string str) { CXmlAttribute rAttribute; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == str) break; } return rAttribute; } public void AddAttribute(CXmlAttribute rAttribute) { if (_rFirstAttribute == null) { _rFirstAttribute = rAttribute; } else { _rLastAttribute._rNextNode = rAttribute; } _rLastAttribute = rAttribute; _nAttributeCount++; } private char ResolveCharEntity(string strName) { if (strName[0] == '#') if (strName[1] == 'x') return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16)); else return Convert.ToChar(Convert.ToInt32(strName.Substring(1))); if (strName == "lt") return '<'; if (strName == "gt") return '>'; if (strName == "amp") return '&'; if (strName == "apos") return '\''; if (strName == "quot") return '"'; return char.MinValue; } } public class CXmlCache { //CXmlCache Properties private bool _fTrace = false; private bool _fThrow = true; private bool _fReadNode = true; private int _hr = 0; private Encoding _eEncoding = System.Text.Encoding.UTF8; private string _strParseError = ""; //XmlReader Properties #pragma warning disable 0618 private ValidationType _eValidationMode = ValidationType.Auto; #pragma warning restore 0618 private WhitespaceHandling _eWhitespaceMode = WhitespaceHandling.None; private EntityHandling _eEntityMode = EntityHandling.ExpandEntities; private bool _fNamespaces = true; private bool _fValidationCallback = false; private bool _fExpandAttributeValues = false; //Internal stuff protected XmlReader _rXmlReader = null; protected CXmlNode _rDocumentRootNode; protected CXmlNode _rRootNode = null; internal static NodeFlags _eDefaultFlags = NodeFlags.None; private ITestOutputHelper _output; public CXmlCache(ITestOutputHelper output) { _output = output; } // // Constructor // public CXmlCache() { } // // Public Methods and Properties // public virtual bool Load(XmlReader rXmlReader) { //Hook up your reader as my reader _rXmlReader = rXmlReader; if (rXmlReader is XmlTextReader) { _eWhitespaceMode = ((XmlTextReader)rXmlReader).WhitespaceHandling; _fNamespaces = ((XmlTextReader)rXmlReader).Namespaces; _eValidationMode = ValidationType.None; } #pragma warning disable 0618 if (rXmlReader is XmlValidatingReader) { if (((XmlValidatingReader)rXmlReader).Reader is XmlTextReader) { _eWhitespaceMode = ((XmlTextReader)((XmlValidatingReader)rXmlReader).Reader).WhitespaceHandling; } else { _eWhitespaceMode = WhitespaceHandling.None; } _fNamespaces = ((XmlValidatingReader)rXmlReader).Namespaces; _eValidationMode = ((XmlValidatingReader)rXmlReader).ValidationType; _eEntityMode = ((XmlValidatingReader)rXmlReader).EntityHandling; } #pragma warning restore 0618 DebugTrace("Setting ValidationMode=" + _eValidationMode.ToString()); DebugTrace("Setting EntityMode=" + _eEntityMode.ToString()); DebugTrace("Setting WhitespaceMode=" + _eWhitespaceMode.ToString()); //Process the Document try { _rDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element); _rDocumentRootNode._eFlags = NodeFlags.DocumentRoot | NodeFlags.Indent; Process(_rDocumentRootNode); for (_rRootNode = _rDocumentRootNode.FirstChild; _rRootNode != null && _rRootNode.NodeType != XmlNodeType.Element; _rRootNode = _rRootNode.NextNode) ; } catch (Exception e) { //Unhook your reader _rXmlReader = null; _strParseError = e.ToString(); if (_fThrow) { throw (e); } if (_hr == 0) _hr = -1; return false; } //Unhook your reader _rXmlReader = null; return true; } public bool Load(string strFileName) { #pragma warning disable 0618 XmlTextReader rXmlTextReader; XmlValidatingReader rXmlValidatingReader; bool fRet; rXmlTextReader = new XmlTextReader(strFileName); rXmlTextReader.WhitespaceHandling = _eWhitespaceMode; rXmlTextReader.Namespaces = _fNamespaces; _eEncoding = rXmlTextReader.Encoding; rXmlValidatingReader = new XmlValidatingReader(rXmlTextReader); rXmlValidatingReader.ValidationType = _eValidationMode; rXmlValidatingReader.EntityHandling = _eEntityMode; #pragma warning restore 0618 if (_fValidationCallback) rXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallback); try { fRet = Load((XmlReader)rXmlValidatingReader); } catch (Exception e) { fRet = false; rXmlValidatingReader.Dispose(); rXmlTextReader.Dispose(); if (_strParseError == string.Empty) _strParseError = e.ToString(); if (_fThrow) throw (e); } rXmlValidatingReader.Dispose(); rXmlTextReader.Dispose(); return fRet; } public void Save(string strName) { Save(strName, false, _eEncoding); } public void Save(string strName, bool fOverWrite) { Save(strName, fOverWrite, _eEncoding); } public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding) { CXmlBase rNode; XmlTextWriter rXmlTextWriter = null; try { if (fOverWrite) { File.Delete(strName); } rXmlTextWriter = new XmlTextWriter(strName, Encoding); rXmlTextWriter.Namespaces = _fNamespaces; for (rNode = _rDocumentRootNode._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) { rNode.Write(rXmlTextWriter); } rXmlTextWriter.Dispose(); } catch (Exception e) { DebugTrace(e.ToString()); if (rXmlTextWriter != null) rXmlTextWriter.Dispose(); throw (e); } } public void WriteXml(TextWriter rTW) { CXmlBase rNode; //Spit out the document for (rNode = _rDocumentRootNode._rFirstChildNode; rNode != null; rNode = rNode._rNextNode) rNode.WriteXml(rTW); } public CXmlNode RootNode { get { return _rRootNode; } } public string ParseError { get { return _strParseError; } } public int ParseErrorCode { get { return _hr; } } // // XmlReader Properties // public string EntityMode { set { if (value == "ExpandEntities") _eEntityMode = EntityHandling.ExpandEntities; else if (value == "ExpandCharEntities") _eEntityMode = EntityHandling.ExpandCharEntities; else throw (new Exception("Invalid Entity mode.")); } get { return _eEntityMode.ToString(); } } public string ValidationMode { set { #pragma warning disable 0618 if (value == "None") _eValidationMode = ValidationType.None; else if (value == "DTD") _eValidationMode = ValidationType.DTD; else if (value == "XDR") _eValidationMode = ValidationType.XDR; else if (value == "Schema") _eValidationMode = ValidationType.Schema; else if (value == "Auto") _eValidationMode = ValidationType.Auto; else throw (new Exception("Invalid Validation mode.")); #pragma warning restore 0618 } get { return _eValidationMode.ToString(); } } public string WhitespaceMode { set { if (value == "All") _eWhitespaceMode = WhitespaceHandling.All; else if (value == "Significant") _eWhitespaceMode = WhitespaceHandling.Significant; else if (value == "None") _eWhitespaceMode = WhitespaceHandling.None; else throw (new Exception("Invalid Whitespace mode.")); } get { return _eWhitespaceMode.ToString(); } } public bool Namespaces { set { _fNamespaces = value; } get { return _fNamespaces; } } public bool UseValidationCallback { set { _fValidationCallback = value; } get { return _fValidationCallback; } } public bool ExpandAttributeValues { set { _fExpandAttributeValues = value; } get { return _fExpandAttributeValues; } } // // Internal Properties // public bool Throw { get { return _fThrow; } set { _fThrow = value; } } public bool Trace { set { _fTrace = value; } get { return _fTrace; } } // //Private Methods // private void DebugTrace(string str) { DebugTrace(str, 0); } private void DebugTrace(string str, int nDepth) { if (_fTrace) { int i; for (i = 0; i < nDepth; i++) _output.WriteLine(" "); _output.WriteLine(str); } } private void DebugTrace(XmlReader rXmlReader) { if (_fTrace) { string str; str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name="; if (rXmlReader.Prefix != "") { str += rXmlReader.Prefix + ":"; } str += rXmlReader.LocalName; if (rXmlReader.HasValue) str += " Value=" + rXmlReader.Value; if (rXmlReader.NodeType == XmlNodeType.Attribute) str += " QuoteChar=" + rXmlReader.QuoteChar; DebugTrace(str, rXmlReader.Depth); } } protected void Process(CXmlBase rParentNode) { CXmlNode rNewNode; while (true) { //We want to pop if Read() returns false, aka EOF if (_fReadNode) { if (!_rXmlReader.Read()) { DebugTrace("Read() == false"); return; } } else { if (!_rXmlReader.ReadAttributeValue()) { DebugTrace("ReadAttributeValue() == false"); return; } } DebugTrace(_rXmlReader); //We also want to pop if we get an EndElement or EndEntity if (_rXmlReader.NodeType == XmlNodeType.EndElement || _rXmlReader.NodeType == XmlNodeType.EndEntity) { DebugTrace("NodeType == EndElement or EndEntity"); return; } rNewNode = GetNewNode(_rXmlReader); rNewNode._nDepth = _rXmlReader.Depth; // Test for MixedContent and set Indent if necessary if ((rParentNode.Flags & NodeFlags.MixedContent) != 0) { rNewNode._eFlags |= NodeFlags.MixedContent; // Indent is off for all new nodes } else { rNewNode._eFlags |= NodeFlags.Indent; // Turn on Indent for current Node } // Set all Depth 0 nodes to No Mixed Content and Indent True if (_rXmlReader.Depth == 0) { rNewNode._eFlags |= NodeFlags.Indent; // Turn on Indent rNewNode._eFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent } rParentNode.InsertNode(rNewNode); //Do some special stuff based on NodeType switch (_rXmlReader.NodeType) { case XmlNodeType.EntityReference: if (_eValidationMode == ValidationType.DTD) { _rXmlReader.ResolveEntity(); Process(rNewNode); } break; case XmlNodeType.Element: if (_rXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(_rXmlReader); rNewNode.AddAttribute(rNewAttribute); if (_fExpandAttributeValues) { DebugTrace("Attribute: " + _rXmlReader.Name); _fReadNode = false; Process(rNewAttribute); _fReadNode = true; } else { CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text); rValueNode._eFlags = _eDefaultFlags | NodeFlags.HasValue; rValueNode._strValue = _rXmlReader.Value; DebugTrace(" Value=" + rValueNode.Value, _rXmlReader.Depth + 1); rNewAttribute.InsertNode(rValueNode); } } while (_rXmlReader.MoveToNextAttribute()); } if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0) Process(rNewNode); break; case XmlNodeType.XmlDeclaration: if (_rXmlReader is XmlTextReader) { _eEncoding = ((XmlTextReader)_rXmlReader).Encoding; } #pragma warning disable 0618 else if (_rXmlReader is XmlValidatingReader) { _eEncoding = ((XmlValidatingReader)_rXmlReader).Encoding; } #pragma warning restore 0618 else { string strValue = rNewNode.NodeValue; int nPos = strValue.IndexOf("encoding"); if (nPos != -1) { int nEnd; nPos = strValue.IndexOf("=", nPos); //Find the = sign nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign { nEnd = strValue.IndexOf("'", nPos); } else { nPos = nEnd; nEnd = strValue.IndexOf("\"", nPos); } string sEncodeName = strValue.Substring(nPos, nEnd - nPos); DebugTrace("XMLDecl contains encoding " + sEncodeName); if (sEncodeName.ToUpper() == "UCS-2") { sEncodeName = "unicode"; } _eEncoding = System.Text.Encoding.GetEncoding(sEncodeName); } } break; case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Text: if (!_fReadNode) { rNewNode._eFlags = _eDefaultFlags | NodeFlags.AttributeTextNode; } rNewNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode._eFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: rNewNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode._eFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Comment: case XmlNodeType.Notation: break; case XmlNodeType.DocumentType: if (_rXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(_rXmlReader); rNewNode.AddAttribute(rNewAttribute); CXmlNode rValueNode = new CXmlNode(_rXmlReader); rValueNode._strValue = _rXmlReader.Value; rNewAttribute.InsertNode(rValueNode); } while (_rXmlReader.MoveToNextAttribute()); } break; default: _output.WriteLine("UNHANDLED TYPE, " + _rXmlReader.NodeType.ToString() + " IN Process()!"); break; } } } protected virtual CXmlNode GetNewNode(XmlReader rXmlReader) { return new CXmlNode(rXmlReader); } private void ValidationCallback(object sender, ValidationEventArgs args) { // commented by ROCHOA -- don't know where ValidationEventArgs comes from // _hr = Convert.ToInt16(args.ErrorCode); throw (new Exception("[" + Convert.ToString(_hr) + "] " + args.Message)); } } public class ChecksumWriter : TextWriter { private int _nPosition = 0; private decimal _dResult = 0; private Encoding _encoding; // -------------------------------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------------------------------- public ChecksumWriter() { _encoding = Encoding.UTF8; } // -------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------- public decimal CheckSum { get { return _dResult; } } public override Encoding Encoding { get { return _encoding; } } // -------------------------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------------------------- override public void Write(string str) { int i; int m; m = str.Length; for (i = 0; i < m; i++) { Write(str[i]); } } override public void Write(char[] rgch) { int i; int m; m = rgch.Length; for (i = 0; i < m; i++) { Write(rgch[i]); } } override public void Write(char[] rgch, int iOffset, int iCount) { int i; int m; m = iOffset + iCount; for (i = iOffset; i < m; i++) { Write(rgch[i]); } } override public void Write(char ch) { _dResult += Math.Round((decimal)(ch / (_nPosition + 1.0)), 10); _nPosition++; } override public void Close() { _nPosition = 0; _dResult = 0; } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.DataTransfer; using Windows.ApplicationModel.DataTransfer.ShareTarget; using Windows.Data.Json; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI; using Windows.UI.Core; using Windows.UI.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using SDKTemplate; using Windows.Security.EnterpriseData; namespace EdpSample { public sealed partial class Scenario14_ShareTarget : Page { private MainPage rootPage; ShareOperation m_shareOperation; private string m_sharedDataTitle; private string m_sharedDataDescription; private string m_sharedDataPackageFamilyName; private Uri m_sharedDataContentSourceWebLink; private Uri m_sharedDataContentSourceApplicationLink; private Color m_sharedDataLogoBackgroundColor; private IRandomAccessStreamReference m_sharedDataSquare30x30Logo; private string shareQuickLinkId; private string m_sharedText; private Uri m_sharedWebLink; private Uri m_sharedApplicationLink; private IReadOnlyList<IStorageItem> m_sharedStorageItems; private string m_sharedCustomData; private string m_sharedHtmlFormat; private IReadOnlyDictionary<string, RandomAccessStreamReference> m_sharedResourceMap; private IRandomAccessStreamReference m_sharedBitmapStreamRef; private IRandomAccessStreamReference m_sharedThumbnailStreamRef; private const string dataFormatName = "http://schema.org/Book"; public Scenario14_ShareTarget() { this.InitializeComponent(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // It is recommended to only retrieve the m_shareOperation object in the activation handler, return as // quickly as possible, and retrieve all data from the share target asynchronously. m_shareOperation = (ShareOperation)e.Parameter; await Task.Factory.StartNew(async () => { // Retrieve the data package properties. m_sharedDataTitle = m_shareOperation.Data.Properties.Title; m_sharedDataDescription = m_shareOperation.Data.Properties.Description; m_sharedDataPackageFamilyName = m_shareOperation.Data.Properties.PackageFamilyName; m_sharedDataContentSourceWebLink = m_shareOperation.Data.Properties.ContentSourceWebLink; m_sharedDataContentSourceApplicationLink = m_shareOperation.Data.Properties.ContentSourceApplicationLink; m_sharedDataLogoBackgroundColor = m_shareOperation.Data.Properties.LogoBackgroundColor; m_sharedDataSquare30x30Logo = m_shareOperation.Data.Properties.Square30x30Logo; m_sharedThumbnailStreamRef = m_shareOperation.Data.Properties.Thumbnail; shareQuickLinkId = m_shareOperation.QuickLinkId; // Retrieve the data package content. // The GetWebLinkAsync(), GetTextAsync(), GetStorageItemsAsync(), etc. APIs will throw if there was an error retrieving the data from the source app. // In this sample, we just display the error. It is recommended that a share target app handles these in a way appropriate for that particular app. if (m_shareOperation.Data.Contains(StandardDataFormats.WebLink)) { try { m_sharedWebLink = await m_shareOperation.Data.GetWebLinkAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(StandardDataFormats.ApplicationLink)) { try { m_sharedApplicationLink = await m_shareOperation.Data.GetApplicationLinkAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(StandardDataFormats.Text)) { try { m_sharedText = await m_shareOperation.Data.GetTextAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(StandardDataFormats.StorageItems)) { try { m_sharedStorageItems = await m_shareOperation.Data.GetStorageItemsAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(dataFormatName)) { try { m_sharedCustomData = await m_shareOperation.Data.GetTextAsync(dataFormatName); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(StandardDataFormats.Html)) { try { m_sharedHtmlFormat = await m_shareOperation.Data.GetHtmlFormatAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage); } try { m_sharedResourceMap = await m_shareOperation.Data.GetResourceMapAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage); } } if (m_shareOperation.Data.Contains(StandardDataFormats.Bitmap)) { try { m_sharedBitmapStreamRef = await m_shareOperation.Data.GetBitmapAsync(); } catch (Exception ex) { NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage); } } // In this sample, we just display the m_shared data content. // Get back to the UI thread using the dispatcher. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { DataPackageTitle.Text = m_sharedDataTitle; DataPackageDescription.Text = m_sharedDataDescription; DataPackagePackageFamilyName.Text = m_sharedDataPackageFamilyName; if (m_sharedDataContentSourceWebLink != null) { DataPackageContentSourceWebLink.Text = m_sharedDataContentSourceWebLink.AbsoluteUri; } if (m_sharedDataContentSourceApplicationLink != null) { DataPackageContentSourceApplicationLink.Text = m_sharedDataContentSourceApplicationLink.AbsoluteUri; } if (m_sharedDataSquare30x30Logo != null) { IRandomAccessStreamWithContentType logoStream = await m_sharedDataSquare30x30Logo.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(logoStream); LogoHolder.Source = bitmapImage; LogoBackground.Background = new SolidColorBrush(m_sharedDataLogoBackgroundColor); LogoArea.Visibility = Visibility.Visible; } if (!String.IsNullOrEmpty(m_shareOperation.QuickLinkId)) { SelectedQuickLinkId.Text = shareQuickLinkId; } if (m_sharedThumbnailStreamRef != null) { IRandomAccessStreamWithContentType thumbnailStream = await m_sharedThumbnailStreamRef.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumbnailStream); ThumbnailHolder.Source = bitmapImage; ThumbnailArea.Visibility = Visibility.Visible; } if (m_sharedWebLink != null) { AddContentValue("WebLink: ", m_sharedWebLink.AbsoluteUri); } if (m_sharedApplicationLink != null) { AddContentValue("ApplicationLink: ", m_sharedApplicationLink.AbsoluteUri); } if (m_sharedText != null) { AddContentValue("Text: ", m_sharedText); } if (m_sharedStorageItems != null) { // Display the name of the files being m_shared. StringBuilder fileNames = new StringBuilder(); for (int index = 0; index < m_sharedStorageItems.Count; index++) { fileNames.Append(m_sharedStorageItems[index].Name); if (index < m_sharedStorageItems.Count - 1) { fileNames.Append(", "); } } fileNames.Append("."); AddContentValue("StorageItems: ", fileNames.ToString()); } if (m_sharedCustomData != null) { // This is an area to be especially careful parsing data from the source app to avoid buffer overruns. // This sample doesn't perform data validation but will catch any exceptions thrown. try { StringBuilder receivedStrings = new StringBuilder(); JsonObject customObject = JsonObject.Parse(m_sharedCustomData); if (customObject.ContainsKey("type")) { if (customObject["type"].GetString() == "http://schema.org/Book") { // This sample expects the custom format to be of type http://schema.org/Book receivedStrings.AppendLine("Type: " + customObject["type"].Stringify()); JsonObject properties = customObject["properties"].GetObject(); receivedStrings.AppendLine("Image: " + properties["image"].Stringify()); receivedStrings.AppendLine("Name: " + properties["name"].Stringify()); receivedStrings.AppendLine("Book Format: " + properties["bookFormat"].Stringify()); receivedStrings.AppendLine("Author: " + properties["author"].Stringify()); receivedStrings.AppendLine("Number of Pages: " + properties["numberOfPages"].Stringify()); receivedStrings.AppendLine("Publisher: " + properties["publisher"].Stringify()); receivedStrings.AppendLine("Date Published: " + properties["datePublished"].Stringify()); receivedStrings.AppendLine("In Language: " + properties["inLanguage"].Stringify()); receivedStrings.Append("ISBN: " + properties["isbn"].Stringify()); AddContentValue("Custom format data:" + Environment.NewLine, receivedStrings.ToString()); } else { rootPage.NotifyUser("The custom format from the source app is not of type http://schema.org/Book", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("The custom format from the source app doesn't contain a type", NotifyType.ErrorMessage); } } catch (Exception ex) { rootPage.NotifyUser("Failed to parse the custom data - " + ex.Message, NotifyType.ErrorMessage); } } if (m_sharedHtmlFormat != null) { string htmlFragment = HtmlFormatHelper.GetStaticFragment(m_sharedHtmlFormat); if (!String.IsNullOrEmpty(htmlFragment)) { AddContentValue("HTML: "); ShareWebView.Visibility = Visibility.Visible; ShareWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>"); } else { rootPage.NotifyUser("GetStaticFragment failed to parse the HTML from the source app", NotifyType.ErrorMessage); } // Check if there are any local images in the resource map. if (m_sharedResourceMap.Count > 0) { //ResourceMapValue.Text = ""; foreach (KeyValuePair<string, RandomAccessStreamReference> item in m_sharedResourceMap) { ResourceMapValue.Text += "\nKey: " + item.Key; } ResourceMapArea.Visibility = Visibility.Visible; } } if (m_sharedBitmapStreamRef != null) { IRandomAccessStreamWithContentType bitmapStream = await m_sharedBitmapStreamRef.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(bitmapStream); ImageHolder.Source = bitmapImage; ImageArea.Visibility = Visibility.Visible; } }); }); } private void QuickLinkSectionLabel_Tapped(object sender, TappedRoutedEventArgs e) { // Trigger the appropriate Checked/Unchecked event if the user taps on the text instead of the checkbox. AddQuickLink.IsChecked = !AddQuickLink.IsChecked; } private void AddQuickLink_Checked(object sender, RoutedEventArgs e) { QuickLinkCustomization.Visibility = Visibility.Visible; } private void AddQuickLink_Unchecked(object sender, RoutedEventArgs e) { QuickLinkCustomization.Visibility = Visibility.Collapsed; } async void ReportCompleted_Click(object sender, RoutedEventArgs e) { if (AddQuickLink.IsChecked.Equals(true)) { QuickLink quickLinkInfo = new QuickLink { Id = QuickLinkId.Text, Title = QuickLinkTitle.Text, // For QuickLinks, the supported FileTypes and DataFormats are set independently from the manifest. SupportedFileTypes = { "*" }, SupportedDataFormats = { StandardDataFormats.Text, StandardDataFormats.WebLink, StandardDataFormats.ApplicationLink, StandardDataFormats.Bitmap, StandardDataFormats.StorageItems, StandardDataFormats.Html, dataFormatName } }; try { StorageFile iconFile = await Package.Current.InstalledLocation.CreateFileAsync("assets\\user.png", CreationCollisionOption.OpenIfExists); quickLinkInfo.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile); m_shareOperation.ReportCompleted(quickLinkInfo); } catch (Exception) { // Even if the QuickLink cannot be created it is important to call ReportCompleted. Otherwise, if this is a long-running share, // the app will stick around in the long-running share progress list. m_shareOperation.ReportCompleted(); throw; } } else { m_shareOperation.ReportCompleted(); } } private void DismissUI_Click(object sender, RoutedEventArgs e) { m_shareOperation.DismissUI(); } private void LongRunningShareLabel_Tapped(object sender, TappedRoutedEventArgs e) { // Trigger the appropriate Checked/Unchecked event if the user taps on the text instead of the checkbox. ExpandLongRunningShareSection.IsChecked = !ExpandLongRunningShareSection.IsChecked; } private void ExpandLongRunningShareSection_Checked(object sender, RoutedEventArgs e) { ExtendedSharingArea.Visibility = Visibility.Visible; } private void ExpandLongRunningShareSection_Unchecked(object sender, RoutedEventArgs e) { ExtendedSharingArea.Visibility = Visibility.Collapsed; } private void ReportStarted_Click(object sender, RoutedEventArgs e) { m_shareOperation.ReportStarted(); rootPage.NotifyUser("Started...", NotifyType.StatusMessage); } private void ReportDataRetrieved_Click(object sender, RoutedEventArgs e) { m_shareOperation.ReportDataRetrieved(); rootPage.NotifyUser("Data retrieved...", NotifyType.StatusMessage); } private void ReportSubmittedBackgroundTask_Click(object sender, RoutedEventArgs e) { m_shareOperation.ReportSubmittedBackgroundTask(); rootPage.NotifyUser("Submitted background task...", NotifyType.StatusMessage); } private void ReportErrorButton_Click(object sender, RoutedEventArgs e) { m_shareOperation.ReportError(ReportError.Text); } async private void NotifyUserBackgroundThread(string message, NotifyType type) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(message, type); }); } private void AddContentValue(string title, string description = null) { Run contentType = new Run(); contentType.FontWeight = FontWeights.Bold; contentType.Text = title; ContentValue.Inlines.Add(contentType); if (description != null) { Run contentValue = new Run(); contentValue.Text = description + Environment.NewLine; ContentValue.Inlines.Add(contentValue); } } } }
using System; using System.Windows.Forms; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.Events; namespace GuruComponents.Netrix { /// <summary> /// Handles basic events for editing purposes. /// </summary> class EditPanel : Panel { private HtmlEditor editor; public EditPanel() : base() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); } public void SetEditor(IHtmlEditor editor) { this.editor = (HtmlEditor)editor; } /// <summary> /// Checks out when we want to handle the TAB key internally. /// </summary> private bool ShouldHandleTAB { get { Interop.IHTMLElement scopeElement = editor.CurrentScopeElement; // LI TAB if (editor.HandleTAB && (scopeElement != null && scopeElement.GetTagName() == "LI")) { return true; } if (editor.HandleTAB) { return true; } return false; } } /// <internalonly/> protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: case Keys.Up | Keys.Shift: case Keys.Down | Keys.Shift: case Keys.Left | Keys.Shift: case Keys.Right | Keys.Shift: case Keys.Up | Keys.Control: case Keys.Down | Keys.Control: case Keys.Left | Keys.Control: case Keys.Right | Keys.Control: return true; } // Optionally we process the TAB Key only, if the property is turned on if (keyData == Keys.Tab && ShouldHandleTAB) { return true; } return base.ProcessCmdKey(ref msg, keyData); } /// <internalonly/> protected override bool IsInputKey(Keys keyData) { if (editor.InternalShortcutKeys) { switch (keyData) { case Keys.A | Keys.Control: //Select All case Keys.C | Keys.Control: //Copy case Keys.P | Keys.Control: //Print case Keys.OemOpenBrackets | Keys.Control: //Outdent case Keys.OemCloseBrackets | Keys.Control: //Indent case Keys.B | Keys.Control: //Bold case Keys.I | Keys.Control: //Italic case Keys.U | Keys.Control: //Underline case Keys.L | Keys.Control: //Left Justify case Keys.J | Keys.Control: //Center Justify case Keys.R | Keys.Control: //Right Justify case Keys.V | Keys.Control: //Paste case Keys.X | Keys.Control: //Cut case Keys.Y | Keys.Control: //Redo case Keys.Z | Keys.Control: //Undo return true; } } // Optionally we process the TAB Key only, if the property is turned on if (keyData == Keys.Tab && ShouldHandleTAB) { return true; } return base.IsInputKey(keyData); } /// <internalonly/> public override bool PreProcessMessage(ref Message msg) { Keys k = (Keys)msg.WParam.ToInt32(); bool handled = false; // Look for internal processed Shortcut key on Key down. if (msg.Msg == 256) { handled = DoShortCut(k); } // After internal processing add modifiers for simplified checks k |= ModifierKeys; // Special Support for Keys in Design Mode if (editor.DesignModeEnabled) { if (k == Keys.Tab && ShouldHandleTAB && msg.Msg == 256) { base.PreProcessMessage(ref msg); Interop.IHTMLElement scopeElement = editor.CurrentScopeElement; switch (scopeElement.GetTagName()) { case "LI": editor.TextFormatting.Indent(); break; } return false; } } // Special Support for Keys in Browse Mode else { if (!handled) // && editor.HtmlEditorSite!= null) { handled = editor.MshtmlSite.PreTranslateMessage(msg); } } if (!handled && msg.Msg == 256) { switch (k) { case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: case Keys.Up | Keys.Shift: case Keys.Down | Keys.Shift: case Keys.Left | Keys.Shift: case Keys.Right | Keys.Shift: case Keys.Up | Keys.Control: case Keys.Down | Keys.Control: case Keys.Left | Keys.Control: case Keys.Right | Keys.Control: break; case Keys.Enter: if (editor.TransposeEnterBehavior) { editor.CreateElementAtCaret("br"); handled = true; } break; case Keys.Enter | Keys.Shift: if (editor.TransposeEnterBehavior) { if (editor.BlockDefault == BlockDefaultType.P) editor.Exec(Interop.IDM.PARAGRAPH); else editor.Exec(Interop.IDM.DIV); handled = true; } break; default: bool baseHandler = false; if ((ModifierKeys & Keys.Control) != 0) { baseHandler = true; } if ((ModifierKeys & Keys.Alt) != 0) { baseHandler = true; } if ((((ModifierKeys & Keys.Control) != 0) || ((ModifierKeys & Keys.Alt) != 0) && (ModifierKeys & Keys.Shift) != 0)) { baseHandler = true; } if (k == Keys.Tab) { baseHandler = true; } if (((k & ~Keys.Shift) == Keys.Tab) && (k & Keys.Shift) == Keys.Shift) { baseHandler = true; } if ((k >= Keys.F1 && k <= Keys.F24) && !((msg.Msg & 2) == 2)) { baseHandler = true; } if (baseHandler) { handled = base.PreProcessMessage(ref msg); } break; } } if (!handled && msg.Msg > 256 && (ModifierKeys & Keys.Alt) != 0) { handled = base.PreProcessMessage(ref msg); } return handled; } /// <summary> /// Executes the short cut keys that should be available and handles all of the cases of design mode versus not. /// </summary> /// <param name="Key">The key to process.</param> /// <returns>If the key was handled succesfully, return true, otherwise return false.</returns> private bool DoShortCut(Keys Key) { try { if ((ModifierKeys & Keys.Control) != 0 && (ModifierKeys & Keys.Shift) == 0 && (ModifierKeys & Keys.Alt) == 0 ) { //fire the BeforeShortcut event and cancel if necessary BeforeShortcutEventArgs e = new BeforeShortcutEventArgs(Key); editor.InvokeBeforeShortcut(e); if (e.Cancel) return true; bool Done = false; // Do no processing if globally turned off if (!editor.InternalShortcutKeys) return false; // process keys internally switch (Key) { case Keys.A: //Select All editor.TextFormatting.SelectAll(); Done = true; break; case Keys.C: //Copy editor.Copy(); Done = true; break; case Keys.P: //Print editor.PrintImmediately(); Done = true; break; } if (editor.DesignModeEnabled) { //Only do the keys that work in design mode. switch (Key) { case Keys.OemOpenBrackets: //Outdent editor.TextFormatting.UnIndent(); Done = true; break; case Keys.OemCloseBrackets: //Indent editor.TextFormatting.Indent(); Done = true; break; case Keys.B: //Bold editor.TextFormatting.ToggleBold(); Done = true; // true; break; case Keys.I: //Italic editor.TextFormatting.ToggleItalics(); Done = true; break; case Keys.U: //Underline editor.TextFormatting.ToggleUnderline(); Done = true; break; case Keys.L: //Left Justify editor.TextFormatting.SetAlignment(Alignment.Left); Done = true; break; case Keys.J: //Center Justify editor.TextFormatting.SetAlignment(Alignment.Full); Done = true; break; case Keys.R: //Right Justify editor.TextFormatting.SetAlignment(Alignment.Right); Done = true; break; case Keys.V: //Paste editor.Paste(); Done = true; break; case Keys.X: //Cut editor.Cut(); Done = true; break; case Keys.Y: //Redo editor.Redo(); Done = true; break; case Keys.Z: //Undo editor.Undo(); Done = true; break; } } return Done; } else { return false; } } finally { editor.OnUpdateUI("key"); } } /// <internalonly/> override protected void WndProc(ref Message m) { if (editor != null) // needed for design time support { switch ((Interop.WM)m.Msg) { case Interop.WM.WM_SETFOCUS: break; case Interop.WM.WM_KILLFOCUS: break; case Interop.WM.WM_MOUSEACTIVATE: if (editor.MshtmlSite != null && !this.DesignMode) { IntPtr fromHandle = Win32.GetFocus(); editor.DocumentHandle = editor.MshtmlSite.DocumentHandle; if ((!editor.Focused) && (fromHandle != editor.PanelHandle) && (fromHandle != editor.DocumentHandle)) { Win32.SendMessage(editor.PanelHandle, (int)Interop.WM.WM_SETFOCUS, fromHandle, IntPtr.Zero); } } break; } } base.WndProc(ref m); } } }
// Copyright (c) .NET Foundation. 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.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Text; using Microsoft.Extensions.Primitives; namespace HtcSharp.HttpModule.Http.Headers { // SourceTools-Start // Remote-File C:\ASP\src\Http\Headers\src\ContentDispositionHeaderValue.cs // Start-At-Remote-Line 14 // SourceTools-End // Note this is for use both in HTTP (https://tools.ietf.org/html/rfc6266) and MIME (https://tools.ietf.org/html/rfc2183) public class ContentDispositionHeaderValue { private const string FileNameString = "filename"; private const string NameString = "name"; private const string FileNameStarString = "filename*"; private const string CreationDateString = "creation-date"; private const string ModificationDateString = "modification-date"; private const string ReadDateString = "read-date"; private const string SizeString = "size"; private static readonly char[] QuestionMark = new char[] {'?'}; private static readonly char[] SingleQuote = new char[] {'\''}; private static readonly HttpHeaderParser<ContentDispositionHeaderValue> Parser = new GenericHeaderParser<ContentDispositionHeaderValue>(false, GetDispositionTypeLength); // Use list instead of dictionary since we may have multiple parameters with the same name. private ObjectCollection<NameValueHeaderValue> _parameters; private StringSegment _dispositionType; private ContentDispositionHeaderValue() { // Used by the parser to create a new instance of this type. } public ContentDispositionHeaderValue(StringSegment dispositionType) { CheckDispositionTypeFormat(dispositionType, "dispositionType"); _dispositionType = dispositionType; } public StringSegment DispositionType { get { return _dispositionType; } set { CheckDispositionTypeFormat(value, "value"); _dispositionType = value; } } public IList<NameValueHeaderValue> Parameters { get { if (_parameters == null) { _parameters = new ObjectCollection<NameValueHeaderValue>(); } return _parameters; } } // Helpers to access specific parameters in the list public StringSegment Name { get { return GetName(NameString); } set { SetName(NameString, value); } } public StringSegment FileName { get { return GetName(FileNameString); } set { SetName(FileNameString, value); } } public StringSegment FileNameStar { get { return GetName(FileNameStarString); } set { SetName(FileNameStarString, value); } } public DateTimeOffset? CreationDate { get { return GetDate(CreationDateString); } set { SetDate(CreationDateString, value); } } public DateTimeOffset? ModificationDate { get { return GetDate(ModificationDateString); } set { SetDate(ModificationDateString, value); } } public DateTimeOffset? ReadDate { get { return GetDate(ReadDateString); } set { SetDate(ReadDateString, value); } } public long? Size { get { var sizeParameter = NameValueHeaderValue.Find(_parameters, SizeString); long value; if (sizeParameter != null) { var sizeString = sizeParameter.Value; if (HeaderUtilities.TryParseNonNegativeInt64(sizeString, out value)) { return value; } } return null; } set { var sizeParameter = NameValueHeaderValue.Find(_parameters, SizeString); if (value == null) { // Remove parameter if (sizeParameter != null) { _parameters.Remove(sizeParameter); } } else if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } else if (sizeParameter != null) { sizeParameter.Value = value.GetValueOrDefault().ToString(CultureInfo.InvariantCulture); } else { string sizeString = value.GetValueOrDefault().ToString(CultureInfo.InvariantCulture); _parameters.Add(new NameValueHeaderValue(SizeString, sizeString)); } } } /// <summary> /// Sets both FileName and FileNameStar using encodings appropriate for HTTP headers. /// </summary> /// <param name="fileName"></param> public void SetHttpFileName(StringSegment fileName) { if (!StringSegment.IsNullOrEmpty(fileName)) { FileName = Sanitize(fileName); } else { FileName = fileName; } FileNameStar = fileName; } /// <summary> /// Sets the FileName parameter using encodings appropriate for MIME headers. /// The FileNameStar parameter is removed. /// </summary> /// <param name="fileName"></param> public void SetMimeFileName(StringSegment fileName) { FileNameStar = null; FileName = fileName; } public override string ToString() { return _dispositionType + NameValueHeaderValue.ToString(_parameters, ';', true); } public override bool Equals(object obj) { var other = obj as ContentDispositionHeaderValue; if (other == null) { return false; } return _dispositionType.Equals(other._dispositionType, StringComparison.OrdinalIgnoreCase) && HeaderUtilities.AreEqualCollections(_parameters, other._parameters); } public override int GetHashCode() { // The dispositionType string is case-insensitive. return StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_dispositionType) ^ NameValueHeaderValue.GetHashCode(_parameters); } public static ContentDispositionHeaderValue Parse(StringSegment input) { var index = 0; return Parser.ParseValue(input, ref index); } public static bool TryParse(StringSegment input, out ContentDispositionHeaderValue parsedValue) { var index = 0; return Parser.TryParseValue(input, ref index, out parsedValue); } private static int GetDispositionTypeLength(StringSegment input, int startIndex, out ContentDispositionHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespaces. If not, we'll return 0. var dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out var dispositionType); if (dispositionTypeLength == 0) { return 0; } var current = startIndex + dispositionTypeLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); var contentDispositionHeader = new ContentDispositionHeaderValue(); contentDispositionHeader._dispositionType = dispositionType; // If we're not done and we have a parameter delimiter, then we have a list of parameters. if ((current < input.Length) && (input[current] == ';')) { current++; // skip delimiter. int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';', contentDispositionHeader.Parameters); parsedValue = contentDispositionHeader; return current + parameterLength - startIndex; } // We have a ContentDisposition header without parameters. parsedValue = contentDispositionHeader; return current - startIndex; } private static int GetDispositionTypeExpressionLength(StringSegment input, int startIndex, out StringSegment dispositionType) { Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the disposition type string, it does not parse parameters. dispositionType = null; // Parse the disposition type, i.e. <dispositiontype> in content-disposition string // "<dispositiontype>; param1=value1; param2=value2" var typeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (typeLength == 0) { return 0; } dispositionType = input.Subsegment(startIndex, typeLength); return typeLength; } private static void CheckDispositionTypeFormat(StringSegment dispositionType, string parameterName) { if (StringSegment.IsNullOrEmpty(dispositionType)) { throw new ArgumentException("An empty string is not allowed.", parameterName); } // When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed. var dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out var tempDispositionType); if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length)) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Invalid disposition type '{0}'.", dispositionType)); } } // Gets a parameter of the given name and attempts to extract a date. // Returns null if the parameter is not present or the format is incorrect. private DateTimeOffset? GetDate(string parameter) { var dateParameter = NameValueHeaderValue.Find(_parameters, parameter); if (dateParameter != null) { var dateString = dateParameter.Value; // Should have quotes, remove them. if (IsQuoted(dateString)) { dateString = dateString.Subsegment(1, dateString.Length - 2); } DateTimeOffset date; if (HttpRuleParser.TryStringToDate(dateString, out date)) { return date; } } return null; } // Add the given parameter to the list. Remove if date is null. private void SetDate(string parameter, DateTimeOffset? date) { var dateParameter = NameValueHeaderValue.Find(_parameters, parameter); if (date == null) { // Remove parameter if (dateParameter != null) { _parameters.Remove(dateParameter); } } else { // Must always be quoted var dateString = HeaderUtilities.FormatDate(date.GetValueOrDefault(), quoted: true); if (dateParameter != null) { dateParameter.Value = dateString; } else { Parameters.Add(new NameValueHeaderValue(parameter, dateString)); } } } // Gets a parameter of the given name and attempts to decode it if necessary. // Returns null if the parameter is not present or the raw value if the encoding is incorrect. private StringSegment GetName(string parameter) { var nameParameter = NameValueHeaderValue.Find(_parameters, parameter); if (nameParameter != null) { string result; // filename*=utf-8'lang'%7FMyString if (parameter.EndsWith("*", StringComparison.Ordinal)) { if (TryDecode5987(nameParameter.Value, out result)) { return result; } return null; // Unrecognized encoding } // filename="=?utf-8?B?BDFSDFasdfasdc==?=" if (TryDecodeMime(nameParameter.Value, out result)) { return result; } // May not have been encoded return HeaderUtilities.RemoveQuotes(nameParameter.Value); } return null; } // Add/update the given parameter in the list, encoding if necessary. // Remove if value is null/Empty private void SetName(StringSegment parameter, StringSegment value) { var nameParameter = NameValueHeaderValue.Find(_parameters, parameter); if (StringSegment.IsNullOrEmpty(value)) { // Remove parameter if (nameParameter != null) { _parameters.Remove(nameParameter); } } else { var processedValue = StringSegment.Empty; if (parameter.EndsWith("*", StringComparison.Ordinal)) { processedValue = Encode5987(value); } else { processedValue = EncodeAndQuoteMime(value); } if (nameParameter != null) { nameParameter.Value = processedValue; } else { Parameters.Add(new NameValueHeaderValue(parameter, processedValue)); } } } // Returns input for decoding failures, as the content might not be encoded private StringSegment EncodeAndQuoteMime(StringSegment input) { var result = input; var needsQuotes = false; // Remove bounding quotes, they'll get re-added later if (IsQuoted(result)) { result = result.Subsegment(1, result.Length - 2); needsQuotes = true; } if (RequiresEncoding(result)) { needsQuotes = true; // Encoded data must always be quoted, the equals signs are invalid in tokens result = EncodeMime(result); // =?utf-8?B?asdfasdfaesdf?= } else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length) { needsQuotes = true; } if (needsQuotes) { // '\' and '"' must be escaped in a quoted string result = result.ToString().Replace(@"\", @"\\").Replace(@"""", @"\"""); // Re-add quotes "value" result = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", result); } return result; } // Replaces characters not suitable for HTTP headers with '_' rather than MIME encoding them. private StringSegment Sanitize(StringSegment input) { var result = input; if (RequiresEncoding(result)) { var builder = new StringBuilder(result.Length); for (int i = 0; i < result.Length; i++) { var c = result[i]; if ((int) c > 0x7f || (int) c < 0x20) { c = '_'; // Replace out-of-range characters } builder.Append(c); } result = builder.ToString(); } return result; } // Returns true if the value starts and ends with a quote private bool IsQuoted(StringSegment value) { Contract.Assert(value != null); return value.Length > 1 && value.StartsWith("\"", StringComparison.Ordinal) && value.EndsWith("\"", StringComparison.Ordinal); } // tspecials are required to be in a quoted string. Only non-ascii needs to be encoded. private bool RequiresEncoding(StringSegment input) { Contract.Assert(input != null); for (int i = 0; i < input.Length; i++) { if ((int) input[i] > 0x7f || (int) input[i] < 0x20) { return true; } } return false; } // Encode using MIME encoding private unsafe string EncodeMime(StringSegment input) { fixed (char* chars = input.Buffer) { var byteCount = Encoding.UTF8.GetByteCount(chars + input.Offset, input.Length); var buffer = new byte[byteCount]; fixed (byte* bytes = buffer) { Encoding.UTF8.GetBytes(chars + input.Offset, input.Length, bytes, byteCount); } var encodedName = Convert.ToBase64String(buffer); return "=?utf-8?B?" + encodedName + "?="; } } // Attempt to decode MIME encoded strings private bool TryDecodeMime(StringSegment input, out string output) { Contract.Assert(input != null); output = null; var processedInput = input; // Require quotes, min of "=?e?b??=" if (!IsQuoted(processedInput) || processedInput.Length < 10) { return false; } var parts = processedInput.Split(QuestionMark).ToArray(); // "=, encodingName, encodingType, encodedData, =" if (parts.Length != 5 || parts[0] != "\"=" || parts[4] != "=\"" || !parts[2].Equals("b", StringComparison.OrdinalIgnoreCase)) { // Not encoded. // This does not support multi-line encoding. // Only base64 encoding is supported, not quoted printable return false; } try { var encoding = Encoding.GetEncoding(parts[1].ToString()); var bytes = Convert.FromBase64String(parts[3].ToString()); output = encoding.GetString(bytes, 0, bytes.Length); return true; } catch (ArgumentException) { // Unknown encoding or bad characters } catch (FormatException) { // Bad base64 decoding } return false; } // Encode a string using RFC 5987 encoding // encoding'lang'PercentEncodedSpecials private string Encode5987(StringSegment input) { var builder = new StringBuilder("UTF-8\'\'"); for (int i = 0; i < input.Length; i++) { var c = input[i]; // attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" // ; token except ( "*" / "'" / "%" ) if (c > 0x7F) // Encodes as multiple utf-8 bytes { var bytes = Encoding.UTF8.GetBytes(c.ToString()); foreach (byte b in bytes) { HexEscape(builder, (char) b); } } else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%') { // ASCII - Only one encoded byte HexEscape(builder, c); } else { builder.Append(c); } } return builder.ToString(); } private static readonly char[] HexUpperChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static void HexEscape(StringBuilder builder, char c) { builder.Append('%'); builder.Append(HexUpperChars[(c & 0xf0) >> 4]); builder.Append(HexUpperChars[c & 0xf]); } // Attempt to decode using RFC 5987 encoding. // encoding'language'my%20string private bool TryDecode5987(StringSegment input, out string output) { output = null; var parts = input.Split(SingleQuote).ToArray(); if (parts.Length != 3) { return false; } var decoded = new StringBuilder(); byte[] unescapedBytes = null; try { var encoding = Encoding.GetEncoding(parts[0].ToString()); var dataString = parts[2]; unescapedBytes = ArrayPool<byte>.Shared.Rent(dataString.Length); var unescapedBytesCount = 0; for (var index = 0; index < dataString.Length; index++) { if (IsHexEncoding(dataString, index)) // %FF { // Unescape and cache bytes, multi-byte characters must be decoded all at once unescapedBytes[unescapedBytesCount++] = HexUnescape(dataString, ref index); index--; // HexUnescape did +=3; Offset the for loop's ++ } else { if (unescapedBytesCount > 0) { // Decode any previously cached bytes decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount)); unescapedBytesCount = 0; } decoded.Append(dataString[index]); // Normal safe character } } if (unescapedBytesCount > 0) { // Decode any previously cached bytes decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount)); } } catch (ArgumentException) { return false; // Unknown encoding or bad characters } finally { if (unescapedBytes != null) { ArrayPool<byte>.Shared.Return(unescapedBytes); } } output = decoded.ToString(); return true; } private static bool IsHexEncoding(StringSegment pattern, int index) { if ((pattern.Length - index) < 3) { return false; } if ((pattern[index] == '%') && IsEscapedAscii(pattern[index + 1], pattern[index + 2])) { return true; } return false; } private static bool IsEscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return false; } if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return false; } return true; } private static byte HexUnescape(StringSegment pattern, ref int index) { if ((index < 0) || (index >= pattern.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } if ((pattern[index] == '%') && (pattern.Length - index >= 3)) { var ret = UnEscapeAscii(pattern[index + 1], pattern[index + 2]); index += 3; return ret; } return (byte) pattern[index++]; } internal static byte UnEscapeAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { throw new ArgumentException(); } var res = (digit <= '9') ? ((int) digit - (int) '0') : (((digit <= 'F') ? ((int) digit - (int) 'A') : ((int) digit - (int) 'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { throw new ArgumentException(); } return (byte) ((res << 4) + ((next <= '9') ? ((int) next - (int) '0') : (((next <= 'F') ? ((int) next - (int) 'A') : ((int) next - (int) 'a')) + 10))); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Xml; using System.Xml.Schema; namespace XsdDocumentation.Model { internal sealed class TopicManager : Manager { private Dictionary<string, Topic> _namespaceTopics = new Dictionary<string, Topic>(); private Dictionary<XmlSchemaObject, Topic> _topicDictionary = new Dictionary<XmlSchemaObject, Topic>(); private Dictionary<string, Topic> _topicUriIndex = new Dictionary<string, Topic>(); public TopicManager(Context context) : base(context) { } public override void Initialize() { var topicBuilder = new TopicBuilder(Context.SchemaSetManager, _namespaceTopics, _topicDictionary); topicBuilder.Traverse(Context.SchemaSetManager.SchemaSet); Topics = topicBuilder.GetRootTopics(); RemoveNamespaceContainerIfConfigured(); RemoveSchemasIfConfigured(); SortNamespaces(); InsertNamespaceOverviewTopics(); InsertNamespaceRootTopics(); InsertSchemaSetTopic(); SetTopicIds(); SetKeywords(Topics); GenerateTopicUriIndex(Topics); } public Topic GetNamespaceTopic(string targetNamespace) { Topic result; _namespaceTopics.TryGetValue(targetNamespace ?? string.Empty, out result); return result; } public Topic GetTopicByUri(string uri) { Topic result; _topicUriIndex.TryGetValue(uri, out result); return result; } public Topic GetTopic(XmlSchemaObject obj) { XmlSchemaElement element; XmlSchemaAttribute attribute; if (Casting.TryCast(obj, out element)) { if (!element.RefName.IsEmpty) obj = Context.SchemaSetManager.SchemaSet.GlobalElements[element.RefName]; } else if (Casting.TryCast(obj, out attribute)) { if (!attribute.RefName.IsEmpty) obj = Context.SchemaSetManager.SchemaSet.GlobalAttributes[attribute.RefName]; } Topic result; _topicDictionary.TryGetValue(obj, out result); return result; } public List<Topic> Topics { get; private set; } private void RemoveNamespaceContainerIfConfigured() { var namespaceTopicCount = Topics.Count; var shouldRemoveNamespaceTopic = !Context.Configuration.NamespaceContainer; var canRemoveNamespaceTopic = (namespaceTopicCount == 1); var removeNamespaceTopic = shouldRemoveNamespaceTopic && canRemoveNamespaceTopic; if (removeNamespaceTopic) { var singleNamespaceTopic = Topics[0]; Topics.Clear(); Topics.AddRange(singleNamespaceTopic.Children); _namespaceTopics.Remove(singleNamespaceTopic.Namespace ?? string.Empty); } Context.Configuration.NamespaceContainer = !removeNamespaceTopic; } private void RemoveSchemasIfConfigured() { if (Context.Configuration.DocumentSchemas) return; if (!Context.Configuration.NamespaceContainer) { RemoveSchemas(Topics); } else { foreach (var namespaceTopic in Topics) RemoveSchemas(namespaceTopic.Children); } } private void RemoveSchemas(IList<Topic> topics) { for (var i = topics.Count - 1; i >= 0; i--) { var topic = topics[i]; if (topic.TopicType != TopicType.Schema) continue; topics.RemoveAt(i); _topicDictionary.Remove(topic.SchemaObject); } } private void SortNamespaces() { if (Context.Configuration.NamespaceContainer) Topics.Sort((x, y) => x.LinkTitle.CompareTo(y.LinkTitle)); } private void InsertNamespaceOverviewTopics() { if (Context.Configuration.NamespaceContainer) { foreach (var namespaceTopic in Topics) CreateNamespaceOverviewTopics(namespaceTopic.Namespace, namespaceTopic.Children); } else if (Topics.Count > 0) { var firstEntry = Topics[0]; CreateNamespaceOverviewTopics(firstEntry.Namespace, Topics); } } private static void CreateNamespaceOverviewTopics(string namespaceUri, List<Topic> namespaceChildTopics) { var groupedChildren = from child in namespaceChildTopics group child by child.TopicType into g orderby GetTopicTypeSortOrderKey(g.Key) select g; var overviewTopics = new List<Topic>(); foreach (var grouping in groupedChildren) { var overviewTopicType = GetOverviewTopicType(grouping.Key); var overviewLinkUri = GetOverviewTopicLinkUri(namespaceUri, overviewTopicType); var overviewTopicTitle = GetOverviewTopicTitle(overviewTopicType); var overviewTopic = new Topic { Title = overviewTopicTitle, LinkTitle = overviewTopicTitle, LinkUri = overviewLinkUri, TopicType = overviewTopicType, Namespace = namespaceUri }; var sortedSubTopics = from subTopic in grouping orderby subTopic.Title select subTopic; overviewTopic.Children.AddRange(sortedSubTopics); overviewTopics.Add(overviewTopic); } namespaceChildTopics.Clear(); namespaceChildTopics.AddRange(overviewTopics); } private void InsertNamespaceRootTopics() { if (Context.Configuration.NamespaceContainer) { foreach (var namespaceTopic in Topics) InsertNamespaceRootTopics(namespaceTopic.Namespace, namespaceTopic.Children); } else if (Topics.Count > 0) { var firstEntry = Topics[0]; InsertNamespaceRootTopics(firstEntry.Namespace, Topics); } } private void InsertNamespaceRootTopics(string namespaceUri, IList<Topic> namespaceChildren) { if (Context.Configuration.DocumentRootElements) { var rootElements = Context.SchemaSetManager.GetNamespaceRootElements(namespaceUri); InsertNamespaceRootTopic(namespaceUri, namespaceChildren, rootElements, TopicType.RootElementsSection); } if (Context.Configuration.DocumentRootSchemas && Context.Configuration.DocumentSchemas) { var rootSchemas = Context.SchemaSetManager.GetNamespaceRootSchemas(namespaceUri); InsertNamespaceRootTopic(namespaceUri, namespaceChildren, rootSchemas, TopicType.RootSchemasSection); } } private static void InsertNamespaceRootTopic(string namespaceUri, IList<Topic> namespaceChildren, IEnumerable<XmlSchemaObject> rootItems, TopicType topicType) { var rootElements = rootItems.ToList(); if (rootElements.Count == 0) return; var overviewTopicTitle = GetOverviewTopicTitle(topicType); var rootElementsTopic = new Topic { Title = overviewTopicTitle, LinkTitle = overviewTopicTitle, LinkUri = GetOverviewTopicLinkUri(namespaceUri, topicType), TopicType = topicType, Namespace = namespaceUri }; namespaceChildren.Insert(0, rootElementsTopic); } private void InsertSchemaSetTopic() { if (!Context.Configuration.SchemaSetContainer) return; var title = string.IsNullOrEmpty(Context.Configuration.SchemaSetTitle) ? "Schema Set" : Context.Configuration.SchemaSetTitle; var schemaSetTopic = new Topic { Title = title, LinkTitle = title, LinkUri = "##SchemaSet", TopicType = TopicType.SchemaSet, }; schemaSetTopic.Children.AddRange(Topics); Topics.Clear(); Topics.Add(schemaSetTopic); } private static int GetTopicTypeSortOrderKey(TopicType topicType) { switch (topicType) { case TopicType.Schema: return 0; case TopicType.Element: return 1; case TopicType.Attribute: return 2; case TopicType.AttributeGroup: return 3; case TopicType.Group: return 4; case TopicType.SimpleType: return 5; case TopicType.ComplexType: return 6; default: throw ExceptionBuilder.UnhandledCaseLabel(topicType); } } private static TopicType GetOverviewTopicType(TopicType topicType) { switch (topicType) { case TopicType.Schema: return TopicType.SchemasSection; case TopicType.Element: return TopicType.ElementsSection; case TopicType.Attribute: return TopicType.AttributesSection; case TopicType.AttributeGroup: return TopicType.AttributeGroupsSection; case TopicType.Group: return TopicType.GroupsSection; case TopicType.SimpleType: return TopicType.SimpleTypesSection; case TopicType.ComplexType: return TopicType.ComplexTypesSection; default: throw ExceptionBuilder.UnhandledCaseLabel(topicType); } } private static string GetOverviewTopicLinkUri(string namespaceUri, TopicType type) { switch (type) { case TopicType.RootSchemasSection: return string.Format(CultureInfo.InvariantCulture, "{0}##RootSchemas", namespaceUri); case TopicType.RootElementsSection: return string.Format(CultureInfo.InvariantCulture, "{0}##RootElements", namespaceUri); case TopicType.SchemasSection: return string.Format(CultureInfo.InvariantCulture, "{0}##Schemas", namespaceUri); case TopicType.ElementsSection: return string.Format(CultureInfo.InvariantCulture, "{0}##Elements", namespaceUri); case TopicType.AttributesSection: return string.Format(CultureInfo.InvariantCulture, "{0}##Attributes", namespaceUri); case TopicType.AttributeGroupsSection: return string.Format(CultureInfo.InvariantCulture, "{0}##AttributeGroups", namespaceUri); case TopicType.GroupsSection: return string.Format(CultureInfo.InvariantCulture, "{0}##Groups", namespaceUri); case TopicType.SimpleTypesSection: return string.Format(CultureInfo.InvariantCulture, "{0}##SimpleTypes", namespaceUri); case TopicType.ComplexTypesSection: return string.Format(CultureInfo.InvariantCulture, "{0}##ComplexTypes", namespaceUri); default: throw ExceptionBuilder.UnhandledCaseLabel(type); } } private static string GetOverviewTopicTitle(TopicType topicType) { switch (topicType) { case TopicType.RootSchemasSection: return "Root Schemas"; case TopicType.RootElementsSection: return "Root Elements"; case TopicType.SchemasSection: return "Schemas"; case TopicType.ElementsSection: return "Elements"; case TopicType.AttributesSection: return "Attributes"; case TopicType.AttributeGroupsSection: return "Attribute Groups"; case TopicType.GroupsSection: return "Groups"; case TopicType.SimpleTypesSection: return "Simple Types"; case TopicType.ComplexTypesSection: return "Complex Types"; default: throw ExceptionBuilder.UnhandledCaseLabel(topicType); } } private void SetTopicIds() { var guidsInUse = new HashSet<Guid>(); using (var md5 = HashAlgorithm.Create("MD5")) SetTopicIds(Topics, md5, guidsInUse); } private static void SetTopicIds(IEnumerable<Topic> topics, HashAlgorithm algorithm, HashSet<Guid> guidsInUse) { foreach (var topic in topics) { var input = Encoding.UTF8.GetBytes(topic.LinkUri); var output = algorithm.ComputeHash(input); var guid = new Guid(output); while (!guidsInUse.Add(guid)) guid = Guid.NewGuid(); topic.Id = guid.ToString(); SetTopicIds(topic.Children, algorithm, guidsInUse); } } private void SetKeywords(IEnumerable<Topic> topics) { foreach (var topic in topics) { switch (topic.TopicType) { case TopicType.Namespace: AddKeywordK(topic, topic.Title); AddKeywordF(topic, topic.Namespace); break; case TopicType.Schema: AddKeywordK(topic, topic.Title); break; case TopicType.Element: { AddKeywordK(topic, topic.Title); var element = (XmlSchemaElement)topic.SchemaObject; AddKeywordF(topic, element.QualifiedName); break; } case TopicType.Attribute: { AddKeywordK(topic, topic.Title); var attribute = (XmlSchemaAttribute)topic.SchemaObject; AddKeywordF(topic, attribute.QualifiedName); break; } case TopicType.AttributeGroup: AddKeywordK(topic, topic.Title); break; case TopicType.Group: AddKeywordK(topic, topic.Title); break; case TopicType.SimpleType: AddKeywordK(topic, topic.Title); break; case TopicType.ComplexType: AddKeywordK(topic, topic.Title); break; } if (Context.Configuration.IncludeLinkUriInKeywordK) AddKeywordK(topic, topic.LinkUri); SetKeywords(topic.Children); } } private static void AddKeywordK(Topic topic, string keyword) { topic.KeywordsK.Add(keyword); } private static void AddKeywordF(Topic topic, string keyword) { topic.KeywordsF.Add(keyword); } private static void AddKeywordF(Topic topic, XmlQualifiedName qualifiedName) { if (string.IsNullOrEmpty(qualifiedName.Namespace)) return; var keyword = string.Format("{0}#{1}", qualifiedName.Namespace, qualifiedName.Name); AddKeywordF(topic, keyword); } private void GenerateTopicUriIndex(IEnumerable<Topic> topics) { foreach (var topic in topics) { AddTopicUriToIndex(topic, topic.LinkUri); AddTopicUriToIndex(topic, topic.LinkIdUri); GenerateTopicUriIndex(topic.Children); } } private void AddTopicUriToIndex(Topic topic, string uri) { if (string.IsNullOrEmpty(uri)) return; if (!_topicUriIndex.ContainsKey(uri)) _topicUriIndex.Add(uri, topic); } } }
// 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 Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using MICore; namespace Microsoft.MIDebugEngine { // This class implements IDebugThread2 which represents a thread running in a program. internal class AD7Thread : IDebugThread2 { private readonly AD7Engine _engine; private readonly DebuggedThread _debuggedThread; public int Id { get { return _debuggedThread.Id; } } public AD7Thread(AD7Engine engine, DebuggedThread debuggedThread) { _engine = engine; _debuggedThread = debuggedThread; } private ThreadContext GetThreadContext() { ThreadContext threadContext = null; _engine.DebuggedProcess.WorkerThread.RunOperation(async () => threadContext = await _engine.DebuggedProcess.ThreadCache.GetThreadContext(_debuggedThread)); return threadContext; } private string GetCurrentLocation(bool fIncludeModuleName) { ThreadContext cxt = GetThreadContext(); string location = null; if (cxt != null) { location = ""; if (fIncludeModuleName) { if (cxt.From != null) { location = cxt.From + '!'; } else { DebuggedModule module = cxt.FindModule(_engine.DebuggedProcess); if (module != null) { location = module.Name + '!'; } } } if (cxt.Function == null) { location += _engine.GetAddressDescription(cxt.pc.Value); } else { location += cxt.Function; } } return location; } internal DebuggedThread GetDebuggedThread() { return _debuggedThread; } #region IDebugThread2 Members // Determines whether the next statement can be set to the given stack frame and code context. int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) { // CLRDBG TODO: This implementation should be changed to compare the method token ulong addr = ((AD7MemoryAddress)codeContext).Address; AD7StackFrame frame = ((AD7StackFrame)stackFrame); if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue || _engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Clrdbg) { return Constants.S_FALSE; } if (addr == frame.ThreadContext.pc) { return Constants.S_OK; } string toFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr); string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value); if (toFunc != fromFunc) { return Constants.S_FALSE; } return Constants.S_OK; } // Retrieves a list of the stack frames for this thread. // For the sample engine, enumerating the stack frames requires walking the callstack in the debuggee for this thread // and coverting that to an implementation of IEnumDebugFrameInfo2. // Real engines will most likely want to cache this information to avoid recomputing it each time it is asked for, // and or construct it on demand instead of walking the entire stack. int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject) { enumObject = null; try { // get the thread's stack frames System.Collections.Generic.List<ThreadContext> stackFrames = null; _engine.DebuggedProcess.WorkerThread.RunOperation(async () => stackFrames = await _engine.DebuggedProcess.ThreadCache.StackFrames(_debuggedThread)); int numStackFrames = stackFrames != null ? stackFrames.Count : 0; FRAMEINFO[] frameInfoArray; if (numStackFrames == 0) { // failed to walk any frames. Return an empty stack. frameInfoArray = new FRAMEINFO[0]; } else { uint low = stackFrames[0].Level; uint high = stackFrames[stackFrames.Count - 1].Level; FilterUnknownFrames(stackFrames); numStackFrames = stackFrames.Count; frameInfoArray = new FRAMEINFO[numStackFrames]; List<ArgumentList> parameters = null; if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS) != 0 && !_engine.DebuggedProcess.MICommandFactory.SupportsFrameFormatting) { _engine.DebuggedProcess.WorkerThread.RunOperation(async () => parameters = await _engine.DebuggedProcess.GetParameterInfoOnly(this, (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0, (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_TYPES) != 0, low, high)); } for (int i = 0; i < numStackFrames; i++) { var p = parameters != null ? parameters.Find((ArgumentList t) => t.Item1 == stackFrames[i].Level) : null; AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]); frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i], p != null ? p.Item2 : null); } } enumObject = new AD7FrameInfoEnum(frameInfoArray); return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } private void FilterUnknownFrames(System.Collections.Generic.List<ThreadContext> stackFrames) { bool lastWasQuestion = false; for (int i = 0; i < stackFrames.Count;) { // replace sequences of "??" with one UnknownCode frame if (stackFrames[i].Function == null || stackFrames[i].Function.Equals("??", StringComparison.Ordinal)) { if (lastWasQuestion) { stackFrames.RemoveAt(i); continue; } lastWasQuestion = true; stackFrames[i] = new ThreadContext(stackFrames[i].pc, stackFrames[i].TextPosition, ResourceStrings.UnknownCode, stackFrames[i].Level, null); } else { lastWasQuestion = false; } i++; } } // Get the name of the thread. For the sample engine, the name of the thread is always "Sample Engine Thread" int IDebugThread2.GetName(out string threadName) { threadName = _debuggedThread.Name; return Constants.S_OK; } // Return the program that this thread belongs to. int IDebugThread2.GetProgram(out IDebugProgram2 program) { program = _engine; return Constants.S_OK; } // Gets the system thread identifier. int IDebugThread2.GetThreadId(out uint threadId) { threadId = _debuggedThread.TargetId; return Constants.S_OK; } // Gets properties that describe a thread. int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] ptp) { try { THREADPROPERTIES props = new THREADPROPERTIES(); if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0) { props.dwThreadId = _debuggedThread.TargetId; props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID; } if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0) { // sample debug engine doesn't support suspending threads props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT; } if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0) { props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING; props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE; } if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0) { props.bstrPriority = "Normal"; props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY; } if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0) { props.bstrName = _debuggedThread.Name; props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME; } if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0) { props.bstrLocation = GetCurrentLocation(true); props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION; if (props.bstrLocation == null) { // Thread deletion events may be delayed, in which case the thread object may still be present in the cache // but the engine is unable to retrieve new data for it. So handle failure to get info for a dead thread. props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_DEAD; props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE; props.bstrLocation = ResourceStrings.ThreadExited; } } ptp[0] = props; return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Resume a thread. // This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen. int IDebugThread2.Resume(out uint suspendCount) { // The sample debug engine doesn't support suspending/resuming threads suspendCount = 0; return Constants.E_NOTIMPL; } // Sets the next statement to the given stack frame and code context. int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) { // CLRDBG TODO: This implementation should be changed to call an MI command ulong addr = ((AD7MemoryAddress)codeContext).Address; AD7StackFrame frame = ((AD7StackFrame)stackFrame); if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue || _engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Clrdbg) { return Constants.S_FALSE; } string toFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr); string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value); if (toFunc != fromFunc) { return Constants.S_FALSE; } string result = frame.EvaluateExpression("$pc=" + EngineUtils.AsAddr(addr, _engine.DebuggedProcess.Is64BitArch)); if (result != null) { _engine.DebuggedProcess.ThreadCache.MarkDirty(); return Constants.S_OK; } return Constants.S_FALSE; } // suspend a thread. // This is called when the user chooses "Freeze" from the threads window int IDebugThread2.Suspend(out uint suspendCount) { // The sample debug engine doesn't support suspending/resuming threads suspendCount = 0; return Constants.E_NOTIMPL; } #endregion #region Uncalled interface methods // These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread) { Debug.Fail("This function is not called by the debugger"); logicalThread = null; return Constants.E_NOTIMPL; } int IDebugThread2.SetThreadName(string name) { Debug.Fail("This function is not called by the debugger"); return Constants.E_NOTIMPL; } #endregion } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using MapEditor.map; namespace MapEditor { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; ContentManager content; Text text; Texture2D[] mapsTex; Texture2D nullTex; Texture2D textTex; SpriteBatch sprite; Texture2D iconsTex; int mosX, mosY; bool mouseDown; bool mouseClick; bool midMouseDown; Vector2 scroll; int scriptScroll; int selScript = -1; int selIdx; int selScroll; int mouseDragSeg = -1; int curLayer = 1; int pMosX, pMosY; int segScroll = 0; const int COLOR_NONE = 0; const int COLOR_YELLOW = 1; const int COLOR_GREEN = 2; const int DRAW_SELECT = 0; const int DRAW_COL = 1; const int DRAW_LEDGE = 2; const int DRAW_SCRIPT = 3; int drawType = DRAW_SELECT; int curLedge = 0; Map map; KeyboardState oldKeyState; int editingText = -1; const int EDITING_NONE = -1; const int EDITING_PATH = 0; const int EDITING_SCRIPT = 1; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 600; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { map = new Map(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. sprite = new SpriteBatch(GraphicsDevice); sprite = new SpriteBatch(graphics.GraphicsDevice); textTex = Content.Load<Texture2D>(@"gfx/arial"); text = new Text(textTex, sprite); nullTex = Content.Load<Texture2D>(@"gfx/1x1"); mapsTex = new Texture2D[1]; for (int i = 0; i < mapsTex.Length; i++) mapsTex[i] = Content.Load<Texture2D>(@"gfx/maps" + (i + 1).ToString()); iconsTex = Content.Load<Texture2D>(@"gfx/icons"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } private void UpdateKeys() { KeyboardState keystate = new KeyboardState(); keystate = Keyboard.GetState(); Keys[] currentkeys = keystate.GetPressedKeys(); Keys[] lastkeys = oldKeyState.GetPressedKeys(); bool found = false; for (int i = 0; i < currentkeys.Length; i++) { found = false; for (int y = 0; y < lastkeys.Length; y++) { if (currentkeys[i] == lastkeys[y]) found = true; } if (found == false) { PressKey(currentkeys[i]); } } oldKeyState = keystate; } private bool ScriptEnter() { if (selScript >= map.script.Length - 1) return false; for (int i = map.script.Length - 1; i > selScript; i--) map.script[i] = map.script[i - 1]; selScript++; return true; } private bool ScriptDelLine() { if (selScript <= 0) return false; for (int i = selScript; i < map.script.Length - 1; i++) map.script[i] = map.script[i + 1]; return true; } private void PressKey(Keys key) { String t = ""; switch (editingText) { case EDITING_PATH: t = map.path; break; case EDITING_SCRIPT: if (selScript < 0) return; t = map.script[selScript]; break; default: return; } bool delLine = false; if (key == Keys.Back) { if (t.Length > 0) t = t.Substring(0, t.Length - 1); else if (editingText == EDITING_SCRIPT) { delLine = ScriptDelLine(); } } else if (key == Keys.Enter) { if (editingText == EDITING_SCRIPT) { if (ScriptEnter()) { t = ""; } } else editingText = EDITING_NONE; } else { t = (t + (char)key).ToLower(); } if (!delLine) { switch (editingText) { case EDITING_PATH: map.path = t; break; case EDITING_SCRIPT: map.script[selScript] = t; break; } } else selScript--; } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); UpdateKeys(); MouseState mState = Mouse.GetState(); mosX = mState.X; mosY = mState.Y; bool pMouseDown = mouseDown; if (mState.LeftButton == ButtonState.Pressed) { if (!mouseDown) { if (GetCanEdit()) { if (drawType == DRAW_SELECT) { int f = map.GetHoveredSegment(mosX, mosY, curLayer, scroll); if (f != -1) { mouseDragSeg = f; pMosX = mosX; pMosY = mosY; } } if (drawType == DRAW_LEDGE) { if (map.GetLedgeTotalNodes(curLedge) < 15) { map.SetLedgeNode(curLedge, map.GetLedgeTotalNodes(curLedge), new Vector2((float)mosX, (float)mosY) + scroll / 2.0f); map.SetLedgeTotalNodes(curLedge, map.GetLedgeTotalNodes(curLedge) + 1); } } if (drawType == DRAW_SCRIPT) { if (selScript > -1) { if (mosX < 400) { Vector2 v = new Vector2((float)mosX, (float)mosY) + scroll / 2.0f; v *= 2f; map.script[selScript] += ((int)(v.X)).ToString() + " " + ((int)(v.Y)).ToString(); } } } } } mouseDown = true; } else mouseDown = false; if (pMouseDown && !mouseDown) mouseClick = true; if (mouseClick) editingText = EDITING_NONE; if (mState.MiddleButton == ButtonState.Pressed) { if (!midMouseDown) { pMosX = mosX; pMosY = mosY; midMouseDown = true; } } else midMouseDown = false; if (mouseDragSeg > -1) { if (!mouseDown) mouseDragSeg = -1; else { Vector2 loc = map.GetSegLoc(curLayer, mouseDragSeg); loc.X += (float)(mosX - pMosX); loc.Y += (float)(mosY - pMosY); pMosX = mosX; pMosY = mosY; map.SetSegLoc(curLayer, mouseDragSeg, loc); } } if (midMouseDown) { scroll.X -= (float)(mosX - pMosX) * 2.0f; scroll.Y -= (float)(mosY - pMosY) * 2.0f; pMosX = mosX; pMosY = mosY; } if (drawType == DRAW_COL) { if (GetCanEdit()) { int x = (mosX + (int)scroll.X / 2) / 32; int y = (mosY + (int)scroll.Y / 2) / 32; if (x >= 0 && y >= 0 && x < map.xSize && y < map.ySize) { if (mState.LeftButton == ButtonState.Pressed) map.SetCol(x, y, 1); if (mState.RightButton == ButtonState.Pressed) map.SetCol(x, y, 0); } } } // TODO: Add your update logic here base.Update(gameTime); } private void DrawGrid() { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); for (int y = 0; y <= map.ySize; y++) { for (int x = 0; x <= map.xSize; x++) { Rectangle dRect = new Rectangle( x * 32 - (int)scroll.X / 2, y * 32 - (int)scroll.Y / 2, 32, 32 ); if (x < map.xSize) sprite.Draw(nullTex, new Rectangle( dRect.X, dRect.Y, 32, 1 ), new Color(new Vector4(1.0f, 0.0f, 0.0f, 0.3f))); if (y < map.ySize) sprite.Draw(nullTex, new Rectangle( dRect.X, dRect.Y, 1, 32 ), new Color(new Vector4(1.0f, 0.0f, 0.0f, 0.3f))); if (x < map.xSize && y < map.ySize) { if (map.GetCol(x, y) == 1) { sprite.Draw(nullTex, dRect, new Color(new Vector4(1.0f, 0.0f, 0.0f, 0.3f))); } } } } sprite.End(); } private bool GetCanEdit() { if (mosX > 100 && mosX < 500 && mosY > 100 && mosY < 550) return true; return false; } private void DrawLedges() { Rectangle rect = new Rectangle(); sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); Color tColor = new Color(); rect.X = 32; rect.Y = 0; rect.Width = 32; rect.Height = 32; for (int i = 0; i < 16; i++) { if (map.GetLedgeTotalNodes(i) > 0) { for (int n = 0; n < map.GetLedgeTotalNodes(i); n++) { Vector2 tVec; tVec = map.GetLedgeNode(i, n); tVec -= scroll / 2.0f; tVec.X -= 5.0f; if (curLedge == i) tColor = Color.Yellow; else tColor = Color.White; sprite.Draw(iconsTex, tVec, rect, tColor, 0.0f, new Vector2(0, 0), 0.35f, SpriteEffects.None, 0.0f); if (n < map.GetLedgeTotalNodes(i) - 1) { Vector2 nVec; nVec = map.GetLedgeNode(i, n + 1); nVec -= scroll / 2.0f; nVec.X -= 4.0f; for (int x = 1; x < 20; x++) { Vector2 iVec = (nVec - tVec) * ((float)x / 20.0f) + tVec; Color nColor = new Color(new Vector4(1.0f, 1.0f, 1.0f, 0.25f)); if (map.GetLedgeFlags(i) == 1) nColor = new Color(new Vector4(1.0f, 0.0f, 0.0f, 0.25f)); sprite.Draw(iconsTex, iVec, rect, nColor, 0.0f, new Vector2(0, 0), 0.25f, SpriteEffects.None, 0.0f); } } } } } sprite.End(); } private void DrawCursor() { Rectangle rect = new Rectangle(); sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); Color tColor = new Color(); tColor = Color.White; if (GetCanEdit()) tColor = Color.Yellow; rect.X = 0; rect.Y = 0; rect.Width = 32; rect.Height = 32; sprite.Draw(iconsTex, new Vector2((float)mosX, (float)mosY), rect, tColor, 0.0f, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0.0f); sprite.End(); } private bool drawButton(int x, int y, int idx, int mosX, int mosY, bool mouseClick) { bool r = false; Rectangle sRect = new Rectangle(32 * (idx % 8), 32 * (idx / 8), 32, 32); Rectangle dRect = new Rectangle(x, y, 32, 32); if (dRect.Contains(mosX, mosY)) { dRect.X -= 1; dRect.Y -= 1; dRect.Width += 2; dRect.Height += 2; if (mouseClick) r = true; } sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); sprite.Draw(iconsTex, dRect, sRect, Color.White); sprite.End(); return r; } private int GetCommandColor(String s) { switch (s) { case "fog": case "monster": case "makebucket": case "addbucket": case "ifnotbucketgoto": case "wait": case "setflag": case "iftruegoto": case "iffalsegoto": case "setglobalflag": case "ifglobaltruegoto": case "ifglobalfalsegoto": case "stop": case "setleftexit": case "setleftentrance": case "setrightexit": case "setrightentrance": case "setintroentrance": case "water": return COLOR_GREEN; case "tag": return COLOR_YELLOW; } return COLOR_NONE; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { Rectangle sRect = new Rectangle(); Rectangle dRect = new Rectangle(); graphics.GraphicsDevice.Clear(Color.CornflowerBlue); map.Draw(sprite, mapsTex, scroll); //if (drawType == DRAW_COL) DrawGrid(); DrawLedges(); sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); Color oColor = new Color(new Vector4(1.0f, 1.0f, 1.0f, 0.3f)); sprite.Draw(nullTex, new Rectangle(100, 50, 400, 1), oColor); sprite.Draw(nullTex, new Rectangle(100, 50, 1, 500), oColor); sprite.Draw(nullTex, new Rectangle(500, 50, 1, 500), oColor); sprite.Draw(nullTex, new Rectangle(100, 550, 400, 1), oColor); sprite.Draw(nullTex, new Rectangle(100, 300, 400, 1), oColor); sprite.End(); String layerName = "map"; switch (curLayer) { case 0: layerName = "back"; break; case 1: layerName = "mid"; break; case 2: layerName = "fore"; break; } if (text.DrawClickText(5, 5, "layer: " + layerName, mosX, mosY, mouseClick)) curLayer = (curLayer + 1) % 3; switch (drawType) { case DRAW_SELECT: layerName = "select"; break; case DRAW_COL: layerName = "col"; break; case DRAW_LEDGE: layerName = "ledge"; break; case DRAW_SCRIPT: layerName = "script"; break; } if (text.DrawClickText(5, 25, "draw: " + layerName, mosX, mosY, mouseClick)) drawType = (drawType + 1) % 4; if (drawType == DRAW_SCRIPT) { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); sprite.Draw(nullTex, new Rectangle(400, 20, 400, 565), new Color( new Vector4(0f, 0f, 0f, .62f))); sprite.End(); for (int i = scriptScroll; i < scriptScroll + 28; i++) { if (selScript == i) { text.SetColor(Color.White); text.DrawText(405, 25 + (i - scriptScroll) * 20, i.ToString() + ": " + map.script[i] + "*"); } else { if (text.DrawClickText(405, 25 + (i - scriptScroll) * 20, i.ToString() + ": " + map.script[i], mosX, mosY, mouseClick)) { selScript = i; editingText = EDITING_SCRIPT; } } if (map.script[i].Length > 0) { String[] split = map.script[i].Split(' '); int c = GetCommandColor(split[0]); if (c > COLOR_NONE) { switch (c) { case COLOR_GREEN: text.SetColor(Color.Lime); break; case COLOR_YELLOW: text.SetColor(Color.Yellow); break; } text.DrawText(405, 25 + (i - scriptScroll) * 20, i.ToString() + ": " + split[0]); } } text.SetColor(Color.White); text.DrawText(405, 25 + (i - scriptScroll) * 20, i.ToString() + ": "); } if (drawButton(770, 20, 1, mosX, mosY, mouseDown) && scriptScroll > 0) scriptScroll--; if (drawButton(770, 550, 2, mosX, mosY, mouseDown) && scriptScroll < map.script.Length - 28) scriptScroll++; } if (drawType == DRAW_LEDGE) { for (int i = 0; i < 16; i++) { int y = 50 + i * 20; if (curLedge == i) { text.SetColor(Color.Lime); text.DrawText(520, 50 + i * 20, "ledge " + i.ToString()); } else { if (text.DrawClickText(520, 50 + i * 20, "ledge " + i.ToString(), mosX, mosY, mouseClick)) curLedge = i; } text.SetColor(Color.White); text.DrawText(620, 50 + i * 20, "n" + map.GetLedgeTotalNodes(i).ToString()); if (text.DrawClickText(680, 50 + i * 20, "f" + map.GetLedgeFlags(i).ToString(), mosX, mosY, mouseClick)) map.SetLedgeFlags(i, (map.GetLedgeFlags(i) + 1) % 2); } } text.SetColor(Color.White); if (editingText == EDITING_PATH) text.DrawText(5, 45, map.path + "*"); else { if (text.DrawClickText(5, 45, map.path, mosX, mosY, mouseClick)) editingText = EDITING_PATH; } if (drawButton(5, 65, 3, mosX, mosY, mouseClick)) { map.Write(); map.Write(true); } if (drawButton(40, 65, 4, mosX, mosY, mouseClick)) { map.Read(); } for (int i = selScroll; i < selScroll + 20; i++) { if (map.GetSegIdx(curLayer, i) > -1) { SegmentDefinition segDef = map.GetSegDef(map.GetSegIdx(curLayer, i)); if (selIdx == i) { text.SetColor(Color.Lime); text.DrawText(5, 100 + (i - selScroll) * 16, segDef.GetName()); } else { if (text.DrawClickText( 5, 100 + (i - selScroll) * 16, segDef.GetName(), mosX, mosY, mouseClick)) { selIdx = i; } } } } if (drawButton(100, 100, 1, mosX, mosY, mouseDown)) { if (selScroll > 0) selScroll--; } if (drawButton(100, 500, 2, mosX, mosY, mouseDown)) { if (selScroll < 43) selScroll++; } if (drawButton(5, 500, 1, mosX, mosY, mouseDown)) { if (selIdx > 0) { map.SwapSegs(curLayer, selIdx, selIdx - 1); selIdx--; } } if (drawButton(25, 500, 2, mosX, mosY, mouseDown)) { if (selIdx < 63) { map.SwapSegs(curLayer, selIdx, selIdx + 1); selIdx++; } } if (drawType == DRAW_SELECT) { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); sprite.Draw(nullTex, new Rectangle(500, 20, 280, 550), new Color( new Vector4(0.0f, 0.0f, 0.0f, 0.4f))); sprite.End(); for (int i = segScroll; i < segScroll + 9; i++) { SegmentDefinition segDef = map.GetSegDef(i); if (segDef != null) { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); dRect.X = 500; dRect.Y = 50 + (i - segScroll) * 60; sRect = segDef.GetSrcRect(); if (sRect.Width > sRect.Height) { dRect.Width = 45; dRect.Height = (int)(((float)sRect.Height / (float)sRect.Width) * 45.0f); } else { dRect.Height = 45; dRect.Width = (int)(((float)sRect.Width / (float)sRect.Height) * 45.0f); } sprite.Draw(mapsTex[map.GetSegDef(i).GetSrcIdx()], dRect, sRect, Color.White); sprite.End(); text.SetSize(0.5f); text.SetColor(Color.White); text.DrawText(dRect.X + 50, dRect.Y, segDef.GetName()); if (mouseDown) { if (mosX > dRect.X && mosX < 700 && mosY > dRect.Y && mosY < dRect.Y + 45) { if (mouseDragSeg == -1) { int f = map.AddSeg(curLayer, i); if (f > -1) { float layerScalar = 0.5f; if (curLayer == 0) layerScalar = 0.375f; if (curLayer == 2) layerScalar = 0.675f; map.SetSegLoc(curLayer, f, new Vector2((float)(mosX - sRect.Width / 4 + scroll.X * layerScalar), (float)(mosY - sRect.Height / 4 + scroll.Y * layerScalar))); mouseDragSeg = f; pMosX = mosX; pMosY = mosY; } } } } } } if (drawButton(740, 20, 1, mosX, mosY, mouseDown)) { if (segScroll > 0) segScroll--; } if (drawButton(740, 550, 2, mosX, mosY, mouseDown)) { if (segScroll < 80) segScroll++; } } Vector2 v = new Vector2((float)mosX, (float)mosY) + scroll / 2.0f; v *= 2f; text.SetSize(.5f); text.SetColor(Color.White); text.DrawText(5, 580, ((int)v.X).ToString() + ", " + ((int)v.Y).ToString()); DrawCursor(); mouseClick = false; base.Draw(gameTime); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AsteroidsGenerator : MonoBehaviour { public GameObject[] asteroids; private Vector3 origin = Vector3.zero; /// <summary> /// The minimum and maximum allowed size of an asteroid. /// </summary> public float minSize = 0.2f; public float maxSize = 1.5f; /// <summary> /// The minimum and maximum amount of asteroids. /// </summary> public int minCount = 500; public int maxCount = 1200; /// <summary> /// The minimum and maximum distance between asteroids. /// </summary> public float minDistance = 30.0f; public float maxDistance = 150.0f; void Start() { origin = transform.position; GenerateAsteroids(Random.Range(minCount, maxCount)); } /// <summary> /// Generates a number (asteroidsCount) of asteroids with a random size between minSize and /// maxSize and a random distance between them from minDistance to maxDistance. /// </summary> /// <param name="asteroidsCount">Number of Asteroids to Generate</param> public void GenerateAsteroids(int asteroidsCount) { for (int i = 0; i < asteroidsCount; i++) { float size = Random.Range(minSize, maxSize); GameObject prefab = asteroids[Random.Range(0, asteroids.Length)]; Vector3 position = Vector3.zero; for (int j = 0; j < 100; j++) { position = Random.insideUnitSphere * (minDistance + (maxDistance - minDistance) * Random.value); position += origin; if (!Physics.CheckSphere(position, size / 2.0f)) { break; } } GameObject go = Instantiate(prefab, position, Random.rotation); go.transform.localScale = new Vector3(size, size, size); setMineralAndCount(go); setMouvement(go); } } #region MineralCountSetter public int[] mineralCountProbability; public int[] mineralIdProbability = { 25, 40, 60, 75, 90, 100 }; private int[] idMineral = { 100, 101, 102, 103, 104, 105 }; private void setMineralAndCount(GameObject toSet) { Asteroid astToSet = toSet.GetComponent<Asteroid>(); if (astToSet == null) { Debug.Log("Asteroid script not found"); return; } //Set the mineral count int max = Mathf.Max(mineralCountProbability); int rand = (int)(Random.value * max); int i; for (i = 0; i < mineralCountProbability.Length && rand > mineralCountProbability[i]; i++) { } astToSet.count = i; //Set the mineral ID max = Mathf.Max(mineralIdProbability); rand = (int)(Random.value * max); for (i = 0; i < mineralIdProbability.Length && rand > mineralIdProbability[i]; i++) { } astToSet.idMineral = idMineral[i]; switch (astToSet.idMineral) { case 100: break; case 101: break; case 102: break; case 103: break; case 104: break; case 105: break; default: break; } setTexture(toSet, astToSet.idMineral); } #endregion #region MovementSetter private Rigidbody rb; /// <summary> /// The minimum and maximum rotation speed allowed for an asteroid. /// </summary> public int minrSpeed = 1; public int maxrSpeed = 8; /// <summary> /// rxSpeed : rotation speed around x axis. /// rySpeed : rotation speed around y axis. /// rzSpeed : rotation speed around z axis. /// </summary> private int rxSpeed; private int rySpeed; private int rzSpeed; /// <summary> /// The minimum and maximum movement speed allowed for an asteroid. /// </summary> public int minmSpeed = 10; public int maxmSpeed = 200; /// <summary> /// mxSpeed : movement speed on x axis. /// mySpeed : movement speed on y axis. /// mzSpeed : movement speed on z axis. /// </summary> private int mxSpeed = 0; private int mySpeed = 0; private int mzSpeed = 0; /// <summary> /// Attribute the rotation and movement speed for the asteroid. /// Apply a force to the asteroid. /// </summary> private void setMouvement(GameObject toSet) { rb = toSet.GetComponent<Rigidbody>(); if (rb == null) { Debug.Log("Rigibody not found on new asteroid"); return; } mxSpeed = Random.Range(minmSpeed, maxmSpeed); mySpeed = Random.Range(minmSpeed, maxmSpeed); mzSpeed = Random.Range(minmSpeed, maxmSpeed); rxSpeed = Random.Range(minrSpeed, maxrSpeed); rySpeed = Random.Range(minrSpeed, maxrSpeed); rzSpeed = Random.Range(minrSpeed, maxrSpeed); Vector3 movement = new Vector3(mxSpeed, mySpeed, mzSpeed); rb.AddForce(movement); Vector3 rotation = new Vector3(rxSpeed, rySpeed, rzSpeed); rb.AddTorque(rotation); } #endregion #region textureSetter //List of texture public Texture[] texture; private void setTexture(GameObject toSet, int id) { int i = id - 100; if (i >= 0 && i < texture.Length) { toSet.GetComponent<Renderer>().material.mainTexture = texture[i]; } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; namespace System.Reflection.Metadata { public sealed class MethodBodyBlock { private readonly MemoryBlock _il; private readonly int _size; private readonly ushort _maxStack; private readonly bool _localVariablesInitialized; private readonly StandaloneSignatureHandle _localSignature; private readonly ImmutableArray<ExceptionRegion> _exceptionRegions; private MethodBodyBlock( bool localVariablesInitialized, ushort maxStack, StandaloneSignatureHandle localSignatureHandle, MemoryBlock il, ImmutableArray<ExceptionRegion> exceptionRegions, int size) { Debug.Assert(!exceptionRegions.IsDefault); _localVariablesInitialized = localVariablesInitialized; _maxStack = maxStack; _localSignature = localSignatureHandle; _il = il; _exceptionRegions = exceptionRegions; _size = size; } /// <summary> /// Size of the method body - includes the header, IL and exception regions. /// </summary> public int Size { get { return _size; } } public int MaxStack { get { return _maxStack; } } public bool LocalVariablesInitialized { get { return _localVariablesInitialized; } } public StandaloneSignatureHandle LocalSignature { get { return _localSignature; } } public ImmutableArray<ExceptionRegion> ExceptionRegions { get { return _exceptionRegions; } } public byte[] GetILBytes() { return _il.ToArray(); } public ImmutableArray<byte> GetILContent() { byte[] bytes = GetILBytes(); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetILReader() { return new BlobReader(_il); } private const byte ILTinyFormat = 0x02; private const byte ILFatFormat = 0x03; private const byte ILFormatMask = 0x03; private const int ILTinyFormatSizeShift = 2; private const byte ILMoreSects = 0x08; private const byte ILInitLocals = 0x10; private const byte ILFatFormatHeaderSize = 0x03; private const int ILFatFormatHeaderSizeShift = 4; private const byte SectEHTable = 0x01; private const byte SectOptILTable = 0x02; private const byte SectFatFormat = 0x40; private const byte SectMoreSects = 0x40; public static MethodBodyBlock Create(BlobReader reader) { int startOffset = reader.Offset; int ilSize; // Error need to check if the Memory Block is empty. This is false for all the calls... byte headByte = reader.ReadByte(); if ((headByte & ILFormatMask) == ILTinyFormat) { // tiny IL can't have locals so technically this shouldn't matter, // but false is consistent with other metadata readers and helps // for use cases involving comparing our output with theirs. const bool initLocalsForTinyIL = false; ilSize = headByte >> ILTinyFormatSizeShift; return new MethodBodyBlock( initLocalsForTinyIL, 8, default(StandaloneSignatureHandle), reader.GetMemoryBlockAt(0, ilSize), ImmutableArray<ExceptionRegion>.Empty, 1 + ilSize // header + IL ); } if ((headByte & ILFormatMask) != ILFatFormat) { throw new BadImageFormatException(SR.Format(SR.InvalidMethodHeader1, headByte)); } // FatILFormat byte headByte2 = reader.ReadByte(); if ((headByte2 >> ILFatFormatHeaderSizeShift) != ILFatFormatHeaderSize) { throw new BadImageFormatException(SR.Format(SR.InvalidMethodHeader2, headByte, headByte2)); } bool localsInitialized = (headByte & ILInitLocals) == ILInitLocals; bool hasExceptionHandlers = (headByte & ILMoreSects) == ILMoreSects; ushort maxStack = reader.ReadUInt16(); ilSize = reader.ReadInt32(); int localSignatureToken = reader.ReadInt32(); StandaloneSignatureHandle localSignatureHandle; if (localSignatureToken == 0) { localSignatureHandle = default(StandaloneSignatureHandle); } else if ((localSignatureToken & TokenTypeIds.TypeMask) == TokenTypeIds.Signature) { localSignatureHandle = StandaloneSignatureHandle.FromRowId((int)((uint)localSignatureToken & TokenTypeIds.RIDMask)); } else { throw new BadImageFormatException(SR.Format(SR.InvalidLocalSignatureToken, unchecked((uint)localSignatureToken))); } var ilBlock = reader.GetMemoryBlockAt(0, ilSize); reader.SkipBytes(ilSize); ImmutableArray<ExceptionRegion> exceptionHandlers; if (hasExceptionHandlers) { reader.Align(4); byte sehHeader = reader.ReadByte(); if ((sehHeader & SectEHTable) != SectEHTable) { throw new BadImageFormatException(SR.Format(SR.InvalidSehHeader, sehHeader)); } bool sehFatFormat = (sehHeader & SectFatFormat) == SectFatFormat; int dataSize = reader.ReadByte(); if (sehFatFormat) { dataSize += reader.ReadUInt16() << 8; exceptionHandlers = ReadFatExceptionHandlers(ref reader, dataSize / 24); } else { reader.SkipBytes(2); // skip over reserved field exceptionHandlers = ReadSmallExceptionHandlers(ref reader, dataSize / 12); } } else { exceptionHandlers = ImmutableArray<ExceptionRegion>.Empty; } return new MethodBodyBlock( localsInitialized, maxStack, localSignatureHandle, ilBlock, exceptionHandlers, reader.Offset - startOffset); } private static ImmutableArray<ExceptionRegion> ReadSmallExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var kind = (ExceptionRegionKind)memReader.ReadUInt16(); var tryOffset = memReader.ReadUInt16(); var tryLength = memReader.ReadByte(); var handlerOffset = memReader.ReadUInt16(); var handlerLength = memReader.ReadByte(); var classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(kind, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } private static ImmutableArray<ExceptionRegion> ReadFatExceptionHandlers(ref BlobReader memReader, int count) { var result = new ExceptionRegion[count]; for (int i = 0; i < result.Length; i++) { var sehFlags = (ExceptionRegionKind)memReader.ReadUInt32(); int tryOffset = memReader.ReadInt32(); int tryLength = memReader.ReadInt32(); int handlerOffset = memReader.ReadInt32(); int handlerLength = memReader.ReadInt32(); int classTokenOrFilterOffset = memReader.ReadInt32(); result[i] = new ExceptionRegion(sehFlags, tryOffset, tryLength, handlerOffset, handlerLength, classTokenOrFilterOffset); } return ImmutableArray.Create(result); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.Util; using System.Text; using System; namespace NPOI.HWPF.Model.Types { /** * File Shape Address (FSPA). * <p> * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 * Binary File Format * * <p> * NOTE: This source is automatically generated please do not modify this file. * Either subclass or remove the record in src/types/defInitions. * <p> * This class is internal. It content or properties may change without notice * due to Changes in our knowledge of internal Microsoft Word binary structures. * * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary * File Format Specification [*.doc] */ public abstract class FSPAAbstractType : BaseObject { protected int field_1_spid; protected int field_2_xaLeft; protected int field_3_yaTop; protected int field_4_xaRight; protected int field_5_yaBottom; protected short field_6_flags; private static BitField fHdr = new BitField(0x0001); private static BitField bx = new BitField(0x0006); private static BitField by = new BitField(0x0018); private static BitField wr = new BitField(0x01E0); private static BitField wrk = new BitField(0x1E00); private static BitField fRcaSimple = new BitField(0x2000); private static BitField fBelowText = new BitField(0x4000); private static BitField fAnchorLock = new BitField(0x8000); protected int field_7_cTxbx; protected FSPAAbstractType() { } protected void FillFields(byte[] data, int offset) { field_1_spid = LittleEndian.GetInt(data, 0x0 + offset); field_2_xaLeft = LittleEndian.GetInt(data, 0x4 + offset); field_3_yaTop = LittleEndian.GetInt(data, 0x8 + offset); field_4_xaRight = LittleEndian.GetInt(data, 0xc + offset); field_5_yaBottom = LittleEndian.GetInt(data, 0x10 + offset); field_6_flags = LittleEndian.GetShort(data, 0x14 + offset); field_7_cTxbx = LittleEndian.GetInt(data, 0x16 + offset); } public void Serialize(byte[] data, int offset) { LittleEndian.PutInt(data, 0x0 + offset, field_1_spid); LittleEndian.PutInt(data, 0x4 + offset, field_2_xaLeft); LittleEndian.PutInt(data, 0x8 + offset, field_3_yaTop); LittleEndian.PutInt(data, 0xc + offset, field_4_xaRight); LittleEndian.PutInt(data, 0x10 + offset, field_5_yaBottom); LittleEndian.PutShort(data, 0x14 + offset, (short)field_6_flags); LittleEndian.PutInt(data, 0x16 + offset, field_7_cTxbx); } /** * Size of record */ public static int GetSize() { return 0 + 4 + 4 + 4 + 4 + 4 + 2 + 4; } public override String ToString() { StringBuilder builder = new StringBuilder(); builder.Append("[FSPA]\n"); builder.Append(" .spid = "); builder.Append(" (").Append(GetSpid()).Append(" )\n"); builder.Append(" .xaLeft = "); builder.Append(" (").Append(GetXaLeft()).Append(" )\n"); builder.Append(" .yaTop = "); builder.Append(" (").Append(GetYaTop()).Append(" )\n"); builder.Append(" .xaRight = "); builder.Append(" (").Append(GetXaRight()).Append(" )\n"); builder.Append(" .yaBottom = "); builder.Append(" (").Append(GetYaBottom()).Append(" )\n"); builder.Append(" .flags = "); builder.Append(" (").Append(GetFlags()).Append(" )\n"); builder.Append(" .fHdr = ").Append(IsFHdr()).Append('\n'); builder.Append(" .bx = ").Append(GetBx()).Append('\n'); builder.Append(" .by = ").Append(GetBy()).Append('\n'); builder.Append(" .wr = ").Append(GetWr()).Append('\n'); builder.Append(" .wrk = ").Append(GetWrk()).Append('\n'); builder.Append(" .fRcaSimple = ").Append(IsFRcaSimple()).Append('\n'); builder.Append(" .fBelowText = ").Append(IsFBelowText()).Append('\n'); builder.Append(" .fAnchorLock = ").Append(IsFAnchorLock()).Append('\n'); builder.Append(" .cTxbx = "); builder.Append(" (").Append(GetCTxbx()).Append(" )\n"); builder.Append("[/FSPA]\n"); return builder.ToString(); } /** * Shape Identifier. Used in conjunction with the office art data (found via fcDggInfo in the FIB) to find the actual data for this shape. */ public int GetSpid() { return field_1_spid; } /** * Shape Identifier. Used in conjunction with the office art data (found via fcDggInfo in the FIB) to find the actual data for this shape. */ public void SetSpid(int field_1_spid) { this.field_1_spid = field_1_spid; } /** * Left of rectangle enclosing shape relative to the origin of the shape. */ public int GetXaLeft() { return field_2_xaLeft; } /** * Left of rectangle enclosing shape relative to the origin of the shape. */ public void SetXaLeft(int field_2_xaLeft) { this.field_2_xaLeft = field_2_xaLeft; } /** * Top of rectangle enclosing shape relative to the origin of the shape. */ public int GetYaTop() { return field_3_yaTop; } /** * Top of rectangle enclosing shape relative to the origin of the shape. */ public void SetYaTop(int field_3_yaTop) { this.field_3_yaTop = field_3_yaTop; } /** * Right of rectangle enclosing shape relative to the origin of the shape. */ public int GetXaRight() { return field_4_xaRight; } /** * Right of rectangle enclosing shape relative to the origin of the shape. */ public void SetXaRight(int field_4_xaRight) { this.field_4_xaRight = field_4_xaRight; } /** * Bottom of the rectangle enclosing shape relative to the origin of the shape. */ public int GetYaBottom() { return field_5_yaBottom; } /** * Bottom of the rectangle enclosing shape relative to the origin of the shape. */ public void SetYaBottom(int field_5_yaBottom) { this.field_5_yaBottom = field_5_yaBottom; } /** * Get the flags field for the FSPA record. */ public short GetFlags() { return field_6_flags; } /** * Set the flags field for the FSPA record. */ public void SetFlags(short field_6_flags) { this.field_6_flags = field_6_flags; } /** * Count of textboxes in shape (undo doc only). */ public int GetCTxbx() { return field_7_cTxbx; } /** * Count of textboxes in shape (undo doc only). */ public void SetCTxbx(int field_7_cTxbx) { this.field_7_cTxbx = field_7_cTxbx; } /** * Sets the fHdr field value. * 1 in the undo doc when shape is from the header doc, 0 otherwise (undefined when not in the undo doc) */ public void SetFHdr(bool value) { field_6_flags = (short)fHdr.SetBoolean(field_6_flags, value); } /** * 1 in the undo doc when shape is from the header doc, 0 otherwise (undefined when not in the undo doc) * @return the fHdr field value. */ public bool IsFHdr() { return fHdr.IsSet(field_6_flags); } /** * Sets the bx field value. * X position of shape relative to anchor CP */ public void SetBx(byte value) { field_6_flags = (short)bx.SetValue(field_6_flags, value); } /** * X position of shape relative to anchor CP * @return the bx field value. */ public byte GetBx() { return (byte)bx.GetValue(field_6_flags); } /** * Sets the by field value. * Y position of shape relative to anchor CP */ public void SetBy(byte value) { field_6_flags = (short)by.SetValue(field_6_flags, value); } /** * Y position of shape relative to anchor CP * @return the by field value. */ public byte GetBy() { return (byte)by.GetValue(field_6_flags); } /** * Sets the wr field value. * Text wrapping mode */ public void SetWr(byte value) { field_6_flags = (short)wr.SetValue(field_6_flags, value); } /** * Text wrapping mode * @return the wr field value. */ public byte GetWr() { return (byte)wr.GetValue(field_6_flags); } /** * Sets the wrk field value. * Text wrapping mode type (valid only for wrapping modes 2 and 4 */ public void SetWrk(byte value) { field_6_flags = (short)wrk.SetValue(field_6_flags, value); } /** * Text wrapping mode type (valid only for wrapping modes 2 and 4 * @return the wrk field value. */ public byte GetWrk() { return (byte)wrk.GetValue(field_6_flags); } /** * Sets the fRcaSimple field value. * When Set, temporarily overrides bx, by, forcing the xaLeft, xaRight, yaTop, and yaBottom fields to all be page relative. */ public void SetFRcaSimple(bool value) { field_6_flags = (short)fRcaSimple.SetBoolean(field_6_flags, value); } /** * When Set, temporarily overrides bx, by, forcing the xaLeft, xaRight, yaTop, and yaBottom fields to all be page relative. * @return the fRcaSimple field value. */ public bool IsFRcaSimple() { return fRcaSimple.IsSet(field_6_flags); } /** * Sets the fBelowText field value. * */ public void SetFBelowText(bool value) { field_6_flags = (short)fBelowText.SetBoolean(field_6_flags, value); } /** * * @return the fBelowText field value. */ public bool IsFBelowText() { return fBelowText.IsSet(field_6_flags); } /** * Sets the fAnchorLock field value. * */ public void SetFAnchorLock(bool value) { field_6_flags = (short)fAnchorLock.SetBoolean(field_6_flags, value); } /** * * @return the fAnchorLock field value. */ public bool IsFAnchorLock() { return fAnchorLock.IsSet(field_6_flags); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class divremTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunDivRem_TwoLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [Fact] public static void RunDivRem_TwoSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [Fact] public static void RunDivRem_OneSmallOneLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One Large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [Fact] public static void RunDivRem_OneLargeOne0BI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One Large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } } [Fact] public static void RunDivRem_OneSmallOne0BI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } } [Fact] public static void Boundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivRemString(Math.Pow(2, 32) + " 2 bDivRem"); // 32 bit boundary n1=0 n2=1 VerifyDivRemString(Math.Pow(2, 33) + " 2 bDivRem"); } [Fact] public static void RunDivRemTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - One Large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - One Large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } // DivRem Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivRemString(Math.Pow(2, 32) + " 2 bDivRem"); // 32 bit boundary n1=0 n2=1 VerifyDivRemString(Math.Pow(2, 33) + " 2 bDivRem"); } private static void VerifyDivRemString(string opstring) { try { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); sc.VerifyOutParameter(); } } catch(Exception e) when (!(e is DivideByZeroException)) { // Log the original parameters, so we can reproduce any failure given the log throw new Exception($"VerifyDivRemString failed: {opstring} {e.ToString()}", e); } } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
namespace GMap.NET { using System; using System.Globalization; /// <summary> /// the rect /// </summary> public struct Rectangle { public static readonly Rectangle Empty = new Rectangle(); private int x; private int y; private int width; private int height; public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public Rectangle(Point location, Size size) { this.x = location.X; this.y = location.Y; this.width = size.Width; this.height = size.Height; } public static Rectangle FromLTRB(int left, int top, int right, int bottom) { return new Rectangle(left, top, right - left, bottom - top); } public Point Location { get { return new Point(X, Y); } set { X = value.X; Y = value.Y; } } public Size Size { get { return new Size(Width, Height); } set { this.Width = value.Width; this.Height = value.Height; } } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public int Width { get { return width; } set { width = value; } } public int Height { get { return height; } set { height = value; } } public int Left { get { return X; } } public int Top { get { return Y; } } public int Right { get { return X + Width; } } public int Bottom { get { return Y + Height; } } public bool IsEmpty { get { return height == 0 && width == 0 && x == 0 && y == 0; } } public override bool Equals(object obj) { if(!(obj is Rectangle)) return false; Rectangle comp = (Rectangle) obj; return (comp.X == this.X) && (comp.Y == this.Y) && (comp.Width == this.Width) && (comp.Height == this.Height); } public static bool operator==(Rectangle left, Rectangle right) { return (left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height); } public static bool operator!=(Rectangle left, Rectangle right) { return !(left == right); } public bool Contains(int x, int y) { return this.X <= x && x < this.X + this.Width && this.Y <= y && y < this.Y + this.Height; } public bool Contains(Point pt) { return Contains(pt.X, pt.Y); } public bool Contains(Rectangle rect) { return (this.X <= rect.X) && ((rect.X + rect.Width) <= (this.X + this.Width)) && (this.Y <= rect.Y) && ((rect.Y + rect.Height) <= (this.Y + this.Height)); } public override int GetHashCode() { return (int) ((UInt32) X ^ (((UInt32) Y << 13) | ((UInt32) Y >> 19)) ^ (((UInt32) Width << 26) | ((UInt32) Width >> 6)) ^ (((UInt32) Height << 7) | ((UInt32) Height >> 25))); } public void Inflate(int width, int height) { this.X -= width; this.Y -= height; this.Width += 2*width; this.Height += 2*height; } public void Inflate(Size size) { Inflate(size.Width, size.Height); } public static Rectangle Inflate(Rectangle rect, int x, int y) { Rectangle r = rect; r.Inflate(x, y); return r; } public void Intersect(Rectangle rect) { Rectangle result = Rectangle.Intersect(rect, this); this.X = result.X; this.Y = result.Y; this.Width = result.Width; this.Height = result.Height; } public static Rectangle Intersect(Rectangle a, Rectangle b) { int x1 = Math.Max(a.X, b.X); int x2 = Math.Min(a.X + a.Width, b.X + b.Width); int y1 = Math.Max(a.Y, b.Y); int y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if(x2 >= x1 && y2 >= y1) { return new Rectangle(x1, y1, x2 - x1, y2 - y1); } return Rectangle.Empty; } public bool IntersectsWith(Rectangle rect) { return (rect.X < this.X + this.Width) && (this.X < (rect.X + rect.Width)) && (rect.Y < this.Y + this.Height) && (this.Y < rect.Y + rect.Height); } public static Rectangle Union(Rectangle a, Rectangle b) { int x1 = Math.Min(a.X, b.X); int x2 = Math.Max(a.X + a.Width, b.X + b.Width); int y1 = Math.Min(a.Y, b.Y); int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new Rectangle(x1, y1, x2 - x1, y2 - y1); } public void Offset(Point pos) { Offset(pos.X, pos.Y); } public void Offset(int x, int y) { this.X += x; this.Y += y; } public override string ToString() { return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) + ",Width=" + Width.ToString(CultureInfo.CurrentCulture) + ",Height=" + Height.ToString(CultureInfo.CurrentCulture) + "}"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; namespace Internal.TypeSystem { public static class TypeSystemHelpers { public static bool IsWellKnownType(this TypeDesc type, WellKnownType wellKnownType) { return type == type.Context.GetWellKnownType(wellKnownType, false); } public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, Instantiation instantiation) { return typeDef.Context.GetInstantiatedType(typeDef, instantiation); } public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, params TypeDesc[] genericParameters) { return typeDef.Context.GetInstantiatedType(typeDef, new Instantiation(genericParameters)); } public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, Instantiation instantiation) { return methodDef.Context.GetInstantiatedMethod(methodDef, instantiation); } public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, params TypeDesc[] genericParameters) { return methodDef.Context.GetInstantiatedMethod(methodDef, new Instantiation(genericParameters)); } public static ArrayType MakeArrayType(this TypeDesc type) { return type.Context.GetArrayType(type); } /// <summary> /// Creates a multidimensional array type with the specified rank. /// To create a vector, use the <see cref="MakeArrayType(TypeDesc)"/> overload. /// </summary> public static ArrayType MakeArrayType(this TypeDesc type, int rank) { return type.Context.GetArrayType(type, rank); } public static ByRefType MakeByRefType(this TypeDesc type) { return type.Context.GetByRefType(type); } public static PointerType MakePointerType(this TypeDesc type) { return type.Context.GetPointerType(type); } public static TypeDesc GetParameterType(this TypeDesc type) { ParameterizedType paramType = (ParameterizedType) type; return paramType.ParameterType; } public static LayoutInt GetElementSize(this TypeDesc type) { if (type.IsValueType) { return ((DefType)type).InstanceFieldSize; } else { return type.Context.Target.LayoutPointerSize; } } /// <summary> /// Gets the parameterless instance constructor on the specified type. To get the default constructor, use <see cref="TypeDesc.GetDefaultConstructor"/>. /// </summary> public static MethodDesc GetParameterlessConstructor(this TypeDesc type) { // TODO: Do we want check for specialname/rtspecialname? Maybe add another overload on GetMethod? var sig = new MethodSignature(0, 0, type.Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes); return type.GetMethod(".ctor", sig); } public static bool HasExplicitOrImplicitDefaultConstructor(this TypeDesc type) { return type.IsValueType || type.GetDefaultConstructor() != null; } internal static MethodDesc FindMethodOnExactTypeWithMatchingTypicalMethod(this TypeDesc type, MethodDesc method) { MethodDesc methodTypicalDefinition = method.GetTypicalMethodDefinition(); var instantiatedType = type as InstantiatedType; if (instantiatedType != null) { Debug.Assert(instantiatedType.GetTypeDefinition() == methodTypicalDefinition.OwningType); return method.Context.GetMethodForInstantiatedType(methodTypicalDefinition, instantiatedType); } else if (type.IsArray) { Debug.Assert(method.OwningType.IsArray); return ((ArrayType)type).GetArrayMethod(((ArrayMethod)method).Kind); } else { Debug.Assert(type == methodTypicalDefinition.OwningType); return methodTypicalDefinition; } } /// <summary> /// Returns method as defined on a non-generic base class or on a base /// instantiation. /// For example, If Foo&lt;T&gt; : Bar&lt;T&gt; and overrides method M, /// if method is Bar&lt;string&gt;.M(), then this returns Bar&lt;T&gt;.M() /// but if Foo : Bar&lt;string&gt;, then this returns Bar&lt;string&gt;.M() /// </summary> /// <param name="targetType">A potentially derived type</param> /// <param name="method">A base class's virtual method</param> public static MethodDesc FindMethodOnTypeWithMatchingTypicalMethod(this TypeDesc targetType, MethodDesc method) { // If method is nongeneric and on a nongeneric type, then it is the matching method if (!method.HasInstantiation && !method.OwningType.HasInstantiation) { return method; } // Since method is an instantiation that may or may not be the same as typeExamine's hierarchy, // find a matching base class on an open type and then work from the instantiation in typeExamine's // hierarchy TypeDesc typicalTypeOfTargetMethod = method.GetTypicalMethodDefinition().OwningType; TypeDesc targetOrBase = targetType; do { TypeDesc openTargetOrBase = targetOrBase; if (openTargetOrBase is InstantiatedType) { openTargetOrBase = openTargetOrBase.GetTypeDefinition(); } if (openTargetOrBase == typicalTypeOfTargetMethod) { // Found an open match. Now find an equivalent method on the original target typeOrBase MethodDesc matchingMethod = targetOrBase.FindMethodOnExactTypeWithMatchingTypicalMethod(method); return matchingMethod; } targetOrBase = targetOrBase.BaseType; } while (targetOrBase != null); Debug.Assert(false, "method has no related type in the type hierarchy of type"); return null; } /// <summary> /// Attempts to resolve constrained call to <paramref name="interfaceMethod"/> into a concrete non-unboxing /// method on <paramref name="constrainedType"/>. /// The ability to resolve constraint methods is affected by the degree of code sharing we are performing /// for generic code. /// </summary> /// <returns>The resolved method or null if the constraint couldn't be resolved.</returns> public static MethodDesc TryResolveConstraintMethodApprox(this TypeDesc constrainedType, TypeDesc interfaceType, MethodDesc interfaceMethod, out bool forceRuntimeLookup) { forceRuntimeLookup = false; // We can't resolve constraint calls effectively for reference types, and there's // not a lot of perf. benefit in doing it anyway. if (!constrainedType.IsValueType) { return null; } // Non-virtual methods called through constraints simply resolve to the specified method without constraint resolution. if (!interfaceMethod.IsVirtual) { return null; } MethodDesc method; MethodDesc genInterfaceMethod = interfaceMethod.GetMethodDefinition(); if (genInterfaceMethod.OwningType.IsInterface) { // Sometimes (when compiling shared generic code) // we don't have enough exact type information at JIT time // even to decide whether we will be able to resolve to an unboxed entry point... // To cope with this case we always go via the helper function if there's any // chance of this happening by checking for all interfaces which might possibly // be compatible with the call (verification will have ensured that // at least one of them will be) // Enumerate all potential interface instantiations // TODO: this code assumes no shared generics Debug.Assert(interfaceType == interfaceMethod.OwningType); method = constrainedType.ResolveInterfaceMethodToVirtualMethodOnType(genInterfaceMethod); } else if (genInterfaceMethod.IsVirtual) { method = constrainedType.FindVirtualFunctionTargetMethodOnObjectType(genInterfaceMethod); } else { // The method will be null if calling a non-virtual instance // methods on System.Object, i.e. when these are used as a constraint. method = null; } if (method == null) { // Fall back to VSD return null; } //#TryResolveConstraintMethodApprox_DoNotReturnParentMethod // Only return a method if the value type itself declares the method, // otherwise we might get a method from Object or System.ValueType if (!method.OwningType.IsValueType) { // Fall back to VSD return null; } // We've resolved the method, ignoring its generic method arguments // If the method is a generic method then go and get the instantiated descriptor if (interfaceMethod.HasInstantiation) { method = method.MakeInstantiatedMethod(interfaceMethod.Instantiation); } Debug.Assert(method != null); //assert(!pMD->IsUnboxingStub()); return method; } /// <summary> /// Retrieves the namespace qualified name of a <see cref="DefType"/>. /// </summary> public static string GetFullName(this DefType metadataType) { string ns = metadataType.Namespace; return ns.Length > 0 ? String.Concat(ns, ".", metadataType.Name) : metadataType.Name; } /// <summary> /// Retrieves all methods on a type, including the ones injected by the type system context. /// </summary> public static IEnumerable<MethodDesc> GetAllMethods(this TypeDesc type) { return type.Context.GetAllMethods(type); } public static IEnumerable<MethodDesc> EnumAllVirtualSlots(this TypeDesc type) { return type.Context.GetVirtualMethodAlgorithmForType(type).ComputeAllVirtualSlots(type); } /// <summary> /// Resolves interface method '<paramref name="interfaceMethod"/>' to a method on '<paramref name="type"/>' /// that implements the the method. /// </summary> public static MethodDesc ResolveInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod) { return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod, type); } /// <summary> /// Resolves a virtual method call. /// </summary> public static MethodDesc FindVirtualFunctionTargetMethodOnObjectType(this TypeDesc type, MethodDesc targetMethod) { return type.Context.GetVirtualMethodAlgorithmForType(type).FindVirtualFunctionTargetMethodOnObjectType(targetMethod, type); } /// <summary> /// Creates an open instantiation of a type. Given Foo&lt;T&gt;, returns Foo&lt;!0&gt;. /// If the type is not generic, returns the <paramref name="type"/>. /// </summary> public static TypeDesc InstantiateAsOpen(this TypeDesc type) { if (!type.IsGenericDefinition) { Debug.Assert(!type.HasInstantiation); return type; } TypeSystemContext context = type.Context; var inst = new TypeDesc[type.Instantiation.Length]; for (int i = 0; i < inst.Length; i++) { inst[i] = context.GetSignatureVariable(i, false); } return context.GetInstantiatedType((MetadataType)type, new Instantiation(inst)); } /// <summary> /// Creates an open instantiation of a field. Given Foo&lt;T&gt;.Field, returns /// Foo&lt;!0&gt;.Field. If the owning type is not generic, returns the <paramref name="field"/>. /// </summary> public static FieldDesc InstantiateAsOpen(this FieldDesc field) { Debug.Assert(field.GetTypicalFieldDefinition() == field); TypeDesc owner = field.OwningType; if (owner.HasInstantiation) { var instantiatedOwner = (InstantiatedType)owner.InstantiateAsOpen(); return field.Context.GetFieldForInstantiatedType(field, instantiatedOwner); } return field; } /// <summary> /// Creates an open instantiation of a method. Given Foo&lt;T&gt;.Method, returns /// Foo&lt;!0&gt;.Method. If the owning type is not generic, returns the <paramref name="method"/>. /// </summary> public static MethodDesc InstantiateAsOpen(this MethodDesc method) { Debug.Assert(method.IsMethodDefinition && !method.HasInstantiation); TypeDesc owner = method.OwningType; if (owner.HasInstantiation) { MetadataType instantiatedOwner = (MetadataType)owner.InstantiateAsOpen(); return method.Context.GetMethodForInstantiatedType(method, (InstantiatedType)instantiatedOwner); } return method; } /// <summary> /// Scan the type and its base types for an implementation of an interface method. Returns null if no /// implementation is found. /// </summary> public static MethodDesc ResolveInterfaceMethodTarget(this TypeDesc thisType, MethodDesc interfaceMethodToResolve) { Debug.Assert(interfaceMethodToResolve.OwningType.IsInterface); MethodDesc result = null; TypeDesc currentType = thisType; do { result = currentType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethodToResolve); currentType = currentType.BaseType; } while (result == null && currentType != null); return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Globalization; using error = Microsoft.Build.Shared.ErrorUtilities; namespace Microsoft.Build.Conversion { /// <summary> /// This class implements a custom text reader for the old VS7/Everett /// project file format. The old format allowed certain XML special /// characters to be present within an XML attribute value. For example, /// /// &lt;MyElement MyAttribute="My --> Value" /&gt; /// /// However, the System.Xml classes are more strict, and do not allow /// the &lt; or &gt; characters to exist within an attribute value. But /// the conversion utility still needs to be able to convert all old /// project files. So the OldVSProjectFileReader class implements /// the TextReader interface, thereby effectively intercepting all of /// the calls which are used by the XmlTextReader to actually read the /// raw text out of the file. As we are reading the text out of the /// file, we replace all &gt; (less-than) characters inside attribute values with "&gt;", /// etc. The XmlTextReader has no idea that this is going on, but /// no longer complains about invalid characters. /// </summary> /// <owner>rgoel</owner> internal sealed class OldVSProjectFileReader : TextReader { // This is the underlying text file where we will be reading the raw text // from. private StreamReader oldVSProjectFile; // We will be reading one line at a time out of the text file, and caching // it here. private StringBuilder singleLine; // The "TextReader" interface that we are implementing only allows // forward access through the file. You cannot seek to a random location // or read backwards. This variable is the index into the "singleLine" // string above, which indicates how far the caller has read. Once we // reach the end of "singleLine", we'll go read a new line from the file. private int currentReadPositionWithinSingleLine; /// <summary> /// Constructor, initialized using the filename of an existing old format /// project file on disk. /// </summary> /// <owner>rgoel</owner> /// <param name="filename"></param> internal OldVSProjectFileReader ( string filename ) { this.oldVSProjectFile = new StreamReader(filename, Encoding.Default); // HIGHCHAR: Default means ANSI, ANSI is what VS .NET 2003 wrote. Without this, the project would be read as ASCII. this.singleLine = new StringBuilder(); this.currentReadPositionWithinSingleLine = 0; } /// <summary> /// Releases all locks and closes all handles on the underlying file. /// </summary> /// <owner>rgoel</owner> public override void Close ( ) { oldVSProjectFile.Close(); } /// <summary> /// Returns the next character in the file, without actually advancing /// the read pointer. Returns -1 if we're already at the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override int Peek ( ) { // If necessary, read a new line of text into our internal buffer // (this.singleLine). if (!this.ReadLineIntoInternalBuffer()) { // If we've reached the end of the file, return -1. return -1; } // Return the next character, but don't advance the current position. return this.singleLine[this.currentReadPositionWithinSingleLine]; } /// <summary> /// Returns the next character in the file, and advances the read pointer. /// Returns -1 if we're already at the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override int Read ( ) { // Use our "Peek" functionality above. int returnCharacter = this.Peek(); // If there's a character there, advance the read pointer by one. if (returnCharacter != -1) { this.currentReadPositionWithinSingleLine++; } return returnCharacter; } /// <summary> /// Reads the specified number of characters into the caller's buffer, /// starting at the specified index into the caller's buffer. Returns /// the number of characters read, or 0 if we're already at the end of /// the file. /// </summary> /// <param name="bufferToReadInto"></param> /// <param name="startIndexIntoBuffer"></param> /// <param name="charactersToRead"></param> /// <returns></returns> /// <owner>rgoel</owner> public override int Read ( char[] bufferToReadInto, // The buffer to read the data into. int startIndexIntoBuffer, // The index into "bufferToReadInto" int charactersToRead // The number of characters to read. ) { // Make sure there's enough room in the caller's buffer for what he's // asking us to do. if ((startIndexIntoBuffer + charactersToRead) > bufferToReadInto.Length) { // End-user should never see this message, so it doesn't need to be localized. throw new ArgumentException("Cannot write past end of user's buffer.", "charactersToRead"); } int charactersCopied = 0; // Keep looping until we've read in the number of characters requested. // If we reach the end of file, we'll break out early. while (0 < charactersToRead) { // Read more data from the underlying file if necessary. if (!this.ReadLineIntoInternalBuffer()) { // If we've reached the end of the underlying file, exit the // loop. break; } // We're going to copy characters from our cached singleLine to the caller's // buffer. The number of characters to copy is the lesser of (the remaining // characters in our cached singleLine) and (the number of characters remaining // before we've fulfilled the caller's request). int charactersToCopy = (this.singleLine.Length - currentReadPositionWithinSingleLine); if (charactersToCopy > charactersToRead) { charactersToCopy = charactersToRead; } // Copy characters from our cached "singleLine" to the caller's buffer. this.singleLine.ToString().CopyTo(this.currentReadPositionWithinSingleLine, bufferToReadInto, startIndexIntoBuffer, charactersToCopy); // Update all counts and indices. startIndexIntoBuffer += charactersToCopy; this.currentReadPositionWithinSingleLine += charactersToCopy; charactersCopied += charactersToCopy; charactersToRead -= charactersToCopy; } return charactersCopied; } /// <summary> /// Not implemented. Our class only supports reading from a file, which /// can't change beneath the covers while we're reading from it. Therefore, /// a blocking read doesn't make sense for our scenario. (A blocking read /// is where you wait until the requested number of characters actually /// become available ... which is never going to happen if you've already /// reached the end of a file.) /// </summary> /// <param name="bufferToReadInto"></param> /// <param name="startIndexIntoBuffer"></param> /// <param name="charactersToRead"></param> /// <returns></returns> /// <owner>rgoel</owner> public override int ReadBlock ( char[] bufferToReadInto, int startIndexIntoBuffer, int charactersToRead ) { throw new NotImplementedException(); } /// <summary> /// Reads a single line of text, and returns it as a string, not including the /// terminating line-ending characters. If we were at the end of the file, /// return null. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override string ReadLine ( ) { // Read a new line from the underlying file if necessary (that is, only // if our currently cached singleLine has already been used up). if (!this.ReadLineIntoInternalBuffer()) { // If we reached the end of the underlying file, return null. return null; } // We now have a single line of text cached in our "singleLine" variable. // Just return that, or the portion of that which hasn't been already read // by the caller). string result = this.singleLine.ToString(this.currentReadPositionWithinSingleLine, this.singleLine.Length - this.currentReadPositionWithinSingleLine); // The caller has read the entirety of our cached "singleLine", so update // our read pointer accordingly. this.currentReadPositionWithinSingleLine = this.singleLine.Length; // Strip off the line endings before returning to caller. char[] lineEndingCharacters = new char[] {'\r', '\n'}; return result.Trim(lineEndingCharacters); } /// <summary> /// Reads the remainder of the file, and returns it as a string. Returns /// an empty string if we've already reached the end of the file. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public override string ReadToEnd ( ) { // This is what we're going to return to the caller. StringBuilder result = new StringBuilder(); // Keep reading lines of text out of the underlying file, one line at // a time. while (true) { if (!this.ReadLineIntoInternalBuffer()) { // Exit the loop when we've reached the end of the underlying // file. break; } // Append the line of text to the resulting output. result.Append(this.singleLine.ToString(this.currentReadPositionWithinSingleLine, this.singleLine.Length - this.currentReadPositionWithinSingleLine)); this.currentReadPositionWithinSingleLine = this.singleLine.Length; } return result.ToString(); } /// <summary> /// And this is where the real magic happens. If our currently cached /// "singleLine" has been used up, we read a new line of text from the /// underlying text file. But as we read the line of text from the file, /// we immediately replace all instances of special characters that occur /// within double-quotes with the corresponding XML-friendly equivalents. /// For example, if the underlying text file contained this: /// /// &lt;MyElement MyAttribute="My --&gt; Value" /&gt; /// /// then we would read it in and immediately convert it to this: /// /// &lt;MyElement MyAttribute="My --&gt; Value" /&gt; /// /// and we would store it this way in our "singleLine", so that the callers /// never know the difference. /// /// This method returns true on success, and false if we were unable to /// read a new line (due to end of file). /// </summary> /// <returns></returns> /// <owner>rgoel</owner> private bool ReadLineIntoInternalBuffer ( ) { // Only do the work if we've already used up the data in the currently // cached "singleLine". if (this.currentReadPositionWithinSingleLine >= this.singleLine.Length) { // Read a line of text from the underlying file. string lineFromProjectFile = this.oldVSProjectFile.ReadLine(); if (lineFromProjectFile == null) { // If we've reached the end of the file, return false. return false; } // Take the line of text just read, and replace all special characters // with the escaped XML-friendly string equivalents. this.singleLine = new StringBuilder(this.ReplaceSpecialCharacters(lineFromProjectFile)); // The underlying StreamReader.ReadLine method doesn't give us the // trailing line endings, so add them back ourselves. this.singleLine.Append(Environment.NewLine); // So now we have a new cached "singleLine". Reset the read pointer // to the beginning of the new line just read. this.currentReadPositionWithinSingleLine = 0; } return true; } /// <summary> /// This method uses a regular expression to search for the stuff in /// between double-quotes. We obviously don't want to touch the stuff /// OUTSIDE of double-quotes, because then we would be mucking with the /// real angle-brackets that delimit the XML element names, etc. /// </summary> /// <param name="originalLine"></param> /// <returns></returns> /// <owner>rgoel</owner> private string ReplaceSpecialCharacters ( string originalLine ) { // Find the stuff within double-quotes, and send it off to the // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of // the special characters. Regex attributeValueInsideDoubleQuotesPattern = new Regex("= *\"[^\"]*\""); string replacedStuffInsideDoubleQuotes = attributeValueInsideDoubleQuotesPattern.Replace(originalLine, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); // Find the stuff within single-quotes, and send it off to the // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of // the special characters. Regex attributeValueInsideSingleQuotesPattern = new Regex("= *'[^']*'"); string replacedStuffInsideSingleQuotes = attributeValueInsideSingleQuotesPattern.Replace(replacedStuffInsideDoubleQuotes, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); return replacedStuffInsideSingleQuotes; } /// <summary> /// This method is used as the delegate that is passed into Regex.Replace. /// It a regular expression to search for the stuff in /// between double-quotes. We obviously don't want to touch the stuff /// OUTSIDE of double-quotes, because then we would be mucking with the /// real angle-brackets that delimit the XML element names, etc. /// </summary> /// <param name="xmlAttribute"></param> /// <returns></returns> /// <owner>RGoel</owner> private string ReplaceSpecialCharactersInXmlAttribute ( Match xmlAttribute ) { // We've been given the string for the attribute value (i.e., all the stuff // within double-quotes, including the double-quotes). Replace all the special characters // within it, and return the new string. return ReplaceSpecialCharactersInXmlAttributeString(xmlAttribute.Value); } /// <summary> /// This method actually does the replacement of special characters within the /// text of the XML attribute. /// </summary> /// <param name="xmlAttributeText">Input string</param> /// <returns>New string with all the replacements (e.g. "&amp;" becomes "&amp;amp;", etc.)</returns> /// <owner>RGoel</owner> internal static string ReplaceSpecialCharactersInXmlAttributeString ( string xmlAttributeText ) { // Replace the special characters with their XML-friendly escaped equivalents. The // "<" and ">" signs are easy, because if they exist at all within the value of an // XML attribute, we know that they need to be replaced with "&lt;" and "&gt;" // respectively. xmlAttributeText = xmlAttributeText.Replace("<", "&lt;"); xmlAttributeText = xmlAttributeText.Replace(">", "&gt;"); xmlAttributeText = ReplaceNonEscapingAmpersands(xmlAttributeText); return xmlAttributeText; } // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&amp;" as "&" // and "&amp;amp;" as "&amp;". Or just look at the intellisense tooltip. /// <summary> /// This method scans the strings for "&amp;" characters, and based on what follows /// the "&amp;" character, it determines whether the "&amp;" character needs to be replaced /// with "&amp;amp;". The old XML parser used in the VS.NET 2002/2003 project system /// was quite inconsistent in its treatment of escaped characters in XML, so here /// we're having to make up for those bugs. The new XML parser (System.Xml) /// is much more strict in enforcing proper XML syntax, and therefore doesn't /// tolerate "&amp;" characters in the XML attribute value, unless the "&amp;" is being /// used to escape some special character. /// </summary> /// <param name="xmlAttributeText">Input string</param> /// <returns>New string with all the replacements (e.g. "&amp;" becomes "&amp;amp;", etc.)</returns> /// <owner>RGoel</owner> private static string ReplaceNonEscapingAmpersands ( string xmlAttributeText ) { // Ampersands are a little trickier, because some instances of "&" we need to leave // untouched, and some we need to replace with "&amp;". For example, // aaa&bbb should be replaced with aaa&amp;bbb // But: // aaa&lt;bbb should not be touched. // Loop through each instance of "&" int indexOfAmpersand = xmlAttributeText.IndexOf('&'); while (indexOfAmpersand != -1) { // If an "&" was found, search for the next ";" following the "&". int indexOfNextSemicolon = xmlAttributeText.IndexOf(';', indexOfAmpersand); if (indexOfNextSemicolon == -1) { // No semicolon means that the ampersand was really intended to be a literal // ampersand and therefore we need to replace it with "&amp;". For example, // // aaa&bbb should get replaced with aaa&amp;bbb xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand); } else { // We found the semicolon. Capture the characters between (but not // including) the "&" and ";". string entityName = xmlAttributeText.Substring(indexOfAmpersand + 1, indexOfNextSemicolon - indexOfAmpersand - 1); // Perf note: Here we are walking through the entire list of entities, and // doing a string comparison for each. This is expensive, but this code // should only get executed in fairly rare circumstances. It's not very // common for people to have these embedded into their project files. bool foundEntity = false; for (int i = 0 ; i < entities.Length ; i++) { // Case-sensitive comparison to see if the entity name matches any of // the well-known ones that were emitted by the XML writer in the VS.NET // 2002/2003 project system. if (0 == String.Compare(entityName, entities[i], StringComparison.Ordinal)) { foundEntity = true; break; } } // If it didn't match a well-known entity name, then the next thing to // check is if it represents an ASCII code. For example, in an XML // attribute, if I wanted to represent the "+" sign, I could do this: // // &#43; // if (!foundEntity && (entityName.Length > 0) && (entityName[0] == '#')) { // At this point, we know entityName is something like "#1234" or "#x1234abcd" bool isNumber = false; // A lower-case "x" in the second position indicates a hexadecimal value. if ((entityName.Length > 2) && (entityName[1] == 'x')) { isNumber = true; // It's a hexadecimal number. Make sure every character of the entity // is in fact a valid hexadecimal character. for (int i = 2; i < entityName.Length; i++) { if (!Uri.IsHexDigit(entityName[i])) { isNumber = false; break; } } } else if (entityName.Length > 1) { // Otherwise it's a decimal value. isNumber = true; // ake sure every character of the entity is in fact a valid decimal number. for (int i = 1; i < entityName.Length; i++) { if (!Char.IsNumber(entityName[i])) { isNumber = false; break; } } } if (isNumber) { foundEntity = true; } } // If the ampersand did not precede an actual well-known entity, then we DO want to // replace the "&" with a "&amp;". Otherwise we don't. if (!foundEntity) { xmlAttributeText = ReplaceAmpersandWithLiteral(xmlAttributeText, indexOfAmpersand); } } // We're done process that particular "&". Now find the next one. indexOfAmpersand = xmlAttributeText.IndexOf('&', indexOfAmpersand + 1); } return xmlAttributeText; } // Note -- the comment below is rendered a little confusing by escaping for XML doc compiler. Read "&amp;" as "&" // and "&amp;amp;" as "&amp;". Or just look at the intellisense tooltip. /// <summary> /// Replaces a single instance of an "&amp;" character in a string with "&amp;amp;" and returns the new string. /// </summary> /// <param name="originalString">Original string where we should find an "&amp;" character.</param> /// <param name="indexOfAmpersand">The index of the "&amp;" which we want to replace.</param> /// <returns>The new string with the "&amp;" replaced with "&amp;amp;".</returns> /// <owner>RGoel</owner> internal static string ReplaceAmpersandWithLiteral ( string originalString, int indexOfAmpersand ) { error.VerifyThrow(originalString[indexOfAmpersand] == '&', "Caller passed in a string that doesn't have an '&' character in the specified location."); StringBuilder replacedString = new StringBuilder(); replacedString.Append(originalString.Substring(0, indexOfAmpersand)); replacedString.Append("&amp;"); replacedString.Append(originalString.Substring(indexOfAmpersand + 1)); return replacedString.ToString(); } // This is the complete list of well-known entity names that were written out // by the XML writer in the VS.NET 2002/2003 project system. This list was // taken directly from the source code. private static readonly string[] entities = { "quot", // "amp", // & - ampersand "apos", // ' - apostrophe //// not part of HTML! "lt", // < less than "gt", // > greater than "nbsp", // Non breaking space "iexcl", // "cent", // cent "pound", // pound "curren", // currency "yen", // yen "brvbar", // vertical bar "sect", // section "uml", // "copy", // Copyright "ordf", // "laquo", // "not", // "shy", // "reg", // Registered TradeMark "macr", // "deg", // "plusmn", // "sup2", // "sup3", // "acute", // "micro", // "para", // "middot", // "cedil", // "sup1", // "ordm", // "raquo", // "frac14", // 1/4 "frac12", // 1/2 "frac34", // 3/4 "iquest", // Inverse question mark "Agrave", // Capital A grave accent "Aacute", // Capital A acute accent "Acirc", // Capital A circumflex accent "Atilde", // Capital A tilde "Auml", // Capital A dieresis or umlaut mark "Aring", // Capital A ring "AElig", // Capital AE dipthong (ligature) "Ccedil", // Capital C cedilla "Egrave", // Capital E grave accent "Eacute", // Capital E acute accent "Ecirc", // Capital E circumflex accent "Euml", // Capital E dieresis or umlaut mark "Igrave", // Capital I grave accent "Iacute", // Capital I acute accent "Icirc", // Capital I circumflex accent "Iuml", // Capital I dieresis or umlaut mark "ETH", // Capital Eth Icelandic "Ntilde", // Capital N tilde "Ograve", // Capital O grave accent "Oacute", // Capital O acute accent "Ocirc", // Capital O circumflex accent "Otilde", // Capital O tilde "Ouml", // Capital O dieresis or umlaut mark "times", // multiply or times "Oslash", // Capital O slash "Ugrave", // Capital U grave accent "Uacute", // Capital U acute accent "Ucirc", // Capital U circumflex accent "Uuml", // Capital U dieresis or umlaut mark; "Yacute", // Capital Y acute accent "THORN", // Capital THORN Icelandic "szlig", // Small sharp s German (sz ligature) "agrave", // Small a grave accent "aacute", // Small a acute accent "acirc", // Small a circumflex accent "atilde", // Small a tilde "auml", // Small a dieresis or umlaut mark "aring", // Small a ring "aelig", // Small ae dipthong (ligature) "ccedil", // Small c cedilla "egrave", // Small e grave accent "eacute", // Small e acute accent "ecirc", // Small e circumflex accent "euml", // Small e dieresis or umlaut mark "igrave", // Small i grave accent "iacute", // Small i acute accent "icirc", // Small i circumflex accent "iuml", // Small i dieresis or umlaut mark "eth", // Small eth Icelandic "ntilde", // Small n tilde "ograve", // Small o grave accent "oacute", // Small o acute accent "ocirc", // Small o circumflex accent "otilde", // Small o tilde "ouml", // Small o dieresis or umlaut mark "divide", // divide "oslash", // Small o slash "ugrave", // Small u grave accent "uacute", // Small u acute accent "ucirc", // Small u circumflex accent "uuml", // Small u dieresis or umlaut mark "yacute", // Small y acute accent "thorn", // Small thorn Icelandic "yuml", // Small y dieresis or umlaut mark "OElig", // latin capital ligature oe, U0152 ISOlat2 "oelig", // latin small ligature oe, U0153 ISOlat2 "Scaron", // latin capital letter s with caron, U0160 ISOlat2 "scaron", // latin small letter s with caron, U0161 ISOlat2 "Yuml", // latin capital letter y with diaeresis, U0178 ISOlat2 "fnof", // latin small f with hook, =function, =florin, U0192 ISOtech "circ", // modifier letter circumflex accent, U02C6 ISOpub "tilde", // small tilde, U02DC ISOdia "Alpha", // greek capital letter alpha "Beta", // greek capital letter beta "Gamma", // greek capital letter gamma "Delta", // greek capital letter delta "Epsilon", // greek capital letter epsilon "Zeta", // greek capital letter zeta "Eta", // greek capital letter eta "Theta", // greek capital letter theta "Iota", // greek capital letter iota "Kappa", // greek capital letter kappa "Lambda", // greek capital letter lambda "Mu", // greek capital letter mu "Nu", // greek capital letter nu "Xi", // greek capital letter xi "Omicron", // greek capital letter omicron "Pi", // greek capital letter pi "Rho", // greek capital letter rho "Sigma", // greek capital letter sigma "Tau", // greek capital letter tau "Upsilon", // greek capital letter upsilon "Phi", // greek capital letter phi "Chi", // greek capital letter chi "Psi", // greek capital letter psi "Omega", // greek capital letter omega "alpha", // greek small letter alpha "beta", // greek small letter beta "gamma", // greek small letter gamma "delta", // greek small letter delta "epsilon", // greek small letter epsilon "zeta", // greek small letter zeta "eta", // greek small letter eta "theta", // greek small letter theta "iota", // greek small letter iota "kappa", // greek small letter kappa "lambda", // greek small letter lambda "mu", // greek small letter mu "nu", // greek small letter nu "xi", // greek small letter xi "omicron", // greek small letter omicron "pi", // greek small letter pi "rho", // greek small letter rho "sigmaf", // greek small final sigma "sigma", // greek small letter sigma "tau", // greek small letter tau "upsilon", // greek small letter upsilon "phi", // greek small letter phi "chi", // greek small letter chi "psi", // greek small letter psi "omega", // greek small letter omega "thetasym", // greek small letter theta symbol, U03D1 NEW "upsih", // greek upsilon with hook symbol "piv", // greek pi symbol "ensp", // en space, U2002 ISOpub "emsp", // em space, U2003 ISOpub "thinsp", // thin space, U2009 ISOpub "zwnj", // zero width non-joiner, U200C NEW RFC 2070 "zwj", // zero width joiner, U200D NEW RFC 2070 "lrm", // left-to-right mark, U200E NEW RFC 2070 "rlm", // right-to-left mark, U200F NEW RFC 2070 "ndash", // en dash, U2013 ISOpub "mdash", // em dash, U2014 ISOpub "lsquo", // left single quotation mark, U2018 ISOnum "rsquo", // right single quotation mark, U2019 ISOnum "sbquo", // single low-9 quotation mark, U201A NEW "ldquo", // left double quotation mark, U201C ISOnum "rdquo", // right double quotation mark, U201D ISOnum "bdquo", // double low-9 quotation mark, U201E NEW "dagger", // dagger, U2020 ISOpub "Dagger", // double dagger, U2021 ISOpub "bull", // bullet, =black small circle, U2022 ISOpub "hellip", // horizontal ellipsis, =three dot leader, U2026 ISOpub "permil", // per mille sign, U2030 ISOtech "prime", // prime, =minutes, =feet, U2032 ISOtech "Prime", // double prime, =seconds, =inches, U2033 ISOtech "lsaquo", // single left-pointing angle quotation mark, U2039 ISO proposed "rsaquo", // single right-pointing angle quotation mark, U203A ISO proposed "oline", // overline, spacing overscore "frasl", // fraction slash "image", // blackletter capital I, =imaginary part, U2111 ISOamso "weierp", // script capital P, =power set, =Weierstrass p, U2118 ISOamso "real", // blackletter capital R, =real part symbol, U211C ISOamso "trade", // trade mark sign, U2122 ISOnum "alefsym", // alef symbol, =first transfinite cardinal, U2135 NEW "larr", // leftwards arrow, U2190 ISOnum "uarr", // upwards arrow, U2191 ISOnum "rarr", // rightwards arrow, U2192 ISOnum "darr", // downwards arrow, U2193 ISOnum "harr", // left right arrow, U2194 ISOamsa "crarr", // downwards arrow with corner leftwards, =carriage return, U21B5 NEW "lArr", // leftwards double arrow, U21D0 ISOtech "uArr", // upwards double arrow, U21D1 ISOamsa "rArr", // rightwards double arrow, U21D2 ISOtech "dArr", // downwards double arrow, U21D3 ISOamsa "hArr", // left right double arrow, U21D4 ISOamsa "forall", // for all, U2200 ISOtech "part", // partial differential, U2202 ISOtech "exist", // there exists, U2203 ISOtech "empty", // empty set, =null set, =diameter, U2205 ISOamso "nabla", // nabla, =backward difference, U2207 ISOtech "isin", // element of, U2208 ISOtech "notin", // not an element of, U2209 ISOtech "ni", // contains as member, U220B ISOtech "prod", // n-ary product, =product sign, U220F ISOamsb "sum", // n-ary sumation, U2211 ISOamsb "minus", // minus sign, U2212 ISOtech "lowast", // asterisk operator, U2217 ISOtech "radic", // square root, =radical sign, U221A ISOtech "prop", // proportional to, U221D ISOtech "infin", // infinity, U221E ISOtech "ang", // angle, U2220 ISOamso "and", // logical and, =wedge, U2227 ISOtech "or", // logical or, =vee, U2228 ISOtech "cap", // intersection, =cap, U2229 ISOtech "cup", // union, =cup, U222A ISOtech "int", // integral, U222B ISOtech "there4", // therefore, U2234 ISOtech "sim", // tilde operator, =varies with, =similar to, U223C ISOtech "cong", // approximately equal to, U2245 ISOtech "asymp", // almost equal to, =asymptotic to, U2248 ISOamsr "ne", // not equal to, U2260 ISOtech "equiv", // identical to, U2261 ISOtech "le", // less-than or equal to, U2264 ISOtech "ge", // greater-than or equal to, U2265 ISOtech "sub", // subset of, U2282 ISOtech "sup", // superset of, U2283 ISOtech "nsub", // not a subset of, U2284 ISOamsn "sube", // subset of or equal to, U2286 ISOtech "supe", // superset of or equal to, U2287 ISOtech "oplus", // circled plus, =direct sum, U2295 ISOamsb "otimes", // circled times, =vector product, U2297 ISOamsb "perp", // up tack, =orthogonal to, =perpendicular, U22A5 ISOtech "sdot", // dot operator, U22C5 ISOamsb "lceil", // left ceiling, =apl upstile, U2308, ISOamsc "rceil", // right ceiling, U2309, ISOamsc "lfloor", // left floor, =apl downstile, U230A, ISOamsc "rfloor", // right floor, U230B, ISOamsc "lang", // left-pointing angle bracket, =bra, U2329 ISOtech "rang", // right-pointing angle bracket, =ket, U232A ISOtech "loz", // lozenge, U25CA ISOpub "spades", // black spade suit, U2660 ISOpub "clubs", // black club suit, =shamrock, U2663 ISOpub "hearts", // black heart suit, =valentine, U2665 ISOpub "diams" // black diamond suit, U2666 ISOpub }; } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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 NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Infoplus.Api; using Infoplus.Model; using Infoplus.Client; using System.Reflection; namespace Infoplus.Test { /// <summary> /// Class for testing ParcelShipment /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class ParcelShipmentTests { // TODO uncomment below to declare an instance variable for ParcelShipment //private ParcelShipment instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of ParcelShipment //instance = new ParcelShipment(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of ParcelShipment /// </summary> [Test] public void ParcelShipmentInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" ParcelShipment //Assert.IsInstanceOfType<ParcelShipment> (instance, "variable 'instance' is a ParcelShipment"); } /// <summary> /// Test the property 'Id' /// </summary> [Test] public void IdTest() { // TODO unit test for the property 'Id' } /// <summary> /// Test the property 'CreateDate' /// </summary> [Test] public void CreateDateTest() { // TODO unit test for the property 'CreateDate' } /// <summary> /// Test the property 'ModifyDate' /// </summary> [Test] public void ModifyDateTest() { // TODO unit test for the property 'ModifyDate' } /// <summary> /// Test the property 'ShipDate' /// </summary> [Test] public void ShipDateTest() { // TODO unit test for the property 'ShipDate' } /// <summary> /// Test the property 'DeliveredDate' /// </summary> [Test] public void DeliveredDateTest() { // TODO unit test for the property 'DeliveredDate' } /// <summary> /// Test the property 'TrackingNo' /// </summary> [Test] public void TrackingNoTest() { // TODO unit test for the property 'TrackingNo' } /// <summary> /// Test the property 'WarehouseId' /// </summary> [Test] public void WarehouseIdTest() { // TODO unit test for the property 'WarehouseId' } /// <summary> /// Test the property 'LobId' /// </summary> [Test] public void LobIdTest() { // TODO unit test for the property 'LobId' } /// <summary> /// Test the property 'OrderNo' /// </summary> [Test] public void OrderNoTest() { // TODO unit test for the property 'OrderNo' } /// <summary> /// Test the property 'CartonNo' /// </summary> [Test] public void CartonNoTest() { // TODO unit test for the property 'CartonNo' } /// <summary> /// Test the property 'NumberOfCartons' /// </summary> [Test] public void NumberOfCartonsTest() { // TODO unit test for the property 'NumberOfCartons' } /// <summary> /// Test the property 'Status' /// </summary> [Test] public void StatusTest() { // TODO unit test for the property 'Status' } /// <summary> /// Test the property 'Shipped' /// </summary> [Test] public void ShippedTest() { // TODO unit test for the property 'Shipped' } /// <summary> /// Test the property 'CarrierServiceId' /// </summary> [Test] public void CarrierServiceIdTest() { // TODO unit test for the property 'CarrierServiceId' } /// <summary> /// Test the property 'Dim1In' /// </summary> [Test] public void Dim1InTest() { // TODO unit test for the property 'Dim1In' } /// <summary> /// Test the property 'Dim2In' /// </summary> [Test] public void Dim2InTest() { // TODO unit test for the property 'Dim2In' } /// <summary> /// Test the property 'Dim3In' /// </summary> [Test] public void Dim3InTest() { // TODO unit test for the property 'Dim3In' } /// <summary> /// Test the property 'EstimatedZone' /// </summary> [Test] public void EstimatedZoneTest() { // TODO unit test for the property 'EstimatedZone' } /// <summary> /// Test the property 'ParcelAccountNo' /// </summary> [Test] public void ParcelAccountNoTest() { // TODO unit test for the property 'ParcelAccountNo' } /// <summary> /// Test the property 'ThirdPartyParcelAccountNo' /// </summary> [Test] public void ThirdPartyParcelAccountNoTest() { // TODO unit test for the property 'ThirdPartyParcelAccountNo' } /// <summary> /// Test the property 'ManifestId' /// </summary> [Test] public void ManifestIdTest() { // TODO unit test for the property 'ManifestId' } /// <summary> /// Test the property 'Residential' /// </summary> [Test] public void ResidentialTest() { // TODO unit test for the property 'Residential' } /// <summary> /// Test the property 'BillingOption' /// </summary> [Test] public void BillingOptionTest() { // TODO unit test for the property 'BillingOption' } /// <summary> /// Test the property 'WeightLbs' /// </summary> [Test] public void WeightLbsTest() { // TODO unit test for the property 'WeightLbs' } /// <summary> /// Test the property 'DimWeight' /// </summary> [Test] public void DimWeightTest() { // TODO unit test for the property 'DimWeight' } /// <summary> /// Test the property 'LicensePlateNumber' /// </summary> [Test] public void LicensePlateNumberTest() { // TODO unit test for the property 'LicensePlateNumber' } /// <summary> /// Test the property 'ChargedFreightAmount' /// </summary> [Test] public void ChargedFreightAmountTest() { // TODO unit test for the property 'ChargedFreightAmount' } /// <summary> /// Test the property 'PublishedFreightAmount' /// </summary> [Test] public void PublishedFreightAmountTest() { // TODO unit test for the property 'PublishedFreightAmount' } /// <summary> /// Test the property 'RetailFreightAmount' /// </summary> [Test] public void RetailFreightAmountTest() { // TODO unit test for the property 'RetailFreightAmount' } } }
using System; using System.IO; using System.Text; using System.Threading.Tasks; using Foundation; using Gaucho.Forms.Core.FileSystem; using Gaucho.Forms.Core.Services; using Gaucho.Forms.iOS.Services; using NUnit.Framework; using FileMode = Gaucho.Forms.Core.FileSystem.FileMode; namespace Gaucho.Forms.iOS.UnitTests { [TestFixture] public class TestFileSystem { protected readonly byte[] TestBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; protected const string Filename = "Testfile.file"; private FileSystem _fileSystem; protected string TestString = "{\"Name\":\"TestName\",\"TestObject\":{\"Id\":\"0123456789\",\"Name\":\"TestObjectName\"}}"; [SetUp] public void Init() { _fileSystem = new FileSystem(); DeleteTestFiles(); } [Test] public void OpenFileReadResource() { var stream = _fileSystem.OpenFile(Filename, StorageLocation.AppResource); Assert.NotNull(stream); } [Test] public async Task OpenFileReadStreamDocuments() { await CreateTestTextFile(StorageLocation.Documents); var stream = _fileSystem.OpenFile(Filename, StorageLocation.Documents); Assert.NotNull(stream); } [Test] public async Task OpenFileReadStreamCache() { await CreateTestTextFile(StorageLocation.Cache); var stream = _fileSystem.OpenFile(Filename, StorageLocation.Cache); Assert.NotNull(stream); } [Test] public void OpenFileWriteResource() { Assert.Throws<NotSupportedException>(() => _fileSystem.OpenFile(Filename, StorageLocation.AppResource, FileMode.Write)); } [Test] public void OpenFileWriteStreamDocuments() { var stream = _fileSystem.OpenFile(Filename, StorageLocation.Documents, FileMode.Write); Assert.NotNull(stream); } [Test] public void OpenFileWriteStreamCache() { var stream = _fileSystem.OpenFile(Filename, StorageLocation.Cache, FileMode.Write); Assert.NotNull(stream); } [Test] public void DeleteFileReadAppResource() { Assert.Throws<NotSupportedException>(() => _fileSystem.DeleteFile(Filename, StorageLocation.AppResource)); } [Test] public async Task DeleteFileDocuments() { await TestDeleteFile(StorageLocation.Documents); } [Test] public async Task DeleteFileCache() { await TestDeleteFile(StorageLocation.Cache); } [Test] public void FileExistsResources() { Assert.True(_fileSystem.FileExists(Filename, StorageLocation.AppResource)); } [Test] public async Task FileExistsDocuments() { await TestFileExists(StorageLocation.Documents); } [Test] public async Task FileExistsCache() { await TestFileExists(StorageLocation.Cache); } private async Task TestDeleteFile(StorageLocation storageLocation) { await CreateTestTextFile(storageLocation); _fileSystem.DeleteFile(Filename, storageLocation); Assert.False(CheckFileExists(storageLocation)); } private async Task TestFileExists(StorageLocation storageLocation) { await CreateTestTextFile(storageLocation); Assert.True(CheckFileExists(storageLocation)); } public async Task CreateTestTextFile(StorageLocation location) { switch (location) { case StorageLocation.AppResource: throw new NotImplementedException(); case StorageLocation.Documents: await CreateTestByteFileInternal(Encoding.UTF8.GetBytes(TestString)); break; case StorageLocation.Cache: await CreateTestByteFileCache(Encoding.UTF8.GetBytes(TestString)); break; default: throw new ArgumentOutOfRangeException(nameof(location), location, null); } } public async Task CreateTestByteFile(StorageLocation location) { switch (location) { case StorageLocation.AppResource: throw new NotImplementedException(); break; case StorageLocation.Documents: await CreateTestByteFileInternal(TestBytes); break; case StorageLocation.Cache: await CreateTestByteFileCache(TestBytes); break; default: throw new ArgumentOutOfRangeException(nameof(location), location, null); } } public bool CheckFileExists(StorageLocation location) { string filesDirPath = null; switch (location) { case StorageLocation.AppResource: filesDirPath = NSBundle.MainBundle.PathForResource(Filename, null); break; case StorageLocation.Documents: filesDirPath = GetDocumentPath(); break; case StorageLocation.Cache: var cacheUrls = GetCachePath(); filesDirPath = GetCachePath(); break; default: throw new ArgumentOutOfRangeException(nameof(location), location, null); } if (filesDirPath != null) { var path = Path.Combine(filesDirPath, Filename); return File.Exists(path); } return false; } private static string GetCachePath() { var cacheUrls = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); return cacheUrls[0].Path; } private static string GetDocumentPath() { var docUrls = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); return docUrls[0].Path; } private async Task CreateTestByteFileCache(byte[] bytes) { var cachePath = GetCachePath(); var path = Path.Combine(cachePath, Filename); NSFileManager.DefaultManager.CreateFile(path, NSData.FromArray(bytes), (NSDictionary) null); } private async Task CreateTestByteFileInternal(byte[] bytes) { var cachePath = GetDocumentPath(); var path = Path.Combine(cachePath, Filename); NSFileManager.DefaultManager.CreateFile(path, NSData.FromArray(bytes), (NSDictionary) null); } public void DeleteTestFiles() { DeleteFile(StorageLocation.Documents); DeleteFile(StorageLocation.Cache); } private void DeleteFile(StorageLocation storageLocation) { string filesDirPath = null; switch (storageLocation) { case StorageLocation.AppResource: throw new NotSupportedException(); case StorageLocation.Documents: filesDirPath = GetDocumentPath(); break; case StorageLocation.Cache: filesDirPath = GetCachePath(); break; default: throw new ArgumentOutOfRangeException(nameof(storageLocation), storageLocation, null); } if (filesDirPath != null) { var path = Path.Combine(filesDirPath, Filename); if (File.Exists(path)) { File.Delete(path); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Framework.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Models; using OmniSharp.Options; using OmniSharp.Services; namespace OmniSharp.Dnx { public class DnxPaths { private readonly IOmnisharpEnvironment _env; private readonly OmniSharpOptions _options; private readonly ILogger _logger; public DnxRuntimePathResult RuntimePath { get; private set; } public string Dnx { get; private set; } public string Dnu { get; private set; } public string Klr { get; private set; } public string Kpm { get; private set; } public string K { get; private set; } public DnxPaths(IOmnisharpEnvironment env, OmniSharpOptions options, ILoggerFactory loggerFactory) { _env = env; _options = options; _logger = loggerFactory.CreateLogger<DnxPaths>(); RuntimePath = GetRuntimePath(); Dnx = FirstPath(RuntimePath.Value, "dnx", "dnx.exe"); Dnu = FirstPath(RuntimePath.Value, "dnu", "dnu.cmd"); Klr = FirstPath(RuntimePath.Value, "klr", "klr.exe"); Kpm = FirstPath(RuntimePath.Value, "kpm", "kpm.cmd"); K = FirstPath(RuntimePath.Value, "k", "k.cmd"); } private DnxRuntimePathResult GetRuntimePath() { var root = ResolveRootDirectory(_env.Path); var globalJson = Path.Combine(root, "global.json"); var versionOrAliasToken = GetRuntimeVersionOrAlias(globalJson); var versionOrAlias = versionOrAliasToken?.Value<string>() ?? _options.Dnx.Alias ?? "default"; var seachedLocations = new List<string>(); foreach (var location in GetRuntimeLocations()) { // Need to expand variables, because DNX_HOME variable might include %USERPROFILE%. var paths = GetRuntimePathsFromVersionOrAlias(versionOrAlias, Environment.ExpandEnvironmentVariables(location)); foreach (var path in paths) { if (string.IsNullOrEmpty(path)) { continue; } if (Directory.Exists(path)) { _logger.LogInformation(string.Format("Using runtime '{0}'.", path)); return new DnxRuntimePathResult() { Value = path }; } seachedLocations.Add(path); } } var message = new ErrorMessage() { Text = string.Format("The specified runtime path '{0}' does not exist. Searched locations {1}.\nVisit https://github.com/aspnet/Home for an installation guide.", versionOrAlias, string.Join("\n", seachedLocations)) }; if (versionOrAliasToken != null) { message.FileName = globalJson; message.Line = ((IJsonLineInfo)versionOrAliasToken).LineNumber; message.Column = ((IJsonLineInfo)versionOrAliasToken).LinePosition; } _logger.LogError(message.Text); return new DnxRuntimePathResult() { Error = message }; } private JToken GetRuntimeVersionOrAlias(string globalJson) { if (File.Exists(globalJson)) { _logger.LogInformation("Looking for sdk version in '{0}'.", globalJson); using (var stream = File.OpenRead(globalJson)) { var obj = JObject.Load(new JsonTextReader(new StreamReader(stream))); return obj["sdk"]?["version"]; } } return null; } private static string ResolveRootDirectory(string projectPath) { var di = new DirectoryInfo(projectPath); while (di.Parent != null) { if (di.EnumerateFiles("global.json").Any()) { return di.FullName; } di = di.Parent; } // If we don't find any files then make the project folder the root return projectPath; } private IEnumerable<string> GetRuntimeLocations() { yield return Environment.GetEnvironmentVariable("DNX_HOME") ?? string.Empty; yield return Environment.GetEnvironmentVariable("KRE_HOME") ?? string.Empty; // %HOME% and %USERPROFILE% might point to different places. foreach (var home in new string[] { Environment.GetEnvironmentVariable("HOME"), Environment.GetEnvironmentVariable("USERPROFILE") }.Where(s => !string.IsNullOrEmpty(s))) { // Newer path yield return Path.Combine(home, ".dnx"); // New path yield return Path.Combine(home, ".k"); // Old path yield return Path.Combine(home, ".kre"); } } private IEnumerable<string> GetRuntimePathsFromVersionOrAlias(string versionOrAlias, string runtimePath) { // Newer format yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".dnx", "dnx-mono.{0}", "dnx-clr-win-x86.{0}", "runtimes"); // New format yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".k", "kre-mono.{0}", "kre-clr-win-x86.{0}", "runtimes"); // Old format yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".kre", "KRE-Mono.{0}", "KRE-CLR-x86.{0}", "packages"); } private string GetRuntimePathFromVersionOrAlias(string versionOrAlias, string runtimeHome, string sdkFolder, string monoFormat, string windowsFormat, string runtimeFolder) { if (string.IsNullOrEmpty(runtimeHome)) { return null; } var aliasDirectory = Path.Combine(runtimeHome, "alias"); var aliasFiles = new[] { "{0}.alias", "{0}.txt" }; // Check alias first foreach (var shortAliasFile in aliasFiles) { var aliasFile = Path.Combine(aliasDirectory, string.Format(shortAliasFile, versionOrAlias)); if (File.Exists(aliasFile)) { var fullName = File.ReadAllText(aliasFile).Trim(); return Path.Combine(runtimeHome, runtimeFolder, fullName); } } // There was no alias, look for the input as a version var version = versionOrAlias; if (PlatformHelper.IsMono) { return Path.Combine(runtimeHome, runtimeFolder, string.Format(monoFormat, versionOrAlias)); } else { return Path.Combine(runtimeHome, runtimeFolder, string.Format(windowsFormat, versionOrAlias)); } } internal static string FirstPath(string runtimePath, params string[] candidates) { if (runtimePath == null) { return null; } return candidates .Select(candidate => Path.Combine(runtimePath, "bin", candidate)) .FirstOrDefault(File.Exists); } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// FieldsMatching /// </summary> [DataContract] public partial class FieldsMatching : IEquatable<FieldsMatching> { /// <summary> /// Initializes a new instance of the <see cref="FieldsMatching" /> class. /// </summary> /// <param name="MatchOnAddressNumber">MatchOnAddressNumber (default to false).</param> /// <param name="MatchOnPostCode1">MatchOnPostCode1 (default to false).</param> /// <param name="MatchOnPostCode2">MatchOnPostCode2 (default to false).</param> /// <param name="MatchOnAreaName1">MatchOnAreaName1 (default to false).</param> /// <param name="MatchOnAreaName2">MatchOnAreaName2 (default to false).</param> /// <param name="MatchOnAreaName3">MatchOnAreaName3 (default to false).</param> /// <param name="MatchOnAreaName4">MatchOnAreaName4 (default to false).</param> /// <param name="MatchOnAllStreetFields">MatchOnAllStreetFields (default to false).</param> /// <param name="MatchOnStreetName">MatchOnStreetName (default to false).</param> /// <param name="MatchOnStreetType">MatchOnStreetType (default to false).</param> /// <param name="MatchOnStreetDirectional">MatchOnStreetDirectional (default to false).</param> /// <param name="MatchOnPlaceName">MatchOnPlaceName (default to false).</param> /// <param name="MatchOnInputFields">MatchOnInputFields (default to false).</param> public FieldsMatching(bool? MatchOnAddressNumber = null, bool? MatchOnPostCode1 = null, bool? MatchOnPostCode2 = null, bool? MatchOnAreaName1 = null, bool? MatchOnAreaName2 = null, bool? MatchOnAreaName3 = null, bool? MatchOnAreaName4 = null, bool? MatchOnAllStreetFields = null, bool? MatchOnStreetName = null, bool? MatchOnStreetType = null, bool? MatchOnStreetDirectional = null, bool? MatchOnPlaceName = null, bool? MatchOnInputFields = null) { // use default value if no "MatchOnAddressNumber" provided if (MatchOnAddressNumber == null) { this.MatchOnAddressNumber = false; } else { this.MatchOnAddressNumber = MatchOnAddressNumber; } // use default value if no "MatchOnPostCode1" provided if (MatchOnPostCode1 == null) { this.MatchOnPostCode1 = false; } else { this.MatchOnPostCode1 = MatchOnPostCode1; } // use default value if no "MatchOnPostCode2" provided if (MatchOnPostCode2 == null) { this.MatchOnPostCode2 = false; } else { this.MatchOnPostCode2 = MatchOnPostCode2; } // use default value if no "MatchOnAreaName1" provided if (MatchOnAreaName1 == null) { this.MatchOnAreaName1 = false; } else { this.MatchOnAreaName1 = MatchOnAreaName1; } // use default value if no "MatchOnAreaName2" provided if (MatchOnAreaName2 == null) { this.MatchOnAreaName2 = false; } else { this.MatchOnAreaName2 = MatchOnAreaName2; } // use default value if no "MatchOnAreaName3" provided if (MatchOnAreaName3 == null) { this.MatchOnAreaName3 = false; } else { this.MatchOnAreaName3 = MatchOnAreaName3; } // use default value if no "MatchOnAreaName4" provided if (MatchOnAreaName4 == null) { this.MatchOnAreaName4 = false; } else { this.MatchOnAreaName4 = MatchOnAreaName4; } // use default value if no "MatchOnAllStreetFields" provided if (MatchOnAllStreetFields == null) { this.MatchOnAllStreetFields = false; } else { this.MatchOnAllStreetFields = MatchOnAllStreetFields; } // use default value if no "MatchOnStreetName" provided if (MatchOnStreetName == null) { this.MatchOnStreetName = false; } else { this.MatchOnStreetName = MatchOnStreetName; } // use default value if no "MatchOnStreetType" provided if (MatchOnStreetType == null) { this.MatchOnStreetType = false; } else { this.MatchOnStreetType = MatchOnStreetType; } // use default value if no "MatchOnStreetDirectional" provided if (MatchOnStreetDirectional == null) { this.MatchOnStreetDirectional = false; } else { this.MatchOnStreetDirectional = MatchOnStreetDirectional; } // use default value if no "MatchOnPlaceName" provided if (MatchOnPlaceName == null) { this.MatchOnPlaceName = false; } else { this.MatchOnPlaceName = MatchOnPlaceName; } // use default value if no "MatchOnInputFields" provided if (MatchOnInputFields == null) { this.MatchOnInputFields = false; } else { this.MatchOnInputFields = MatchOnInputFields; } } /// <summary> /// Gets or Sets MatchOnAddressNumber /// </summary> [DataMember(Name="matchOnAddressNumber", EmitDefaultValue=false)] public bool? MatchOnAddressNumber { get; set; } /// <summary> /// Gets or Sets MatchOnPostCode1 /// </summary> [DataMember(Name="matchOnPostCode1", EmitDefaultValue=false)] public bool? MatchOnPostCode1 { get; set; } /// <summary> /// Gets or Sets MatchOnPostCode2 /// </summary> [DataMember(Name="matchOnPostCode2", EmitDefaultValue=false)] public bool? MatchOnPostCode2 { get; set; } /// <summary> /// Gets or Sets MatchOnAreaName1 /// </summary> [DataMember(Name="matchOnAreaName1", EmitDefaultValue=false)] public bool? MatchOnAreaName1 { get; set; } /// <summary> /// Gets or Sets MatchOnAreaName2 /// </summary> [DataMember(Name="matchOnAreaName2", EmitDefaultValue=false)] public bool? MatchOnAreaName2 { get; set; } /// <summary> /// Gets or Sets MatchOnAreaName3 /// </summary> [DataMember(Name="matchOnAreaName3", EmitDefaultValue=false)] public bool? MatchOnAreaName3 { get; set; } /// <summary> /// Gets or Sets MatchOnAreaName4 /// </summary> [DataMember(Name="matchOnAreaName4", EmitDefaultValue=false)] public bool? MatchOnAreaName4 { get; set; } /// <summary> /// Gets or Sets MatchOnAllStreetFields /// </summary> [DataMember(Name="matchOnAllStreetFields", EmitDefaultValue=false)] public bool? MatchOnAllStreetFields { get; set; } /// <summary> /// Gets or Sets MatchOnStreetName /// </summary> [DataMember(Name="matchOnStreetName", EmitDefaultValue=false)] public bool? MatchOnStreetName { get; set; } /// <summary> /// Gets or Sets MatchOnStreetType /// </summary> [DataMember(Name="matchOnStreetType", EmitDefaultValue=false)] public bool? MatchOnStreetType { get; set; } /// <summary> /// Gets or Sets MatchOnStreetDirectional /// </summary> [DataMember(Name="matchOnStreetDirectional", EmitDefaultValue=false)] public bool? MatchOnStreetDirectional { get; set; } /// <summary> /// Gets or Sets MatchOnPlaceName /// </summary> [DataMember(Name="matchOnPlaceName", EmitDefaultValue=false)] public bool? MatchOnPlaceName { get; set; } /// <summary> /// Gets or Sets MatchOnInputFields /// </summary> [DataMember(Name="matchOnInputFields", EmitDefaultValue=false)] public bool? MatchOnInputFields { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class FieldsMatching {\n"); sb.Append(" MatchOnAddressNumber: ").Append(MatchOnAddressNumber).Append("\n"); sb.Append(" MatchOnPostCode1: ").Append(MatchOnPostCode1).Append("\n"); sb.Append(" MatchOnPostCode2: ").Append(MatchOnPostCode2).Append("\n"); sb.Append(" MatchOnAreaName1: ").Append(MatchOnAreaName1).Append("\n"); sb.Append(" MatchOnAreaName2: ").Append(MatchOnAreaName2).Append("\n"); sb.Append(" MatchOnAreaName3: ").Append(MatchOnAreaName3).Append("\n"); sb.Append(" MatchOnAreaName4: ").Append(MatchOnAreaName4).Append("\n"); sb.Append(" MatchOnAllStreetFields: ").Append(MatchOnAllStreetFields).Append("\n"); sb.Append(" MatchOnStreetName: ").Append(MatchOnStreetName).Append("\n"); sb.Append(" MatchOnStreetType: ").Append(MatchOnStreetType).Append("\n"); sb.Append(" MatchOnStreetDirectional: ").Append(MatchOnStreetDirectional).Append("\n"); sb.Append(" MatchOnPlaceName: ").Append(MatchOnPlaceName).Append("\n"); sb.Append(" MatchOnInputFields: ").Append(MatchOnInputFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as FieldsMatching); } /// <summary> /// Returns true if FieldsMatching instances are equal /// </summary> /// <param name="other">Instance of FieldsMatching to be compared</param> /// <returns>Boolean</returns> public bool Equals(FieldsMatching other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.MatchOnAddressNumber == other.MatchOnAddressNumber || this.MatchOnAddressNumber != null && this.MatchOnAddressNumber.Equals(other.MatchOnAddressNumber) ) && ( this.MatchOnPostCode1 == other.MatchOnPostCode1 || this.MatchOnPostCode1 != null && this.MatchOnPostCode1.Equals(other.MatchOnPostCode1) ) && ( this.MatchOnPostCode2 == other.MatchOnPostCode2 || this.MatchOnPostCode2 != null && this.MatchOnPostCode2.Equals(other.MatchOnPostCode2) ) && ( this.MatchOnAreaName1 == other.MatchOnAreaName1 || this.MatchOnAreaName1 != null && this.MatchOnAreaName1.Equals(other.MatchOnAreaName1) ) && ( this.MatchOnAreaName2 == other.MatchOnAreaName2 || this.MatchOnAreaName2 != null && this.MatchOnAreaName2.Equals(other.MatchOnAreaName2) ) && ( this.MatchOnAreaName3 == other.MatchOnAreaName3 || this.MatchOnAreaName3 != null && this.MatchOnAreaName3.Equals(other.MatchOnAreaName3) ) && ( this.MatchOnAreaName4 == other.MatchOnAreaName4 || this.MatchOnAreaName4 != null && this.MatchOnAreaName4.Equals(other.MatchOnAreaName4) ) && ( this.MatchOnAllStreetFields == other.MatchOnAllStreetFields || this.MatchOnAllStreetFields != null && this.MatchOnAllStreetFields.Equals(other.MatchOnAllStreetFields) ) && ( this.MatchOnStreetName == other.MatchOnStreetName || this.MatchOnStreetName != null && this.MatchOnStreetName.Equals(other.MatchOnStreetName) ) && ( this.MatchOnStreetType == other.MatchOnStreetType || this.MatchOnStreetType != null && this.MatchOnStreetType.Equals(other.MatchOnStreetType) ) && ( this.MatchOnStreetDirectional == other.MatchOnStreetDirectional || this.MatchOnStreetDirectional != null && this.MatchOnStreetDirectional.Equals(other.MatchOnStreetDirectional) ) && ( this.MatchOnPlaceName == other.MatchOnPlaceName || this.MatchOnPlaceName != null && this.MatchOnPlaceName.Equals(other.MatchOnPlaceName) ) && ( this.MatchOnInputFields == other.MatchOnInputFields || this.MatchOnInputFields != null && this.MatchOnInputFields.Equals(other.MatchOnInputFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.MatchOnAddressNumber != null) hash = hash * 59 + this.MatchOnAddressNumber.GetHashCode(); if (this.MatchOnPostCode1 != null) hash = hash * 59 + this.MatchOnPostCode1.GetHashCode(); if (this.MatchOnPostCode2 != null) hash = hash * 59 + this.MatchOnPostCode2.GetHashCode(); if (this.MatchOnAreaName1 != null) hash = hash * 59 + this.MatchOnAreaName1.GetHashCode(); if (this.MatchOnAreaName2 != null) hash = hash * 59 + this.MatchOnAreaName2.GetHashCode(); if (this.MatchOnAreaName3 != null) hash = hash * 59 + this.MatchOnAreaName3.GetHashCode(); if (this.MatchOnAreaName4 != null) hash = hash * 59 + this.MatchOnAreaName4.GetHashCode(); if (this.MatchOnAllStreetFields != null) hash = hash * 59 + this.MatchOnAllStreetFields.GetHashCode(); if (this.MatchOnStreetName != null) hash = hash * 59 + this.MatchOnStreetName.GetHashCode(); if (this.MatchOnStreetType != null) hash = hash * 59 + this.MatchOnStreetType.GetHashCode(); if (this.MatchOnStreetDirectional != null) hash = hash * 59 + this.MatchOnStreetDirectional.GetHashCode(); if (this.MatchOnPlaceName != null) hash = hash * 59 + this.MatchOnPlaceName.GetHashCode(); if (this.MatchOnInputFields != null) hash = hash * 59 + this.MatchOnInputFields.GetHashCode(); return hash; } } } }
namespace Cleangorod.Data.Migrations { using Cleangorod.Data.Models; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using OfficeOpenXml; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; } private string MapPath(string filePath) { if (HttpContext.Current != null) return Path.Combine(HostingEnvironment.ApplicationPhysicalPath, filePath); var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; var directoryName = Path.GetDirectoryName(absolutePath); var path = Path.Combine(directoryName, filePath.Replace('/', '\\')); return path; } public Configuration() { AutomaticMigrationsEnabled = false; ContextKey = "Cleangorod.Data.Models.ApplicationDbContext"; } protected override void Seed(Cleangorod.Data.Models.ApplicationDbContext context) { SeedAsync(context).Wait(); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } protected async Task SeedAsync(Cleangorod.Data.Models.ApplicationDbContext context) { var options = new IdentityFactoryOptions<ApplicationUserManager>(); var userManager = ApplicationUserManager.Create(options, context); var roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context)); await roleManager.CreateAsync(new IdentityRole { Name = "Client" }); await roleManager.CreateAsync(new IdentityRole { Name = "Admin" }); await ImportUsers(userManager); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } private async Task ImportUsers(ApplicationUserManager userManager) { var excelSrcPath = MapPath("Migrations/SeedData/Customers_14-15022015.xlsx"); var csvSrcPath = MapPath("Migrations/SeedData/members_export_d88509a54a.csv"); IEnumerable<ExternalUser> mergedUsers = null; using (var csvInputStream = File.OpenRead(csvSrcPath)) { mergedUsers = GetMergedUsers(csvInputStream, File.OpenRead(excelSrcPath)); } foreach (var item in mergedUsers) { await SaveExternalUser(userManager, item); } } private async Task SaveExternalUser(ApplicationUserManager userManager, ExternalUser externalUser) { var user = new ApplicationUser() { UserName = externalUser.Email, Email = externalUser.Email, PhoneNumber = externalUser.PhoneNumber, Name = externalUser.Name, Surname = externalUser.Surname, Note = externalUser.Note, ClientAddress = new ClientAddress { Address = externalUser.Address, Latitude = externalUser.Latitude, Longitude = externalUser.Longitude, } }; var result = await userManager.CreateAsync(user, "Moomoo/99"); if (!result.Succeeded) { throw new Exception(String.Join("; ", result.Errors)); } await userManager.AddToRoleAsync(user.Id, "Client"); } private class ExternalUser { public string Email { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } public string Name { get; set; } public string Surname { get; set; } public string PhoneNumber { get; set; } public string Note { get; set; } public string Address { get; set; } } private static IEnumerable<ExternalUser> GetExcelUsers(Stream inputStream) { using (var excelPackage = new ExcelPackage(inputStream)) { var worksheet = excelPackage.Workbook.Worksheets.First(); var start = worksheet.Dimension.Start; var end = worksheet.Dimension.End; int position; return Enumerable.Range(start.Row, end.Row - start.Row + 1) .Select(x => (Func<string, ExcelRange>)((string col) => worksheet.Cells[col + x])) .Where(x => int.TryParse(x("A").Text, out position)) .Select(x => new ExternalUser() { Email = x("G").Text, Longitude = double.Parse(x("J").Text.Split(',')[0], CultureInfo.InvariantCulture), Latitude = double.Parse(x("J").Text.Split(',')[1], CultureInfo.InvariantCulture), Name = x("D").Text, Surname = x("E").Text, Note = x("AZ").Text, PhoneNumber = x("F").Text, Address = x("I").Text }) .ToList(); } } private static IEnumerable<ExternalUser> GetCsvUsers(Stream inputStream) { var rows = ReadCsv(inputStream); return rows.Skip(1).Select(x => new ExternalUser { Name = x[0], Surname = x[1], PhoneNumber = x[2], Email = x[3], Address = x[4], }).ToList(); } private static IEnumerable<ExternalUser> GetMergedUsers(Stream csvStream, Stream excelStream) { var excelUsers = GetExcelUsers(excelStream); var csvUsers = GetCsvUsers(csvStream).ToList(); var csvDict = csvUsers.ToDictionary(x => x.Email, x => x); foreach (var item in excelUsers) { if (!csvDict.ContainsKey(item.Email)) { csvUsers.Add(item); continue; } var csvUser = csvDict[item.Email]; csvUser.Latitude = item.Latitude; csvUser.Longitude = item.Longitude; csvUser.PhoneNumber = item.PhoneNumber; csvUser.Address = item.Address; csvUser.Note = item.Note; } return csvUsers; } private static void SaveMergedUsers(string csvScrPath, string excelSrcPath, string csvDestPath) { using (var excelInputStream = File.OpenRead(excelSrcPath)) { var mergedUsers = GetMergedUsers(File.OpenRead(csvScrPath), excelInputStream); File.WriteAllLines(csvDestPath, mergedUsers.Select(x => String.Join(",", x))); } } private static List<string[]> ReadCsv(Stream inputStream) { List<string[]> list = new List<string[]>(); using (var reader = new StreamReader(inputStream)) while (!reader.EndOfStream) list.Add(reader.ReadLine().Split(',')); return list; } } }
// 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; internal class TestApp { private static unsafe long test_7(B[] ab) { fixed (B* pb = &ab[0]) { return pb->m_bval; } } private static unsafe long test_14(B* pb) { return (++pb)->m_bval; } private static unsafe long test_21(B* pb, long[] i, long ii) { return (&pb[i[ii]])->m_bval; } private static unsafe long test_28(AA* px) { return (AA.get_pb_1(px) + 1)->m_bval; } private static unsafe long test_35(long pb) { return ((B*)checked(((long)pb) + 1))->m_bval; } private static unsafe long test_42(B* pb) { return (pb--)[0].m_bval; } private static unsafe long test_49(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return pb[0].m_bval; } } private static unsafe long test_56(B* pb1, long i) { B* pb; return (pb = pb1 + i)[0].m_bval; } private static unsafe long test_63(B* pb1, B* pb2) { return (pb1 > pb2 ? pb2 : null)[0].m_bval; } private static unsafe long test_70(long pb) { return ((B*)pb)[0].m_bval; } private static unsafe long test_77(double* pb, long i) { return ((B*)(pb + i))[0].m_bval; } private static unsafe long test_84(ref B b) { fixed (B* pb = &b) { return AA.get_bv1(pb); } } private static unsafe long test_91(B* pb) { return AA.get_bv1((--pb)); } private static unsafe long test_98(B* pb, long i) { return AA.get_bv1((&pb[-(i << (int)i)])); } private static unsafe long test_105(AA* px) { return AA.get_bv1(AA.get_pb(px)); } private static unsafe long test_112(long pb) { return AA.get_bv1(((B*)checked((long)pb))); } private static unsafe long test_119(B* pb) { return AA.get_bv2(*(pb++)); } private static unsafe long test_126(B[,] ab, long i, long j) { fixed (B* pb = &ab[i, j]) { return AA.get_bv2(*pb); } } private static unsafe long test_133(B* pb1) { B* pb; return AA.get_bv2(*(pb = pb1 - 8)); } private static unsafe long test_140(B* pb, B* pb1, B* pb2) { return AA.get_bv2(*(pb = pb + (pb2 - pb1))); } private static unsafe long test_147(B* pb1, bool trig) { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv2(*(trig ? pb : pb1)); } } private static unsafe long test_154(byte* pb) { return AA.get_bv2(*((B*)(pb + 7))); } private static unsafe long test_161(B b) { return AA.get_bv3(ref *(&b)); } private static unsafe long test_168() { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv3(ref *pb); } } private static unsafe long test_175(B* pb, long i) { return AA.get_bv3(ref *(&pb[i * 2])); } private static unsafe long test_182(B* pb1, B* pb2) { return AA.get_bv3(ref *(pb1 >= pb2 ? pb1 : null)); } private static unsafe long test_189(long pb) { return AA.get_bv3(ref *((B*)pb)); } private static unsafe long test_196(B* pb) { return pb->m_bval == 100 ? 100 : 101; } private static unsafe long test_203(B[] ab, long i) { fixed (B* pb = &ab[i]) { return pb->m_bval == 100 ? 100 : 101; } } private static unsafe long test_210(B* pb) { return (pb += 6)->m_bval == 100 ? 100 : 101; } private static unsafe long test_217(B* pb, long[,,] i, long ii) { return (&pb[++i[--ii, 0, 0]])->m_bval == 100 ? 100 : 101; } private static unsafe long test_224(AA* px) { return ((B*)AA.get_pb_i(px))->m_bval == 100 ? 100 : 101; } private static unsafe long test_231(byte diff, A* pa) { return ((B*)(((byte*)pa) + diff))->m_bval == 100 ? 100 : 101; } private static unsafe long test_238() { AA loc_x = new AA(0, 100); return AA.get_i1(&(&loc_x.m_b)->m_bval); } private static unsafe long test_245(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return AA.get_i1(&pb->m_bval); } } private static unsafe long test_252(B* pb1, long i) { B* pb; return AA.get_i1(&(pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval); } private static unsafe long test_259(B* pb, long[,,] i, long ii, byte jj) { return AA.get_i1(&(&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval); } private static unsafe long test_266(ulong ub, byte lb) { return AA.get_i1(&((B*)(ub | lb))->m_bval); } private static unsafe long test_273(long p, long s) { return AA.get_i1(&((B*)((p >> 4) | s))->m_bval); } private static unsafe long test_280(B[] ab) { fixed (B* pb = &ab[0]) { return AA.get_i2(pb->m_bval); } } private static unsafe long test_287(B* pb) { return AA.get_i2((++pb)->m_bval); } private static unsafe long test_294(B* pb, long[] i, long ii) { return AA.get_i2((&pb[i[ii]])->m_bval); } private static unsafe long test_301(AA* px) { return AA.get_i2((AA.get_pb_1(px) + 1)->m_bval); } private static unsafe long test_308(long pb) { return AA.get_i2(((B*)checked(((long)pb) + 1))->m_bval); } private static unsafe long test_315(B* pb) { return AA.get_i3(ref (pb--)->m_bval); } private static unsafe long test_322(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return AA.get_i3(ref pb->m_bval); } } private static unsafe long test_329(B* pb1, long i) { B* pb; return AA.get_i3(ref (pb = pb1 + i)->m_bval); } private static unsafe long test_336(B* pb1, B* pb2) { return AA.get_i3(ref (pb1 > pb2 ? pb2 : null)->m_bval); } private static unsafe long test_343(long pb) { return AA.get_i3(ref ((B*)pb)->m_bval); } private static unsafe long test_350(double* pb, long i) { return AA.get_i3(ref ((B*)(pb + i))->m_bval); } private static unsafe long test_357(ref B b) { fixed (B* pb = &b) { return AA.get_bv1(pb) != 100 ? 99 : 100; } } private static unsafe long test_364(B* pb) { return AA.get_bv1((--pb)) != 100 ? 99 : 100; } private static unsafe long test_371(B* pb, long i) { return AA.get_bv1((&pb[-(i << (int)i)])) != 100 ? 99 : 100; } private static unsafe long test_378(AA* px) { return AA.get_bv1(AA.get_pb(px)) != 100 ? 99 : 100; } private static unsafe long test_385(long pb) { return AA.get_bv1(((B*)checked((long)pb))) != 100 ? 99 : 100; } private static unsafe long test_392(B* pb1, B* pb2) { long[] e = { 100, 101 }; return e[pb1 >= pb2 ? 0 : 1]; } private static unsafe int Main() { AA loc_x = new AA(0, 100); AA.init_all(0); loc_x = new AA(0, 100); if (test_7(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_7() failed."); return 107; } AA.init_all(0); loc_x = new AA(0, 100); if (test_14(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_14() failed."); return 114; } AA.init_all(0); loc_x = new AA(0, 100); if (test_21(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_21() failed."); return 121; } AA.init_all(0); loc_x = new AA(0, 100); if (test_28(&loc_x) != 100) { Console.WriteLine("test_28() failed."); return 128; } AA.init_all(0); loc_x = new AA(0, 100); if (test_35((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_35() failed."); return 135; } AA.init_all(0); loc_x = new AA(0, 100); if (test_42(&loc_x.m_b) != 100) { Console.WriteLine("test_42() failed."); return 142; } AA.init_all(0); loc_x = new AA(0, 100); if (test_49(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_49() failed."); return 149; } AA.init_all(0); loc_x = new AA(0, 100); if (test_56(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_56() failed."); return 156; } AA.init_all(0); loc_x = new AA(0, 100); if (test_63(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_63() failed."); return 163; } AA.init_all(0); loc_x = new AA(0, 100); if (test_70((long)&loc_x.m_b) != 100) { Console.WriteLine("test_70() failed."); return 170; } AA.init_all(0); loc_x = new AA(0, 100); if (test_77(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_77() failed."); return 177; } AA.init_all(0); loc_x = new AA(0, 100); if (test_84(ref loc_x.m_b) != 100) { Console.WriteLine("test_84() failed."); return 184; } AA.init_all(0); loc_x = new AA(0, 100); if (test_91(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_91() failed."); return 191; } AA.init_all(0); loc_x = new AA(0, 100); if (test_98(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_98() failed."); return 198; } AA.init_all(0); loc_x = new AA(0, 100); if (test_105(&loc_x) != 100) { Console.WriteLine("test_105() failed."); return 205; } AA.init_all(0); loc_x = new AA(0, 100); if (test_112((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_112() failed."); return 212; } AA.init_all(0); loc_x = new AA(0, 100); if (test_119(&loc_x.m_b) != 100) { Console.WriteLine("test_119() failed."); return 219; } AA.init_all(0); loc_x = new AA(0, 100); if (test_126(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_126() failed."); return 226; } AA.init_all(0); loc_x = new AA(0, 100); if (test_133(&loc_x.m_b + 8) != 100) { Console.WriteLine("test_133() failed."); return 233; } AA.init_all(0); loc_x = new AA(0, 100); if (test_140(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100) { Console.WriteLine("test_140() failed."); return 240; } AA.init_all(0); loc_x = new AA(0, 100); if (test_147(&loc_x.m_b, true) != 100) { Console.WriteLine("test_147() failed."); return 247; } AA.init_all(0); loc_x = new AA(0, 100); if (test_154(((byte*)(&loc_x.m_b)) - 7) != 100) { Console.WriteLine("test_154() failed."); return 254; } AA.init_all(0); loc_x = new AA(0, 100); if (test_161(loc_x.m_b) != 100) { Console.WriteLine("test_161() failed."); return 261; } AA.init_all(0); loc_x = new AA(0, 100); if (test_168() != 100) { Console.WriteLine("test_168() failed."); return 268; } AA.init_all(0); loc_x = new AA(0, 100); if (test_175(&loc_x.m_b - 2, 1) != 100) { Console.WriteLine("test_175() failed."); return 275; } AA.init_all(0); loc_x = new AA(0, 100); if (test_182(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_182() failed."); return 282; } AA.init_all(0); loc_x = new AA(0, 100); if (test_189((long)&loc_x.m_b) != 100) { Console.WriteLine("test_189() failed."); return 289; } AA.init_all(0); loc_x = new AA(0, 100); if (test_196(&loc_x.m_b) != 100) { Console.WriteLine("test_196() failed."); return 296; } AA.init_all(0); loc_x = new AA(0, 100); if (test_203(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100) { Console.WriteLine("test_203() failed."); return 303; } AA.init_all(0); loc_x = new AA(0, 100); if (test_210(&loc_x.m_b - 6) != 100) { Console.WriteLine("test_210() failed."); return 310; } AA.init_all(0); loc_x = new AA(0, 100); if (test_217(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100) { Console.WriteLine("test_217() failed."); return 317; } AA.init_all(0); loc_x = new AA(0, 100); if (test_224(&loc_x) != 100) { Console.WriteLine("test_224() failed."); return 324; } AA.init_all(0); loc_x = new AA(0, 100); if (test_231((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100) { Console.WriteLine("test_231() failed."); return 331; } AA.init_all(0); loc_x = new AA(0, 100); if (test_238() != 100) { Console.WriteLine("test_238() failed."); return 338; } AA.init_all(0); loc_x = new AA(0, 100); if (test_245(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_245() failed."); return 345; } AA.init_all(0); loc_x = new AA(0, 100); if (test_252(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_252() failed."); return 352; } AA.init_all(0); loc_x = new AA(0, 100); if (test_259(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_259() failed."); return 359; } AA.init_all(0); loc_x = new AA(0, 100); if (test_266(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_266() failed."); return 366; } AA.init_all(0); loc_x = new AA(0, 100); if (test_273(((long)(&loc_x.m_b)) << 4, (long)(((ulong)&loc_x.m_b) & 0xff00000000000000)) != 100) { Console.WriteLine("test_273() failed."); return 373; } AA.init_all(0); loc_x = new AA(0, 100); if (test_280(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_280() failed."); return 380; } AA.init_all(0); loc_x = new AA(0, 100); if (test_287(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_287() failed."); return 387; } AA.init_all(0); loc_x = new AA(0, 100); if (test_294(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_294() failed."); return 394; } AA.init_all(0); loc_x = new AA(0, 100); if (test_301(&loc_x) != 100) { Console.WriteLine("test_301() failed."); return 401; } AA.init_all(0); loc_x = new AA(0, 100); if (test_308((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_308() failed."); return 408; } AA.init_all(0); loc_x = new AA(0, 100); if (test_315(&loc_x.m_b) != 100) { Console.WriteLine("test_315() failed."); return 415; } AA.init_all(0); loc_x = new AA(0, 100); if (test_322(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_322() failed."); return 422; } AA.init_all(0); loc_x = new AA(0, 100); if (test_329(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_329() failed."); return 429; } AA.init_all(0); loc_x = new AA(0, 100); if (test_336(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_336() failed."); return 436; } AA.init_all(0); loc_x = new AA(0, 100); if (test_343((long)&loc_x.m_b) != 100) { Console.WriteLine("test_343() failed."); return 443; } AA.init_all(0); loc_x = new AA(0, 100); if (test_350(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_350() failed."); return 450; } AA.init_all(0); loc_x = new AA(0, 100); if (test_357(ref loc_x.m_b) != 100) { Console.WriteLine("test_357() failed."); return 457; } AA.init_all(0); loc_x = new AA(0, 100); if (test_364(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_364() failed."); return 464; } AA.init_all(0); loc_x = new AA(0, 100); if (test_371(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_371() failed."); return 471; } AA.init_all(0); loc_x = new AA(0, 100); if (test_378(&loc_x) != 100) { Console.WriteLine("test_378() failed."); return 478; } AA.init_all(0); loc_x = new AA(0, 100); if (test_385((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_385() failed."); return 485; } AA.init_all(0); loc_x = new AA(0, 100); if (test_392(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_392() failed."); return 492; } Console.WriteLine("All tests passed."); return 100; } }
// 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.Security; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { public abstract class EncoderFallback { // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bIsMicrosoftBestFitFallback = false; #pragma warning restore 0414 private static volatile EncoderFallback replacementFallback; // Default fallback, uses no best fit & "?" private static volatile EncoderFallback exceptionFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Get each of our generic fallbacks. public static EncoderFallback ReplacementFallback { get { if (replacementFallback == null) lock (InternalSyncObject) if (replacementFallback == null) replacementFallback = new EncoderReplacementFallback(); return replacementFallback; } } public static EncoderFallback ExceptionFallback { get { if (exceptionFallback == null) lock (InternalSyncObject) if (exceptionFallback == null) exceptionFallback = new EncoderExceptionFallback(); return exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomEncoderFallbackBuffer(this); public abstract EncoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } } public abstract class EncoderFallbackBuffer { // Most implementations will probably need an implemenation-specific constructor // Public methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that is incorrect public abstract bool Fallback(char charUnknown, int index); public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Not sure if this should be public or not. // Clear the buffer public virtual void Reset() { while (GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe char* charStart; internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack = false; internal int iRecursionCount = 0; private const int iMaxRecursion = 250; // Internal Reset // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; Reset(); } // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) { this.charStart = charStart; this.charEnd = charEnd; this.encoder = encoder; this.setEncoder = setEncoder; this.bUsedEncoder = false; this.bFallingBack = false; this.iRecursionCount = 0; } internal char InternalGetNextChar() { char ch = GetNextChar(); bFallingBack = (ch != 0); if (ch == 0) iRecursionCount = 0; return ch; } // Fallback the current character using the remaining buffer and encoder if necessary // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our EncoderNLS here too. // setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount // // Note that this could also change the contents of this.encoder, which is the same // object that the caller is using, so the caller could mess up the encoder for us // if they aren't careful. internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 int index = (int)(chars - charStart) - 1; // See if it was a high surrogate if (Char.IsHighSurrogate(ch)) { // See if there's a low surrogate to go with it if (chars >= this.charEnd) { // Nothing left in input buffer // No input, return 0 if mustflush is false if (this.encoder != null && !this.encoder.MustFlush) { // Done, nothing to fallback if (this.setEncoder) { bUsedEncoder = true; this.encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { // Might have a low surrogate char cNext = *chars; if (Char.IsLowSurrogate(cNext)) { // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext)); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; bFallingBack = Fallback(ch, cNext, index); return bFallingBack; } // Next isn't a low surrogate, just fallback the high surrogate } } // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive((int)ch); // Fall back our char bFallingBack = Fallback(ch, index); return bFallingBack; } // private helper methods internal void ThrowLastCharRecursive(int charRecursive) { // Throw it, using our complete character throw new ArgumentException( SR.Format(SR.Argument_RecursiveFallback, charRecursive), "chars"); } } }
// Copyright 2012 Henrik Feldt, Chris Patterson, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Transports.AzureServiceBus { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Configuration; using Context; using Logging; using Microsoft.ServiceBus.Messaging; /// <summary> /// Inbound transport implementation for Azure Service Bus. /// </summary> public class InboundAzureServiceBusTransport : IInboundTransport { static readonly ILog _logger = Logger.Get<InboundAzureServiceBusTransport>(); readonly IAzureServiceBusEndpointAddress _address; readonly ConnectionHandler<AzureServiceBusConnection> _connectionHandler; readonly IMessageNameFormatter _formatter; readonly IInboundSettings _inboundSettings; Consumer _consumer; bool _disposed; Publisher _publisher; public InboundAzureServiceBusTransport(IAzureServiceBusEndpointAddress address, ConnectionHandler<AzureServiceBusConnection> connectionHandler, IMessageNameFormatter formatter = null, IInboundSettings inboundSettings = null) { if (address == null) throw new ArgumentNullException("address"); if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); _address = address; _connectionHandler = connectionHandler; _formatter = formatter ?? new AzureServiceBusMessageNameFormatter(); _inboundSettings = inboundSettings; _logger.DebugFormat("created new inbound transport for '{0}'", address); } /// <summary> /// The formatter for message types /// </summary> public IMessageNameFormatter MessageNameFormatter { get { return _formatter; } } public void Dispose() { if (_disposed) return; _logger.DebugFormat("disposing transport for '{0}'", Address); try { RemoveConsumerBinding(); } finally { _disposed = true; } } public IEndpointAddress Address { get { return _address; } } public void Receive(Func<IReceiveContext, Action<IReceiveContext>> callback, TimeSpan timeout) { AddConsumerBinding(); _connectionHandler.Use(connection => { BrokeredMessage message = _consumer.Get(timeout); if (message == null) return; using (var stream = message.GetBody<Stream>()) { ReceiveContext context = ReceiveContext.FromBodyStream(stream); context.SetMessageId(message.MessageId); context.SetInputAddress(Address); context.SetCorrelationId(message.CorrelationId); context.SetContentType(message.ContentType); Action<IReceiveContext> receive = callback(context); if (receive == null) { Address.LogSkipped(message.MessageId); return; } try { receive(context); } catch (Exception ex) { if (_logger.IsErrorEnabled) _logger.Error("Consumer threw an exception", ex); message.Abandon(); } try { message.Complete(); } catch (MessageLockLostException ex) { if (_logger.IsErrorEnabled) _logger.Error("Message Lock Lost on message Complete()", ex); } catch (MessagingException ex) { if (_logger.IsErrorEnabled) _logger.Error("Generic MessagingException thrown", ex); } } }); } public IEnumerable<Type> SubscribeTopicsForPublisher(Type messageType, IMessageNameFormatter messageNameFormatter) { AddPublisherBinding(); IList<Type> messageTypes = new List<Type>(); _connectionHandler.Use(connection => { MessageName messageName = messageNameFormatter.GetMessageName(messageType); _publisher.CreateTopic(messageName.ToString()); messageTypes.Add(messageType); foreach (Type type in messageType.GetMessageTypes().Skip(1)) { MessageName interfaceName = messageNameFormatter.GetMessageName(type); // Create topics for inherited types before trying to setup the subscription _publisher.CreateTopic(interfaceName.Name.ToString()); _publisher.AddTopicSubscription(interfaceName.ToString(), messageName.ToString()); messageTypes.Add(type); } }); return messageTypes; } void AddPublisherBinding() { if (_publisher != null) return; _publisher = new Publisher(_address); _connectionHandler.AddBinding(_publisher); } void AddConsumerBinding() { if (_consumer != null) return; _consumer = new Consumer(_address, _inboundSettings); _connectionHandler.AddBinding(_consumer); } void RemoveConsumerBinding() { if (_consumer == null) return; _connectionHandler.RemoveBinding(_consumer); _consumer = null; } public void AddTopicSubscriber(TopicDescription value) { AddPublisherBinding(); _publisher.AddTopicSubscription(_address.QueueName, value.Path); } public void RemoveTopicSubscriber(TopicDescription value) { AddPublisherBinding(); _publisher.RemoveTopicSubscription(_address.QueueName, value.Path); } } }
// // TableViewBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Gtk; using System.Collections.Generic; using System.Linq; #if XWT_GTK3 using TreeModel = Gtk.ITreeModel; #endif namespace Xwt.GtkBackend { public class TableViewBackend: WidgetBackend, ICellRendererTarget { Dictionary<CellView,CellInfo> cellViews = new Dictionary<CellView, CellInfo> (); class CellInfo { public CellViewBackend Renderer; public Gtk.TreeViewColumn Column; } protected override void OnSetBackgroundColor (Xwt.Drawing.Color color) { // Gtk3 workaround (by rpc-scandinavia, see https://github.com/mono/xwt/pull/411) var selectedColor = Widget.GetBackgroundColor(StateType.Selected); Widget.SetBackgroundColor (StateType.Normal, Xwt.Drawing.Colors.Transparent); Widget.SetBackgroundColor (StateType.Selected, selectedColor); base.OnSetBackgroundColor (color); } public TableViewBackend () { var sw = new Gtk.ScrolledWindow (); sw.ShadowType = Gtk.ShadowType.In; sw.Child = new CustomTreeView (this); sw.Child.Show (); sw.Show (); base.Widget = sw; Widget.EnableSearch = false; } protected new Gtk.TreeView Widget { get { return (Gtk.TreeView)ScrolledWindow.Child; } } protected Gtk.ScrolledWindow ScrolledWindow { get { return (Gtk.ScrolledWindow)base.Widget; } } protected new ITableViewEventSink EventSink { get { return (ITableViewEventSink)base.EventSink; } } protected override Gtk.Widget EventsRootWidget { get { return ScrolledWindow.Child; } } public ScrollPolicy VerticalScrollPolicy { get { return ScrolledWindow.VscrollbarPolicy.ToXwtValue (); } set { ScrolledWindow.VscrollbarPolicy = value.ToGtkValue (); } } public ScrollPolicy HorizontalScrollPolicy { get { return ScrolledWindow.HscrollbarPolicy.ToXwtValue (); } set { ScrolledWindow.HscrollbarPolicy = value.ToGtkValue (); } } public GridLines GridLinesVisible { get { return Widget.EnableGridLines.ToXwtValue (); } set { Widget.EnableGridLines = value.ToGtkValue (); } } public IScrollControlBackend CreateVerticalScrollControl () { return new ScrollControltBackend (ScrolledWindow.Vadjustment); } public IScrollControlBackend CreateHorizontalScrollControl () { return new ScrollControltBackend (ScrolledWindow.Hadjustment); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TableViewEvent) { if (((TableViewEvent)eventId) == TableViewEvent.SelectionChanged) Widget.Selection.Changed += HandleWidgetSelectionChanged; } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TableViewEvent) { if (((TableViewEvent)eventId) == TableViewEvent.SelectionChanged) Widget.Selection.Changed -= HandleWidgetSelectionChanged; } } void HandleWidgetSelectionChanged (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } public object AddColumn (ListViewColumn col) { Gtk.TreeViewColumn tc = new Gtk.TreeViewColumn (); tc.Title = col.Title; tc.Resizable = col.CanResize; tc.Alignment = col.Alignment.ToGtkAlignment (); tc.SortIndicator = col.SortIndicatorVisible; tc.SortOrder = (SortType)col.SortDirection; if (col.SortDataField != null) tc.SortColumnId = col.SortDataField.Index; Widget.AppendColumn (tc); MapTitle (col, tc); MapColumn (col, tc); return tc; } void MapTitle (ListViewColumn col, Gtk.TreeViewColumn tc) { if (col.HeaderView == null) tc.Title = col.Title; else tc.Widget = CellUtil.CreateCellRenderer (ApplicationContext, col.HeaderView); } void MapColumn (ListViewColumn col, Gtk.TreeViewColumn tc) { foreach (var k in cellViews.Where (e => e.Value.Column == tc).Select (e => e.Key).ToArray ()) cellViews.Remove (k); foreach (var v in col.Views) { var r = CellUtil.CreateCellRenderer (ApplicationContext, Frontend, this, tc, v); cellViews [v] = new CellInfo { Column = tc, Renderer = r }; } } public void RemoveColumn (ListViewColumn col, object handle) { Widget.RemoveColumn ((Gtk.TreeViewColumn)handle); } public void UpdateColumn (ListViewColumn col, object handle, ListViewColumnChange change) { Gtk.TreeViewColumn tc = (Gtk.TreeViewColumn) handle; switch (change) { case ListViewColumnChange.Cells: tc.Clear (); MapColumn (col, tc); break; case ListViewColumnChange.Title: MapTitle (col, tc); break; case ListViewColumnChange.CanResize: tc.Resizable = col.CanResize; break; case ListViewColumnChange.SortIndicatorVisible: tc.SortIndicator = col.SortIndicatorVisible; break; case ListViewColumnChange.SortDirection: tc.SortOrder = (SortType)col.SortDirection; break; case ListViewColumnChange.SortDataField: if (col.SortDataField != null) tc.SortColumnId = col.SortDataField.Index; break; case ListViewColumnChange.Alignment: tc.Alignment = col.Alignment.ToGtkAlignment (); break; } } public void ScrollToRow (TreeIter pos) { if (Widget.Columns.Length > 0) Widget.ScrollToCell (Widget.Model.GetPath (pos), Widget.Columns[0], false, 0, 0); } public void SelectAll () { Widget.Selection.SelectAll (); } public void UnselectAll () { Widget.Selection.UnselectAll (); } public void SetSelectionMode (SelectionMode mode) { switch (mode) { case SelectionMode.Single: Widget.Selection.Mode = Gtk.SelectionMode.Single; break; case SelectionMode.Multiple: Widget.Selection.Mode = Gtk.SelectionMode.Multiple; break; } } protected Gtk.CellRenderer GetCellRenderer (CellView cell) { return cellViews [cell].Renderer.CellRenderer; } protected Gtk.TreeViewColumn GetCellColumn (CellView cell) { return cellViews [cell].Column; } #region ICellRendererTarget implementation public void PackStart (object target, Gtk.CellRenderer cr, bool expand) { #if !XWT_GTK3 // Gtk2 tree background color workaround if (UsingCustomBackgroundColor) cr.CellBackgroundGdk = BackgroundColor.ToGtkValue (); #endif ((Gtk.TreeViewColumn)target).PackStart (cr, expand); } public void PackEnd (object target, Gtk.CellRenderer cr, bool expand) { ((Gtk.TreeViewColumn)target).PackEnd (cr, expand); } public void AddAttribute (object target, Gtk.CellRenderer cr, string field, int col) { ((Gtk.TreeViewColumn)target).AddAttribute (cr, field, col); } public void SetCellDataFunc (object target, Gtk.CellRenderer cr, Gtk.CellLayoutDataFunc dataFunc) { ((Gtk.TreeViewColumn)target).SetCellDataFunc (cr, dataFunc); } Rectangle ICellRendererTarget.GetCellBounds (object target, Gtk.CellRenderer cra, Gtk.TreeIter iter) { var col = (TreeViewColumn)target; var path = Widget.Model.GetPath (iter); Gdk.Rectangle rect = Widget.GetCellArea (path, col); int x = 0; int th = 0; CellRenderer[] renderers = col.GetCellRenderers(); foreach (CellRenderer cr in renderers) { int sp, wi, he, xo, yo; col.CellGetSize (rect, out xo, out yo, out wi, out he); col.CellGetPosition (cr, out sp, out wi); Gdk.Rectangle crect = new Gdk.Rectangle (x, rect.Y, wi, rect.Height); #if !XWT_GTK3 cr.GetSize (Widget, ref crect, out xo, out yo, out wi, out he); #endif if (cr == cra) { Widget.ConvertBinWindowToWidgetCoords (rect.X + x, rect.Y, out xo, out yo); // There seems to be a 1px vertical padding yo++; rect.Height -= 2; return new Rectangle (xo, yo + 1, wi, rect.Height - 2); } if (cr != renderers [renderers.Length - 1]) x += crect.Width + col.Spacing + 1; else x += wi + 1; if (he > th) th = he; } return Rectangle.Zero; } Rectangle ICellRendererTarget.GetCellBackgroundBounds (object target, Gtk.CellRenderer cr, Gtk.TreeIter iter) { var col = (TreeViewColumn)target; var path = Widget.Model.GetPath (iter); var a = Widget.GetBackgroundArea (path, (TreeViewColumn)target); int x, y, w, h; col.CellGetSize (a, out x, out y, out w, out h); return new Rectangle (a.X + x, a.Y + y, w, h); } public virtual void SetCurrentEventRow (string path) { } Gtk.Widget ICellRendererTarget.EventRootWidget { get { return Widget; } } TreeModel ICellRendererTarget.Model { get { return Widget.Model; } } Gtk.TreeIter ICellRendererTarget.PressedIter { get; set; } CellViewBackend ICellRendererTarget.PressedCell { get; set; } public bool GetCellPosition (Gtk.CellRenderer r, int ex, int ey, out int cx, out int cy, out Gtk.TreeIter it) { Gtk.TreeViewColumn col; Gtk.TreePath path; int cellx, celly; cx = cy = 0; it = Gtk.TreeIter.Zero; if (!Widget.GetPathAtPos (ex, ey, out path, out col, out cellx, out celly)) return false; if (!Widget.Model.GetIterFromString (out it, path.ToString ())) return false; int sp, w; if (col.CellGetPosition (r, out sp, out w)) { if (cellx >= sp && cellx < sp + w) { Widget.ConvertBinWindowToWidgetCoords (ex, ey, out cx, out cy); return true; } } return false; } public void QueueDraw (object target, Gtk.TreeIter iter) { var p = Widget.Model.GetPath (iter); var r = Widget.GetBackgroundArea (p, (Gtk.TreeViewColumn)target); int x, y; Widget.ConvertBinWindowToWidgetCoords (r.X, r.Y, out x, out y); Widget.QueueDrawArea (x, y, r.Width, r.Height); } #endregion } class CustomTreeView: Gtk.TreeView { WidgetBackend backend; public CustomTreeView (WidgetBackend b) { backend = b; } protected override void OnDragDataDelete (Gdk.DragContext context) { // This method is override to avoid the default implementation // being called. The default implementation deletes the // row being dragged, and we don't want that backend.DoDragaDataDelete (); } } }
/* * Naiad ver. 0.5 * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.Linq.Expressions; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Frameworks; using Microsoft.Research.Naiad.Diagnostics; namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.Operators { internal class Join<K, V1, V2, S1, S2, T, R> : OperatorImplementations.BinaryStatefulOperator<K, V1, V2, S1, S2, T, R> where K : IEquatable<K> where V1 : IEquatable<V1> where V2 : IEquatable<V2> where S1 : IEquatable<S1> where S2 : IEquatable<S2> where T : Time<T> where R : IEquatable<R> { Func<K, V1, V2, R> resultSelector; // performs the same role as keyIndices, just with less memory. Dictionary<K, JoinKeyIndices> JoinKeys; NaiadList<int> times = new NaiadList<int>(1); NaiadList<Weighted<V1>> differences1 = new NaiadList<Weighted<V1>>(1); NaiadList<Weighted<V2>> differences2 = new NaiadList<Weighted<V2>>(1); public override void OnInput1(Weighted<S1> entry, T time) { //Console.WriteLine("Join Recv1"); var k = key1(entry.record); var v = value1(entry.record); var state = new JoinKeyIndices(); if (!JoinKeys.TryGetValue(k, out state)) state = new JoinKeyIndices(); if (!inputShutdown2)//!this.inputImmutable2) { inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed1); inputTrace1.Introduce(ref state.processed1, v, entry.weight, internTable.Intern(time)); } if (inputShutdown1) Console.Error.WriteLine("Error in Join input shutdown1"); if (state.processed2 != 0) { inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed2); times.Clear(); inputTrace2.EnumerateTimes(state.processed2, times); for (int i = 0; i < times.Count; i++) { differences2.Clear(); inputTrace2.EnumerateDifferenceAt(state.processed2, times.Array[i], differences2); var newTime = time.Join(internTable.times[times.Array[i]]); var output = this.Output.GetBufferForTime(newTime); for (int j = 0; j < differences2.Count; j++) if (differences2.Array[j].weight != 0) output.Send(resultSelector(k, v, differences2.Array[j].record).ToWeighted(entry.weight * differences2.Array[j].weight)); } } if (state.IsEmpty) JoinKeys.Remove(k); else JoinKeys[k] = state; } public override void OnInput2(Weighted<S2> entry, T time) { var k = key2(entry.record); var v = value2(entry.record); var state = new JoinKeyIndices(); if (!JoinKeys.TryGetValue(k, out state)) state = new JoinKeyIndices(); if (!inputShutdown1) { inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed2); inputTrace2.Introduce(ref state.processed2, v, entry.weight, internTable.Intern(time)); } if (inputShutdown2) Console.Error.WriteLine("Error in Join input shutdown2"); if (state.processed1 != 0) { inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed1); times.Clear(); inputTrace1.EnumerateTimes(state.processed1, times); for (int i = 0; i < times.Count; i++) { differences1.Clear(); inputTrace1.EnumerateDifferenceAt(state.processed1, times.Array[i], differences1); var newTime = time.Join(internTable.times[times.Array[i]]); var output = this.Output.GetBufferForTime(newTime); for (int j = 0; j < differences1.Count; j++) if (differences1.Array[j].weight != 0) output.Send(resultSelector(k, differences1.Array[j].record, v).ToWeighted(entry.weight * differences1.Array[j].weight)); } } if (state.IsEmpty) JoinKeys.Remove(k); else JoinKeys[k] = state; } protected override void OnShutdown() { base.OnShutdown(); //Console.Error.WriteLine("Shutting down Join: {0}", this); JoinKeys = null; times = null; difference1 = null; difference2 = null; } bool inputShutdown1 = false; // set once an input is drained (typically: immutable, read once) bool inputShutdown2 = false; // set once an input is drained (typically: immutable, read once) public override void OnNotify(T workTime) { // if input is immutable, we can shut down the other trace if (this.inputImmutable1 && !inputShutdown1) { Logging.Info("{0}: Shutting down input1; nulling input2", this); inputTrace2 = null; inputShutdown1 = true; } // if input is immutable, we can shut down the other trace if (this.inputImmutable2 && !inputShutdown2) { Logging.Info("{0}: Shutting down input2; nulling input1", this); inputTrace1 = null; inputShutdown2 = true; } base.OnNotify(workTime); } #region Checkpointing /* Checkpoint format: * (base) * if !terminated * Dictionary<K,JoinKeyIndices> JoinKeys */ protected override void Checkpoint(NaiadWriter writer) { base.Checkpoint(writer); if (!this.isShutdown) { this.JoinKeys.Checkpoint(writer); } } protected override void Restore(NaiadReader reader) { base.Restore(reader); if (!this.isShutdown) { this.JoinKeys.Restore(reader); } } #endregion public override void OnReceive1(Message<Weighted<S1>, T> message) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput1(message.payload[i], message.time); } public override void OnReceive2(Message<Weighted<S2>, T> message) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput2(message.payload[i], message.time); } public Join(int index, Stage<T> collection, bool input1Immutable, bool input2Immutable, Expression<Func<S1, K>> k1, Expression<Func<S2, K>> k2, Expression<Func<S1, V1>> v1, Expression<Func<S2, V2>> v2, Expression<Func<K, V1, V2, R>> r) : base(index, collection, input1Immutable, input2Immutable, k1, k2, v1, v2) { resultSelector = r.Compile(); keyIndices = new Dictionary<K,BinaryKeyIndices>(); JoinKeys = new Dictionary<K, JoinKeyIndices>(); //collection.LeftInput.Register(new ActionReceiver<Weighted<S1>, T>(this, x => { OnInput1(x.s, x.t); this.ScheduleAt(x.t); })); //collection.RightInput.Register(new ActionReceiver<Weighted<S2>, T>(this, x => { OnInput2(x.s, x.t); this.ScheduleAt(x.t); })); //this.input1 = new ActionReceiver<Weighted<S1>, T>(this, x => { this.OnInput1(x.s, x.t); this.ScheduleAt(x.t); }); //this.input2 = new ActionReceiver<Weighted<S2>, T>(this, x => { this.OnInput2(x.s, x.t); this.ScheduleAt(x.t); }); } } internal class JoinIntKeyed<V1, V2, S1, S2, T, R> : OperatorImplementations.BinaryStatefulIntKeyedOperator<V1, V2, S1, S2, T, R> where V1 : IEquatable<V1> where V2 : IEquatable<V2> where S1 : IEquatable<S1> where S2 : IEquatable<S2> where T : Time<T> where R : IEquatable<R> { Func<Int32, V1, V2, R> resultSelector; // performs the same role as keyIndices, just with less memory. JoinIntKeyIndices[][] JoinKeys; NaiadList<int> times = new NaiadList<int>(1); NaiadList<Weighted<V1>> differences1 = new NaiadList<Weighted<V1>>(1); NaiadList<Weighted<V2>> differences2 = new NaiadList<Weighted<V2>>(1); private int parts; public override void OnInput1(Weighted<S1> entry, T time) { var k = key1(entry.record); var v = value1(entry.record); var index = k / parts; if (JoinKeys[index / 65536] == null) JoinKeys[index / 65536] = new JoinIntKeyIndices[65536]; var state = JoinKeys[index / 65536][index % 65536]; if (!inputShutdown2) { inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed1); inputTrace1.Introduce(ref state.processed1, v, entry.weight, internTable.Intern(time)); } if (inputShutdown1) Console.Error.WriteLine("Error in Join; input1 shutdown but recv'd input2"); if (state.processed2 != 0) { inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed2); times.Clear(); inputTrace2.EnumerateTimes(state.processed2, times); for (int i = 0; i < times.Count; i++) { differences2.Clear(); inputTrace2.EnumerateDifferenceAt(state.processed2, times.Array[i], differences2); var newTime = time.Join(internTable.times[times.Array[i]]); var output = this.Output.GetBufferForTime(newTime); for (int j = 0; j < differences2.Count; j++) if (differences2.Array[j].weight != 0) output.Send(resultSelector(k, v, differences2.Array[j].record).ToWeighted(entry.weight * differences2.Array[j].weight)); } } JoinKeys[index / 65536][index % 65536] = state; } public override void OnInput2(Weighted<S2> entry, T time) { var k = key2(entry.record); var v = value2(entry.record); var index = k / parts; if (JoinKeys[index / 65536] == null) JoinKeys[index / 65536] = new JoinIntKeyIndices[65536]; var state = JoinKeys[index / 65536][index % 65536]; if (!inputShutdown1) { inputTrace2.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed2); inputTrace2.Introduce(ref state.processed2, v, entry.weight, internTable.Intern(time)); } if (inputShutdown2) Console.Error.WriteLine("Error in Join; input2 shutdown but recv'd input1"); if (state.processed1 != 0) { inputTrace1.EnsureStateIsCurrentWRTAdvancedTimes(ref state.processed1); times.Clear(); inputTrace1.EnumerateTimes(state.processed1, times); for (int i = 0; i < times.Count; i++) { differences1.Clear(); inputTrace1.EnumerateDifferenceAt(state.processed1, times.Array[i], differences1); var newTime = time.Join(internTable.times[times.Array[i]]); var output = this.Output.GetBufferForTime(newTime); for (int j = 0; j < differences1.Count; j++) if (differences1.Array[j].weight != 0) output.Send(resultSelector(k, differences1.Array[j].record, v).ToWeighted(entry.weight * differences1.Array[j].weight)); } } JoinKeys[index / 65536][index % 65536] = state; } protected override void OnShutdown() { base.OnShutdown(); //Console.Error.WriteLine("Shutting down Join: {0}", this); JoinKeys = null; times = null; differences1 = null; differences2 = null; } bool inputShutdown1 = false; // set once an input is drained (typically: immutable, read once) bool inputShutdown2 = false; // set once an input is drained (typically: immutable, read once) public override void OnNotify(T workTime) { if (this.inputImmutable1 && this.inputTrace1 != null) this.inputTrace1.Compact(); if (this.inputImmutable2 && this.inputTrace2 != null) this.inputTrace2.Compact(); // if input is immutable, we can shut down the other trace if (this.inputImmutable1 && !inputShutdown1) { //Console.Error.WriteLine("{0}: Shutting down input1; nulling input2", this); Logging.Info("{0}: Shutting down input1; nulling input2", this); inputTrace2 = null; inputShutdown1 = true; } // if input is immutable, we can shut down the other trace if (this.inputImmutable2 && !inputShutdown2) { //Console.Error.WriteLine("{0}: Shutting down input2; nulling input1", this); Logging.Info("{0}: Shutting down input2; nulling input1", this); inputTrace1 = null; inputShutdown2 = true; } base.OnNotify(workTime); } #region Checkpointing /* Checkpoint format: * (base) * if !terminated * int keyIndicesLength * (int n,n*BinaryKeyIndices|-1)*keyIndicesLength keyIndices */ protected override void Checkpoint(NaiadWriter writer) { base.Checkpoint(writer); if (!this.isShutdown) { for (int i = 0; i < this.JoinKeys.Length; ++i) { if (this.JoinKeys[i] == null) writer.Write(-1); else { writer.Write(this.JoinKeys[i].Length); for (int j = 0; j < this.JoinKeys[i].Length; ++j) writer.Write(this.JoinKeys[i][j]); } } } } protected override void Restore(NaiadReader reader) { base.Restore(reader); if (!this.isShutdown) { for (int i = 0; i < this.JoinKeys.Length; ++i) { int count = reader.Read<int>(); if (count >= 0) { this.JoinKeys[i] = new JoinIntKeyIndices[count]; for (int j = 0; j < this.JoinKeys[i].Length; ++j) this.JoinKeys[i][j] = reader.Read<JoinIntKeyIndices>(); } else this.JoinKeys[i] = null; } } } #endregion public override void OnReceive1(Message<Weighted<S1>, T> message) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput1(message.payload[i], message.time); } public override void OnReceive2(Message<Weighted<S2>, T> message) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput2(message.payload[i], message.time); } public JoinIntKeyed(int index, Stage<T> collection, bool input1Immutable, bool input2Immutable, Expression<Func<S1, Int32>> k1, Expression<Func<S2, Int32>> k2, Expression<Func<S1, V1>> v1, Expression<Func<S2, V2>> v2, Expression<Func<Int32, V1, V2, R>> r) : base(index, collection, input1Immutable, input2Immutable, k1, k2, v1, v2) { resultSelector = r.Compile(); // Inhibits verbose serialization of the parent's keyIndices. keyIndices = new BinaryKeyIndices[0][]; JoinKeys = new JoinIntKeyIndices[65536][]; this.parts = collection.Placement.Count; } } }
// 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. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // using System; using System.Diagnostics; namespace System.Text { public class UTF7Encoding : Encoding { private const String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. private const String directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. private const String optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // Used by Encoding.UTF7 for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly UTF7Encoding s_default = new UTF7Encoding(); // The set of base 64 characters. private byte[] _base64Bytes; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. private sbyte[] _base64Values; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. private bool[] _directEncode; private bool _allowOptionals; private const int UTF7_CODEPAGE = 65000; public UTF7Encoding() : this(false) { } public UTF7Encoding(bool allowOptionals) : base(UTF7_CODEPAGE) //Set the data item. { // Allowing optionals? _allowOptionals = allowOptionals; // Make our tables MakeTables(); } private void MakeTables() { // Build our tables _base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) _base64Bytes[i] = (byte)base64Chars[i]; _base64Values = new sbyte[128]; for (int i = 0; i < 128; i++) _base64Values[i] = -1; for (int i = 0; i < 64; i++) _base64Values[_base64Bytes[i]] = (sbyte)i; _directEncode = new bool[128]; int count = directChars.Length; for (int i = 0; i < count; i++) { _directEncode[directChars[i]] = true; } if (_allowOptionals) { count = optionalChars.Length; for (int i = 0; i < count; i++) { _directEncode[optionalChars[i]] = true; } } } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. internal override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevant because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) this.encoderFallback = new EncoderReplacementFallback(String.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } public override bool Equals(Object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) { return (_allowOptionals == that._allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } // Compared to all the other encodings, variations of UTF7 are unlikely public override int GetHashCode() { return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string s) { // Validate input if (s==null) throw new ArgumentNullException("s"); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0]) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (count == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; // Default bits & count int bits = 0; int bitCount = -1; // prepare our helpers Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { bits = encoder.bits; bitCount = encoder.bitCount; // May have had too many left over while (bitCount >= 6) { bitCount -= 6; // If we fail we'll never really have enough room if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) ThrowBytesOverflow(encoder, buffer.Count == 0); } } while (buffer.MoreData) { char currentChar = buffer.GetNextChar(); if (currentChar < 0x80 && _directEncode[currentChar]) { if (bitCount >= 0) { if (bitCount > 0) { // Try to add the next byte if (!buffer.AddByte(_base64Bytes[bits << 6 - bitCount & 0x3F])) break; // Stop here, didn't throw bitCount = 0; } // Need to get emit '-' and our char, 2 bytes total if (!buffer.AddByte((byte)'-')) break; // Stop here, didn't throw bitCount = -1; } // Need to emit our char if (!buffer.AddByte((byte)currentChar)) break; // Stop here, didn't throw } else if (bitCount < 0 && currentChar == '+') { if (!buffer.AddByte((byte)'+', (byte)'-')) break; // Stop here, didn't throw } else { if (bitCount < 0) { // Need to emit a + and 12 bits (3 bytes) // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time if (!buffer.AddByte((byte)'+')) break; // Stop here, didn't throw // We're now in bit mode, but haven't stored data yet bitCount = 0; } // Add our bits bits = bits << 16 | currentChar; bitCount += 16; while (bitCount >= 6) { bitCount -= 6; if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) { bitCount += 6; // We didn't use these bits currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte // --'d it when we ran out of space break; // Stop here, not enough room for bytes } } if (bitCount >= 6) break; // Didn't have room to encode enough bits } } // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) { if (buffer.AddByte(_base64Bytes[(bits << (6 - bitCount)) & 0x3F])) { // Emitted spare bits, 0 bits left bitCount = 0; } } // If converting and failed bitCount above, then we'll fail this too if (buffer.AddByte((byte)'-')) { // turned off bit mode'; bits = 0; bitCount = -1; } else // If not successful, convert will maintain state for next time, also // AddByte will have decremented our char count, however we need it to remain the same buffer.GetNextChar(); } // Do we have an encoder we're allowed to use? // bytes == null if counting, so don't use encoder then if (bytes != null && encoder != null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; encoder.bitCount = bitCount; encoder._charsUsed = buffer.CharsUsed; } return buffer.Count; } internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder)baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( this, decoder, chars, charCount, bytes, byteCount); // Get decoder info int bits = 0; int bitCount = -1; bool firstByte = false; if (decoder != null) { bits = decoder.bits; bitCount = decoder.bitCount; firstByte = decoder.firstByte; Debug.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } // We may have had bits in the decoder that we couldn't output last time, so do so now if (bitCount >= 16) { // Check our decoder buffer if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF))) ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert // Used this one, clean up extra bits bitCount -= 16; } // Loop through the input while (buffer.MoreData) { byte currentByte = buffer.GetNextByte(); int c; if (bitCount >= 0) { // // Modified base 64 encoding. // sbyte v; if (currentByte < 0x80 && ((v = _base64Values[currentByte]) >= 0)) { firstByte = false; bits = (bits << 6) | ((byte)v); bitCount += 6; if (bitCount >= 16) { c = (bits >> (bitCount - 16)) & 0xFFFF; bitCount -= 16; } // If not enough bits just continue else continue; } else { // If it wasn't a base 64 byte, everything's going to turn off base 64 mode bitCount = -1; if (currentByte != '-') { // >= 0x80 (because of 1st if statemtn) // We need this check since the _base64Values[b] check below need b <= 0x7f. // This is not a valid base 64 byte. Terminate the shifted-sequence and // emit this byte. // not in base 64 table // According to the RFC 1642 and the example code of UTF-7 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte // Chars won't be updated unless this works, try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Used that byte, we're done with it continue; } // // The encoding for '+' is "+-". // if (firstByte) c = '+'; // We just turn it off if not emitting a +, so we're done. else continue; } // // End of modified base 64 encoding block. // } else if (currentByte == '+') { // // Found the start of a modified base 64 encoding block or a plus sign. // bitCount = 0; firstByte = true; continue; } else { // Normal character if (currentByte >= 0x80) { // Try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Done falling back continue; } // Use the normal character c = currentByte; } if (c >= 0) { // Check our buffer if (!buffer.AddChar((char)c)) { // No room. If it was a plain char we'll try again later. // Note, we'll consume this byte and stick it in decoder, even if we can't output it if (bitCount >= 0) // Can we rememmber this byte (char) { buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed bitCount += 16; // We'll still need that char we have in our bits } break; // didn't throw, stop } } } // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) if (chars != null && decoder != null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) { // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = bits; decoder.bitCount = bitCount; decoder.firstByte = firstByte; } decoder._bytesUsed = buffer.BytesUsed; } // else ignore any hanging bits. // Return our count return buffer.Count; } public override System.Text.Decoder GetDecoder() { return new UTF7Encoding.Decoder(this); } public override System.Text.Encoder GetEncoder() { return new UTF7Encoding.Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark. // Therefore, the max byte should be: // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6); // That is always <= 2 + 3 * charCount; // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char. // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off // encoding if MustFlush is true. // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char. // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3 // bytes allows us to turn off and then back on base64 mode if necessary. // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all // code points are encodable int UTF7. long byteCount = (long)charCount * 3 + 2; // check for overflow if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. int charCount = byteCount; if (charCount == 0) charCount = 1; return charCount; } // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change private sealed class Decoder : DecoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; /*private*/ internal bool firstByte; public Decoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bits = 0; this.bitCount = -1; this.firstByte = false; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { // NOTE: This forces the last -, which some encoder might not encode. If we // don't see it we don't think we're done reading. return (this.bitCount != -1); } } } // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change private sealed class Encoder : EncoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; public Encoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bitCount = -1; this.bits = 0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { return (this.bits != 0 || this.bitCount != -1); } } } // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. private sealed class DecoderUTF7Fallback : DecoderFallback { // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderUTF7Fallback() { } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderUTF7FallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { // returns 1 char per bad byte return 1; } } public override bool Equals(Object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) { return true; } return (false); } public override int GetHashCode() { return 984; } } private sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { // Store our default string private char cFallback = (char)0; private int iCount = -1; private int iSize; // Construction public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback) { } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; // Any of the fallback characters can be handled except for 0 if (cFallback == 0) { return false; } iCount = iSize = 1; return true; } public override char GetNextChar() { if (iCount-- > 0) return cFallback; // Note: this means that 0 in UTF7 stream will never be emitted. return (char)0; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } // return true if we were allowed to do this return (iCount >= 0 && iCount <= iSize); } // Return # of chars left in this fallback public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } // Can't fallback a byte 0, so return for that case, 1 otherwise. return bytes[0] == 0 ? 0 : 1; } } } }
/* * CCControlSlider * * Copyright 2011 Yannick Loriot. All rights reserved. * http://yannickloriot.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. * * Converted to c++ / cocos2d-x by Angus C */ using System; using System.Diagnostics; namespace CocosSharp { public class CCControlSlider : CCControl { float maximumValue; float minimumValue; float value; #region Properties public float SnappingInterval { get; set; } public float MinimumAllowedValue { get; set; } public float MaximumAllowedValue { get; set; } public CCSprite ThumbSprite { get; set; } public CCSprite ProgressSprite { get; set; } public CCSprite BackgroundSprite { get; set; } public float Value { get { return this.value; } set { this.value = CCMathHelper.Clamp(value, MinimumValue, MaximumValue); NeedsLayout(); SendActionsForControlEvents(CCControlEvent.ValueChanged); } } public float MinimumValue { get { return minimumValue; } set { minimumValue = value; if (minimumValue >= maximumValue) { maximumValue = minimumValue + 1.0f; } MinimumAllowedValue = minimumValue; Value = value; } } public float MaximumValue { get { return maximumValue; } set { maximumValue = value; if (maximumValue <= minimumValue) { minimumValue = maximumValue - 1.0f; } MaximumAllowedValue = maximumValue; Value = value; } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; if (ThumbSprite != null) { ThumbSprite.Opacity = (byte) (value ? 255 : 128); } } } #endregion Properties #region Constructors public CCControlSlider(string bgFile, string progressFile, string thumbFile) : this(new CCSprite(bgFile), new CCSprite(progressFile), new CCSprite(thumbFile)) { } public CCControlSlider(CCSprite backgroundSprite, CCSprite progressSprite, CCSprite thumbSprite) { Debug.Assert(backgroundSprite != null, "Background sprite must be not nil"); Debug.Assert(progressSprite != null, "Progress sprite must be not nil"); Debug.Assert(thumbSprite != null, "Thumb sprite must be not nil"); BackgroundSprite = backgroundSprite; ProgressSprite = progressSprite; ThumbSprite = thumbSprite; minimumValue = 0.0f; maximumValue = 1.0f; Value = minimumValue; IgnoreAnchorPointForPosition = false; // Defines the content size CCRect maxRect = CCControlUtils.CCRectUnion(backgroundSprite.BoundingBox, thumbSprite.BoundingBox); ContentSize = new CCSize(maxRect.Size.Width, maxRect.Size.Height); // Add the slider background BackgroundSprite.AnchorPoint = new CCPoint(0.5f, 0.5f); BackgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); AddChild(BackgroundSprite); // Add the progress bar ProgressSprite.AnchorPoint = new CCPoint(0.0f, 0.5f); ProgressSprite.Position = new CCPoint(0.0f, ContentSize.Height / 2); AddChild(ProgressSprite); // Add the slider thumb ThumbSprite.Position = new CCPoint(0, ContentSize.Height / 2); AddChild(ThumbSprite); // Register Touch Event var touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = OnTouchBegan; touchListener.OnTouchMoved = OnTouchMoved; touchListener.OnTouchEnded = OnTouchEnded; AddEventListener(touchListener); } #endregion Constructors protected float ValueForLocation(CCPoint location) { float percent = location.X / BackgroundSprite.ContentSize.Width; return Math.Max(Math.Min(minimumValue + percent * (MaximumValue - MinimumValue), MaximumAllowedValue), MinimumAllowedValue); } protected virtual CCPoint LocationFromTouch(CCTouch touch) { CCPoint touchLocation = touch.LocationOnScreen; // Get the touch position touchLocation = WorldToParentspace(Layer.ScreenToWorldspace(touchLocation)); // Convert to the node space of this class if (touchLocation.X < 0) { touchLocation.X = 0; } else if (touchLocation.X > BackgroundSprite.ContentSize.Width) { touchLocation.X = BackgroundSprite.ContentSize.Width; } return touchLocation; } public override bool IsTouchInside(CCTouch touch) { CCPoint touchLocation = touch.LocationOnScreen; touchLocation = Layer.ScreenToWorldspace(touchLocation); CCRect rect = BoundingBoxTransformedToWorld; rect.Size.Width += ThumbSprite.ContentSize.Width; rect.Origin.X -= ThumbSprite.ContentSize.Width / 2; return rect.ContainsPoint(touchLocation); } #region Slider event handling protected void SliderBegan(CCPoint location) { Selected = true; ThumbSprite.Color = CCColor3B.Gray; Value = ValueForLocation(location); } protected void SliderMoved(CCPoint location) { Value = ValueForLocation(location); } protected void SliderEnded(CCPoint location) { if (Selected) { Value = ValueForLocation(ThumbSprite.Position); } ThumbSprite.Color = CCColor3B.White; Selected = false; } bool OnTouchBegan(CCTouch touch, CCEvent touchEvent) { if (!IsTouchInside(touch) || !Enabled || !Visible) return false; CCPoint location = LocationFromTouch(touch); SliderBegan(location); return true; } void OnTouchMoved(CCTouch pTouch, CCEvent touchEvent) { CCPoint location = LocationFromTouch(pTouch); SliderMoved(location); } void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent) { SliderEnded(CCPoint.Zero); } #endregion Slider event handling public override void NeedsLayout() { if (null == ThumbSprite || null == BackgroundSprite || null == ProgressSprite) { return; } // Update thumb position for new value float percent = (value - minimumValue) / (maximumValue - minimumValue); CCPoint pos = ThumbSprite.Position; pos.X = percent * BackgroundSprite.ContentSize.Width; ThumbSprite.Position = pos; // Stretches content proportional to newLevel CCRect textureRect = ProgressSprite.TextureRectInPixels; textureRect = new CCRect(textureRect.Origin.X, textureRect.Origin.Y, pos.X, textureRect.Size.Height); ProgressSprite.TextureRectInPixels = textureRect; ProgressSprite.ContentSize = textureRect.Size; } }; }
// 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.Diagnostics.Contracts; using System.Linq; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; namespace Microsoft.Contracts { static class ContextHelper { /// <summary> /// Code taken from Pex /// </summary> /// <param name="serviceProvider"></param> /// <param name="point"></param> /// <returns></returns> public static bool TryGetSelectionPoint(IServiceProvider serviceProvider, out VirtualPoint point) { Contract.Requires(serviceProvider != null); Contract.Ensures(Contract.ValueAtReturn(out point) != null || !Contract.Result<bool>()); point = null; var dte = VsServiceProviderHelper.GetService<DTE>(serviceProvider); if (dte == null) { return false; } try { // code window supported only Document document = dte.ActiveDocument; if (document != null) { TextDocument tdoc = document.Object("TextDocument") as TextDocument; if (tdoc != null) { try { Contract.Assume(tdoc.Selection != null); point = tdoc.Selection.TopPoint; } catch (COMException) { } } } } catch (ArgumentException) { } // reported by user catch (COMException) { } return point != null; } /// <summary> /// Code stolen from Pex. /// </summary> /// <param name="serviceProvider"></param> /// <param name="point"></param> /// <returns></returns> public static bool TryGetSelectedElement<T>( IServiceProvider serviceProvider, vsCMElement elementType, out T element) where T : class { Contract.Requires(serviceProvider != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out element) != default(T)); element = default(T); try { VirtualPoint point; if (ContextHelper.TryGetSelectionPoint(serviceProvider, out point)) element = point.get_CodeElement(elementType) as T; } catch (COMException) { } return element != null; } private static bool TryMangleNamespaceName(CodeNamespace codeNamespace, out string mangled) { Contract.Requires(codeNamespace != null); mangled = null; string res = codeNamespace.FullName; Contract.Assume(res != null); switch(codeNamespace.Language) { case CodeModelLanguageConstants.vsCMLanguageVB: res = res.Replace("[", "").Replace("]", ""); break; case CodeModelLanguageConstants.vsCMLanguageCSharp: res = res.Replace("@", ""); break; default : return false; } mangled = res; return true; } public static bool TryGetSelectedNamespaceFullNameMangled(IServiceProvider serviceProvider, out string fullName) { Contract.Requires(serviceProvider != null); fullName = null; CodeNamespace codeNamespace; if(!TryGetSelectedElement<CodeNamespace>(serviceProvider, vsCMElement.vsCMElementNamespace, out codeNamespace)) return false; return TryMangleNamespaceName(codeNamespace, out fullName); } /// <summary> /// Do not handle generic types nor array types /// </summary> /// <param name="codeType"></param> /// <param name="mangled"></param> /// <returns></returns> private static bool TryMangleTypeName(CodeType codeType, out string mangled) { Contract.Requires(codeType != null); mangled = null; string namespaceFullName = codeType.Namespace == null ? "" : codeType.Namespace.FullName; if (namespaceFullName == null) { return false; } string name = codeType.FullName; Contract.Assume(name != null); if(namespaceFullName != "" && !name.StartsWith(namespaceFullName + ".")) return false; int startIndex = namespaceFullName == "" ? 0 : namespaceFullName.Length + 1; Contract.Assert(startIndex <= name.Length); name = name.Substring(startIndex); string genericsMarker; switch(codeType.Language) { case CodeModelLanguageConstants.vsCMLanguageVB: name = name.Replace("[", "").Replace("]", ""); genericsMarker = "(Of"; break; case CodeModelLanguageConstants.vsCMLanguageCSharp: name = name.Replace("@", ""); genericsMarker = "<"; break; default : return false; } string namespaceMangled = null; if(codeType.Namespace != null && !TryMangleNamespaceName(codeType.Namespace, out namespaceMangled)) return false; namespaceMangled = namespaceMangled == null ? "" : namespaceMangled + "."; mangled = String.Format("{0}{1}", namespaceMangled, String.Join("+", name .Split('.') .Select(className => { int startGenerics = className.LastIndexOf(genericsMarker); if (startGenerics >= 0) return className.Substring(0, startGenerics) + '`' + (className.Count(c => c == ',')+1).ToString(); return className; }))); return true; } public static bool TryGetSelectedTypeFullNameMangled(IServiceProvider serviceProvider, out string fullName) { Contract.Requires(serviceProvider != null); fullName = null; CodeType codeType; if (!TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementClass, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementStruct, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementInterface, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementDelegate, out codeType)) { return false; } return TryMangleTypeName(codeType, out fullName); } /// <summary> /// Works for methods, properties, events, constructors, destructors. /// Do NOT work for fields. /// Do NOT work for operators (TODO). /// Does not contain the function parameters types (TODO). /// </summary> public static bool TryGetSelectedMemberFullNameMangled(IServiceProvider serviceProvider, out string fullName) { Contract.Requires(serviceProvider != null); fullName = null; CodeElement2 codeElmt; if (!TryGetSelectedElement<CodeElement2>(serviceProvider, vsCMElement.vsCMElementFunction, out codeElmt) && !TryGetSelectedElement<CodeElement2>(serviceProvider, vsCMElement.vsCMElementProperty, out codeElmt) && !TryGetSelectedElement<CodeElement2>(serviceProvider, vsCMElement.vsCMElementEvent, out codeElmt)) return false; string name = codeElmt.Name; Contract.Assume(name != null); var codeFunc = codeElmt as CodeFunction2; if (codeFunc != null && (codeFunc.FunctionKind & vsCMFunction.vsCMFunctionConstructor) != 0) name = codeFunc.IsShared ? ".cctor" : ".ctor"; else if (codeFunc != null && (codeFunc.FunctionKind & vsCMFunction.vsCMFunctionDestructor) != 0) name = "Finalize"; else if (codeFunc != null && (codeFunc.FunctionKind & vsCMFunction.vsCMFunctionOperator) != 0) return false; // TODO else switch (codeElmt.Language) { case CodeModelLanguageConstants.vsCMLanguageVB: name = name.Replace("[", "").Replace("]", ""); break; case CodeModelLanguageConstants.vsCMLanguageCSharp: if (name == "this") // hack for indexer name = "Item"; name = name.Replace("@", ""); break; default: return false; } CodeType codeType; if (!TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementClass, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementStruct, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementInterface, out codeType) && !TryGetSelectedElement<CodeType>(serviceProvider, vsCMElement.vsCMElementDelegate, out codeType)) { return false; } string typeFullName; if (!TryMangleTypeName(codeType, out typeFullName)) return false; fullName = typeFullName + "." + name; return 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt640() { var test = new VectorGetAndWithElement__GetAndWithElementUInt640(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt640 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { UInt64 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt64 insertedValue = TestLibrary.Generator.GetUInt64(); try { Vector256<UInt64> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt64)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt64 insertedValue = TestLibrary.Generator.GetUInt64(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt64>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "") { UInt64[] resultElements = new UInt64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Hard coded images referenced from C++ code //------------------------------------------------------------------------------ // editor/SelectHandle.png // editor/DefaultHandle.png // editor/LockedHandle.png //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Mission Editor //------------------------------------------------------------------------------ function Editor::create() { // Not much to do here, build it and they will come... // Only one thing... the editor is a gui control which // expect the Canvas to exist, so it must be constructed // before the editor. new EditManager(Editor) { profile = "GuiContentProfile"; horizSizing = "right"; vertSizing = "top"; position = "0 0"; extent = "640 480"; minExtent = "8 8"; visible = "1"; setFirstResponder = "0"; modal = "1"; helpTag = "0"; open = false; }; } function Editor::getUndoManager(%this) { if ( !isObject( %this.undoManager ) ) { /// This is the global undo manager used by all /// of the mission editor sub-editors. %this.undoManager = new UndoManager( EUndoManager ) { numLevels = 200; }; } return %this.undoManager; } function Editor::setUndoManager(%this, %undoMgr) { %this.undoManager = %undoMgr; } function Editor::onAdd(%this) { // Ignore Replicated fxStatic Instances. EWorldEditor.ignoreObjClass("fxShapeReplicatedStatic"); } function Editor::checkActiveLoadDone() { if(isObject(EditorGui) && EditorGui.loadingMission) { Canvas.setContent(EditorGui); EditorGui.loadingMission = false; return true; } return false; } //------------------------------------------------------------------------------ function toggleEditor(%make) { if (%make) { %timerId = startPrecisionTimer(); if( GuiEditorIsActive() ) toggleGuiEditor(1); if( !$missionRunning ) { // Flag saying, when level is chosen, launch it with the editor open. ChooseLevelDlg.launchInEditor = true; Canvas.pushDialog( ChooseLevelDlg ); } else { pushInstantGroup(); if ( !isObject( Editor ) ) { Editor::create(); MissionCleanup.add( Editor ); MissionCleanup.add( Editor.getUndoManager() ); } if( EditorIsActive() ) { if (theLevelInfo.type $= "DemoScene") { commandToServer('dropPlayerAtCamera'); Editor.close("SceneGui"); } else { Editor.close("PlayGui"); } } else { canvas.pushDialog( EditorLoadingGui ); canvas.repaint(); Editor.open(); // Cancel the scheduled event to prevent // the level from cycling after it's duration // has elapsed. cancel($Game::Schedule); if (theLevelInfo.type $= "DemoScene") commandToServer('dropCameraAtPlayer', true); canvas.popDialog(EditorLoadingGui); } popInstantGroup(); } %elapsed = stopPrecisionTimer( %timerId ); warn( "Time spent in toggleEditor() : " @ %elapsed / 1000.0 @ " s" ); } } //------------------------------------------------------------------------------ // The editor action maps are defined in editor.bind.cs GlobalActionMap.bind(keyboard, "f11", toggleEditor); // The scenario: // The editor is open and the user closes the level by any way other than // the file menu ( exit level ), eg. typing disconnect() in the console. // // The problem: // Editor::close() is not called in this scenario which means onEditorDisable // is not called on objects which hook into it and also gEditingMission will no // longer be valid. // // The solution: // Override the stock disconnect() function which is in game scripts from here // in tools so we avoid putting our code in there. // // Disclaimer: // If you think of a better way to do this feel free. The thing which could // be dangerous about this is that no one will ever realize this code overriding // a fairly standard and core game script from a somewhat random location. // If it 'did' have unforscene sideeffects who would ever find it? package EditorDisconnectOverride { function disconnect() { if ( isObject( Editor ) && Editor.isEditorEnabled() ) { if (isObject( MainMenuGui )) Editor.close("MainMenuGui"); } Parent::disconnect(); } }; activatePackage( EditorDisconnectOverride );
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) Franklin Wise // (C) 2003 Martin Willemoes Hansen // 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 Xunit; namespace System.Data.Tests { public class ForeignKeyConstraintTest { private DataSet _ds; //NOTE: fk constraints only work when the table is part of a DataSet public ForeignKeyConstraintTest() { _ds = new DataSet(); //Setup DataTable DataTable table; table = new DataTable("TestTable"); table.Columns.Add("Col1", typeof(int)); table.Columns.Add("Col2", typeof(int)); table.Columns.Add("Col3", typeof(int)); _ds.Tables.Add(table); table = new DataTable("TestTable2"); table.Columns.Add("Col1", typeof(int)); table.Columns.Add("Col2", typeof(int)); table.Columns.Add("Col3", typeof(int)); _ds.Tables.Add(table); } // Tests ctor (string, DataColumn, DataColumn) [Fact] public void Ctor1() { DataTable Table = _ds.Tables[0]; Assert.Equal(0, Table.Constraints.Count); Table = _ds.Tables[1]; Assert.Equal(0, Table.Constraints.Count); // ctor (string, DataColumn, DataColumn ForeignKeyConstraint Constraint = new ForeignKeyConstraint("test", _ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]); Table = _ds.Tables[1]; Table.Constraints.Add(Constraint); Assert.Equal(1, Table.Constraints.Count); Assert.Equal("test", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType()); Table = _ds.Tables[0]; Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType()); } // Tests ctor (DataColumn, DataColumn) [Fact] public void Ctor2() { DataTable Table = _ds.Tables[0]; Assert.Equal(0, Table.Constraints.Count); Table = _ds.Tables[1]; Assert.Equal(0, Table.Constraints.Count); // ctor (string, DataColumn, DataColumn ForeignKeyConstraint Constraint = new ForeignKeyConstraint(_ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]); Table = _ds.Tables[1]; Table.Constraints.Add(Constraint); Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType()); Table = _ds.Tables[0]; Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType()); } // Test ctor (DataColumn [], DataColumn []) [Fact] public void Ctor3() { DataTable Table = _ds.Tables[0]; Assert.Equal(0, Table.Constraints.Count); Table = _ds.Tables[1]; Assert.Equal(0, Table.Constraints.Count); DataColumn[] Cols1 = new DataColumn[2]; Cols1[0] = _ds.Tables[0].Columns[1]; Cols1[1] = _ds.Tables[0].Columns[2]; DataColumn[] Cols2 = new DataColumn[2]; Cols2[0] = _ds.Tables[1].Columns[0]; Cols2[1] = _ds.Tables[1].Columns[1]; ForeignKeyConstraint Constraint = new ForeignKeyConstraint(Cols1, Cols2); Table = _ds.Tables[1]; Table.Constraints.Add(Constraint); Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType()); Table = _ds.Tables[0]; Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType()); } // Tests ctor (string, DataColumn [], DataColumn []) [Fact] public void Ctor4() { DataTable Table = _ds.Tables[0]; Assert.Equal(0, Table.Constraints.Count); Table = _ds.Tables[1]; Assert.Equal(0, Table.Constraints.Count); DataColumn[] Cols1 = new DataColumn[2]; Cols1[0] = _ds.Tables[0].Columns[1]; Cols1[1] = _ds.Tables[0].Columns[2]; DataColumn[] Cols2 = new DataColumn[2]; Cols2[0] = _ds.Tables[1].Columns[0]; Cols2[1] = _ds.Tables[1].Columns[1]; ForeignKeyConstraint Constraint = new ForeignKeyConstraint("Test", Cols1, Cols2); Table = _ds.Tables[1]; Table.Constraints.Add(Constraint); Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Test", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType()); Table = _ds.Tables[0]; Assert.Equal(1, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType()); } [Fact] public void TestCtor5() { DataTable table1 = new DataTable("Table1"); DataTable table2 = new DataTable("Table2"); DataSet dataSet = new DataSet(); dataSet.Tables.Add(table1); dataSet.Tables.Add(table2); DataColumn column1 = new DataColumn("col1"); DataColumn column2 = new DataColumn("col2"); DataColumn column3 = new DataColumn("col3"); table1.Columns.Add(column1); table1.Columns.Add(column2); table1.Columns.Add(column3); DataColumn column4 = new DataColumn("col4"); DataColumn column5 = new DataColumn("col5"); DataColumn column6 = new DataColumn("col6"); table2.Columns.Add(column4); table2.Columns.Add(column5); table2.Columns.Add(column6); string[] parentColumnNames = { "col1", "col2", "col3" }; string[] childColumnNames = { "col4", "col5", "col6" }; string parentTableName = "table1"; // Create a ForeingKeyConstraint Object using the constructor // ForeignKeyConstraint (string, string, string[], string[], AcceptRejectRule, Rule, Rule); ForeignKeyConstraint fkc = new ForeignKeyConstraint("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade); // Assert that the Constraint object does not belong to any table yet try { DataTable tmp = fkc.Table; Assert.False(true); } catch (NullReferenceException) { // actually .NET throws this (bug) } catch (InvalidOperationException) { } Constraint[] constraints = new Constraint[3]; constraints[0] = new UniqueConstraint(column1); constraints[1] = new UniqueConstraint(column2); constraints[2] = fkc; // Try to add the constraint to ConstraintCollection of the DataTable through Add() try { table2.Constraints.Add(fkc); throw new ApplicationException("An Exception was expected"); } // LAMESPEC : spec says InvalidConstraintException but throws this catch (NullReferenceException) { } #if false // FIXME: Here this test crashes under MS.NET. // OK - So AddRange() is the only way! table2.Constraints.AddRange (constraints); // After AddRange(), Check the properties of ForeignKeyConstraint object Assert.True(fkc.RelatedColumns [0].ColumnName.Equals ("col1")); Assert.True(fkc.RelatedColumns [1].ColumnName.Equals ("col2")); Assert.True(fkc.RelatedColumns [2].ColumnName.Equals ("col3")); Assert.True(fkc.Columns [0].ColumnName.Equals ("col4")); Assert.True(fkc.Columns [1].ColumnName.Equals ("col5")); Assert.True(fkc.Columns [2].ColumnName.Equals ("col6")); #endif // Try to add columns with names which do not exist in the table parentColumnNames[2] = "noColumn"; ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade); constraints[0] = new UniqueConstraint(column1); constraints[1] = new UniqueConstraint(column2); constraints[2] = foreignKeyConstraint; try { table2.Constraints.AddRange(constraints); throw new ApplicationException("An Exception was expected"); } catch (ArgumentException e) { } catch (InvalidConstraintException e) { // Could not test on ms.net, as ms.net does not reach here so far. } #if false // FIXME: Here this test crashes under MS.NET. // Check whether the child table really contains the foreign key constraint named "hello world" Assert.True(table2.Constraints.Contains ("hello world")); #endif } // If Childs and parents are in same table [Fact] public void KeyBetweenColumns() { DataTable Table = _ds.Tables[0]; Assert.Equal(0, Table.Constraints.Count); Table = _ds.Tables[1]; Assert.Equal(0, Table.Constraints.Count); ForeignKeyConstraint Constraint = new ForeignKeyConstraint("Test", _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[2]); Table = _ds.Tables[0]; Table.Constraints.Add(Constraint); Assert.Equal(2, Table.Constraints.Count); Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName); Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType()); Assert.Equal("Test", Table.Constraints[1].ConstraintName); Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[1].GetType()); } [Fact] public void CtorExceptions() { ForeignKeyConstraint fkc; DataTable localTable = new DataTable(); localTable.Columns.Add("Col1", typeof(int)); localTable.Columns.Add("Col2", typeof(bool)); //Null Assert.Throws<NullReferenceException>(() => { fkc = new ForeignKeyConstraint(null, (DataColumn)null); }); //zero length collection AssertExtensions.Throws<ArgumentException>(null, () => { fkc = new ForeignKeyConstraint(new DataColumn[] { }, new DataColumn[] { }); }); //different datasets Assert.Throws<InvalidOperationException>(() => { fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[0]); }); Assert.Throws<InvalidOperationException>(() => { fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[1]); }); // Cannot create a Key from Columns that belong to // different tables. Assert.Throws<InvalidConstraintException>(() => { fkc = new ForeignKeyConstraint(new DataColumn[] { _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[1] }, new DataColumn[] { localTable.Columns[1], _ds.Tables[1].Columns[0] }); }); } [Fact] public void CtorExceptions2() { DataColumn col = new DataColumn("MyCol1", typeof(int)); ForeignKeyConstraint fkc; //Columns must belong to a Table AssertExtensions.Throws<ArgumentException>(null, () => { fkc = new ForeignKeyConstraint(col, _ds.Tables[0].Columns[0]); }); //Columns must belong to the same table //InvalidConstraintException DataColumn[] difTable = new DataColumn[] {_ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]}; Assert.Throws<InvalidConstraintException>(() => { fkc = new ForeignKeyConstraint(difTable, new DataColumn[] { _ds.Tables[0].Columns[1], _ds.Tables[0].Columns[0]}); }); //parent columns and child columns should be the same length //ArgumentException DataColumn[] twoCol = new DataColumn[] { _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[1] }; AssertExtensions.Throws<ArgumentException>(null, () => { fkc = new ForeignKeyConstraint(twoCol, new DataColumn[] { _ds.Tables[0].Columns[0] }); }); //InvalidOperation: Parent and child are the same column. Assert.Throws<InvalidOperationException>(() => { fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], _ds.Tables[0].Columns[0]); }); } [Fact] public void EqualsAndHashCode() { DataTable tbl = _ds.Tables[0]; DataTable tbl2 = _ds.Tables[1]; ForeignKeyConstraint fkc = new ForeignKeyConstraint( new DataColumn[] { tbl.Columns[0], tbl.Columns[1] }, new DataColumn[] { tbl2.Columns[0], tbl2.Columns[1] }); ForeignKeyConstraint fkc2 = new ForeignKeyConstraint( new DataColumn[] { tbl.Columns[0], tbl.Columns[1] }, new DataColumn[] { tbl2.Columns[0], tbl2.Columns[1] }); ForeignKeyConstraint fkcDiff = new ForeignKeyConstraint(tbl.Columns[1], tbl.Columns[2]); Assert.True(fkc.Equals(fkc2)); Assert.True(fkc2.Equals(fkc)); Assert.True(fkc.Equals(fkc)); Assert.True(fkc.Equals(fkcDiff) == false); //Assert.True( "Hash Code Assert.True.Failed. 1"); Assert.True(fkc.GetHashCode() != fkcDiff.GetHashCode()); } [Fact] public void ViolationTest() { AssertExtensions.Throws<ArgumentException>(null, () => { DataTable parent = _ds.Tables[0]; DataTable child = _ds.Tables[1]; parent.Rows.Add(new object[] { 1, 1, 1 }); child.Rows.Add(new object[] { 2, 2, 2 }); try { child.Constraints.Add(new ForeignKeyConstraint(parent.Columns[0], child.Columns[0]) ); } finally { // clear the rows for further testing _ds.Clear(); } }); } [Fact] public void NoViolationTest() { DataTable parent = _ds.Tables[0]; DataTable child = _ds.Tables[1]; parent.Rows.Add(new object[] { 1, 1, 1 }); child.Rows.Add(new object[] { 2, 2, 2 }); try { _ds.EnforceConstraints = false; child.Constraints.Add(new ForeignKeyConstraint(parent.Columns[0], child.Columns[0]) ); } finally { // clear the rows for further testing _ds.Clear(); _ds.EnforceConstraints = true; } } [Fact] public void ModifyParentKeyBeforeAcceptChanges() { DataSet ds1 = new DataSet(); DataTable t1 = ds1.Tables.Add("t1"); DataTable t2 = ds1.Tables.Add("t2"); t1.Columns.Add("col1", typeof(int)); t2.Columns.Add("col2", typeof(int)); ds1.Relations.Add("fk", t1.Columns[0], t2.Columns[0]); t1.Rows.Add(new object[] { 10 }); t2.Rows.Add(new object[] { 10 }); t1.Rows[0][0] = 20; Assert.True((int)t2.Rows[0][0] == 20); } [Fact] // https://bugzilla.novell.com/show_bug.cgi?id=650402 public void ForeignKey_650402() { DataSet data = new DataSet(); DataTable parent = new DataTable("parent"); DataColumn pk = parent.Columns.Add("PK"); DataTable child = new DataTable("child"); DataColumn fk = child.Columns.Add("FK"); data.Tables.Add(parent); data.Tables.Add(child); data.Relations.Add(pk, fk); parent.Rows.Add("value"); child.Rows.Add("value"); data.AcceptChanges(); child.Rows[0].Delete(); parent.Rows[0][0] = "value2"; data.EnforceConstraints = false; data.EnforceConstraints = true; } } }
using SemanticReleaseNotesParser.Core; using System.IO; using System.Linq; using System.Text; using Xunit; namespace SemanticReleaseNotesParser.Tests { public class ArgumentsTest { [Fact] public void WriteHelp_All() { // arrange var arguments = Arguments.ParseArguments(Enumerable.Empty<string>()); var output = new StringBuilder(); var writer = new StringWriter(output); // act arguments.WriteOptionDescriptions(writer); // assert Assert.Contains("-r, --releasenotes=VALUE", output.ToString()); Assert.Contains("-o, --outputfile=VALUE", output.ToString()); Assert.Contains("-t, --outputtype=VALUE", output.ToString()); Assert.Contains("--template=VALUE", output.ToString()); Assert.Contains("--debug", output.ToString()); Assert.Contains("-h, -?, --help", output.ToString()); Assert.Contains("-f, --outputformat=VALUE", output.ToString()); Assert.Contains("-g, --groupby=VALUE", output.ToString()); Assert.Contains("--pluralizecategoriestitle", output.ToString()); Assert.Contains("--includestyle[=VALUE]", output.ToString()); } [Fact] public void ParseArguments_NoArgument() { // act var arguments = Arguments.ParseArguments(new string[0]); // assert Assert.False(arguments.Debug); Assert.False(arguments.Help); Assert.Equal(OutputFormat.Html, arguments.OutputFormat); Assert.Equal(OutputType.File, arguments.OutputType); Assert.Equal("ReleaseNotes.md", arguments.ReleaseNotesPath); Assert.Equal("ReleaseNotes.html", arguments.ResultFilePath); Assert.Null(arguments.TemplatePath); Assert.False(arguments.PluralizeCategoriesTitle); Assert.Null(arguments.IncludeStyle); } [Fact] public void ParseArguments_Debug() { // act var arguments = Arguments.ParseArguments(new[] { "--debug" }); // assert Assert.True(arguments.Debug); } [Fact] public void ParseArguments_Help_h() { // act var arguments = Arguments.ParseArguments(new[] { "-h" }); // assert Assert.True(arguments.Help); } [Fact] public void ParseArguments_Help_QuestionMark() { // act var arguments = Arguments.ParseArguments(new[] { "-?" }); // assert Assert.True(arguments.Help); } [Fact] public void ParseArguments_Help_Help() { // act var arguments = Arguments.ParseArguments(new[] { "--help" }); // assert Assert.True(arguments.Help); } [Fact] public void ParseArguments_ReleaseNotesPath_r() { // act var arguments = Arguments.ParseArguments(new[] { "-r=myReleases.md" }); // assert Assert.Equal("myReleases.md", arguments.ReleaseNotesPath); } [Fact] public void ParseArguments_ReleaseNotesPath_releasenotes() { // act var arguments = Arguments.ParseArguments(new[] { "--releasenotes=myReleases.md" }); // assert Assert.Equal("myReleases.md", arguments.ReleaseNotesPath); } [Fact] public void ParseArguments_ResultFilePath_o() { // act var arguments = Arguments.ParseArguments(new[] { "-o=myReleases.html" }); // assert Assert.Equal("myReleases.html", arguments.ResultFilePath); } [Fact] public void ParseArguments_ResultFilePath_outputfile() { // act var arguments = Arguments.ParseArguments(new[] { "--outputfile=myReleases.html" }); // assert Assert.Equal("myReleases.html", arguments.ResultFilePath); } [Fact] public void ParseArguments_OutputType_t() { // act var arguments = Arguments.ParseArguments(new[] { "-t=environment" }); // assert Assert.Equal(OutputType.Environment, arguments.OutputType); } [Fact] public void ParseArguments_OutputType_outputfile() { // act var arguments = Arguments.ParseArguments(new[] { "--outputtype=environment" }); // assert Assert.Equal(OutputType.Environment, arguments.OutputType); } [Fact] public void ParseArguments_OutputType_t_fileandenvironment() { // act var arguments = Arguments.ParseArguments(new[] { "-t=fileandenvironment" }); // assert Assert.Equal(OutputType.FileAndEnvironment, arguments.OutputType); } [Fact] public void ParseArguments_OutputType_outputfile_fileandenvironment() { // act var arguments = Arguments.ParseArguments(new[] { "--outputtype=fileandenvironment" }); // assert Assert.Equal(OutputType.FileAndEnvironment, arguments.OutputType); } [Fact] public void ParseArguments_OutputFormat_f() { // act var arguments = Arguments.ParseArguments(new[] { "-f=markdown" }); // assert Assert.Equal(OutputFormat.Markdown, arguments.OutputFormat); Assert.Equal("ReleaseNotes.md", arguments.ResultFilePath); } [Fact] public void ParseArguments_OutputFormat_outputformat() { // act var arguments = Arguments.ParseArguments(new[] { "--outputformat=markdown" }); // assert Assert.Equal(OutputFormat.Markdown, arguments.OutputFormat); Assert.Equal("ReleaseNotes.md", arguments.ResultFilePath); } [Fact] public void ParseArguments_Template() { // act var arguments = Arguments.ParseArguments(new[] { "--template=template.liquid" }); // assert Assert.Equal("template.liquid", arguments.TemplatePath); } [Fact] public void ParseArguments_FirstAdditionalArgument_IsReleaseNotesPath() { // act var arguments = Arguments.ParseArguments(new[] { "myReleases.md" }); // assert Assert.Equal("myReleases.md", arguments.ReleaseNotesPath); } [Fact] public void ParseArguments_GroupBy_g() { // act var arguments = Arguments.ParseArguments(new[] { "-g=Categories" }); // assert Assert.Equal(GroupBy.Categories, arguments.GroupBy); } [Fact] public void ParseArguments_GroupBy_groupby() { // act var arguments = Arguments.ParseArguments(new[] { "--groupby=Categories" }); // assert Assert.Equal(GroupBy.Categories, arguments.GroupBy); } [Fact] public void ParseArguments_PluralizeCategoriesTitle() { // act var arguments = Arguments.ParseArguments(new[] { "--pluralizecategoriestitle" }); // assert Assert.True(arguments.PluralizeCategoriesTitle); } [Fact] public void ParseArguments_IncludeStyle() { // act var arguments = Arguments.ParseArguments(new[] { "--includestyle" }); // assert Assert.Equal(string.Empty, arguments.IncludeStyle); } [Fact] public void ParseArguments_IncludeStyle_WithValue() { // act var arguments = Arguments.ParseArguments(new[] { "--includestyle=my_style" }); // assert Assert.Equal("my_style", arguments.IncludeStyle); } } }
using System; using System.Collections; /// <summary> /// System.Array.Sort(System.Array,System.Array,System.Collections.IComparer) /// </summary> public class ArrayIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; int[] i1 = new int[6] { 24, 30, 28, 26, 32, 23 }; string[] s2 = new string[6]{"Allin", "Jack", "Mary", "Mike", "Peter", "Tom"}; int[] i2 = new int[6] { 23, 24, 30, 28, 26, 32 }; Array.Sort(s1, i1, null); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("002", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer "); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; i2[i] = value; } IComparer a1 = new A(); Array.Sort(i1, i2, a1); for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("004", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer "); try { char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; char[] c2 = new char[10] { 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a' }; char[] d1 = new char[10]; char[] d2 = new char[10]; c1.CopyTo(d2, 0); c2.CopyTo(d1, 0); IComparer b = new B(); Array.Sort(c1, c2, b); for (int i = 0; i < 10; i++) { if (c1[i] != d1[i]) { TestLibrary.TestFramework.LogError("006", "The result is not the value as expected"); retVal = false; } if (c2[i] != d2[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort a customized array "); try { C c1 = new C(100); C c2 = new C(16); C c3 = new C(11); C c4 = new C(9); C c5 = new C(7); C c6 = new C(2); int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 }; int[] i2 = new int[6] { 6, 5, 4, 3, 2, 1 }; Array myarray = Array.CreateInstance(typeof(C), 6); myarray.SetValue(c1, 0); myarray.SetValue(c2, 1); myarray.SetValue(c3, 2); myarray.SetValue(c4, 3); myarray.SetValue(c5, 4); myarray.SetValue(c6, 5); Array.Sort(myarray, i1, (IComparer)myarray.GetValue(0)); for (int i = 0; i < 6; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The first argument is null reference "); try { string[] s1 = null; int[] i1 = { 1, 2, 3, 4, 5 }; Array.Sort(s1, i1, null); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The keys array is not one dimension "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; int[] i2 = { 1, 2, 3, 4, 5 }; Array.Sort(i1, i2, null); TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The items array is not one dimension "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; int[] i2 = { 1, 2, 3, 4, 5 }; Array.Sort(i2, i1, null); TestLibrary.TestFramework.LogError("105", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: The length of items array is not equal to the length of keys array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; int[] i1 = new int[5] { 24, 30, 28, 26, 32 }; Array.Sort(s1, i1, null); TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: The Icomparer is null and keys array does not implement the IComparer interface "); try { D d1 = new D(); D d2 = new D(); D d3 = new D(); D d4 = new D(); int[] i2 = { 1, 2, 3, 4 }; D[] d = new D[4] { d1, d2, d3, d4 }; Array.Sort(d, i2, null); TestLibrary.TestFramework.LogError("109", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf1 test = new ArrayIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class A : IComparer { #region IComparer Members public int Compare(object x, object y) { return ((int)x).CompareTo((int)y); } #endregion } class B : IComparer { #region IComparer Members public int Compare(object x, object y) { if (((char)x).CompareTo((char)y) > 0) return -1; else { if (x == y) { return 0; } else { return 1; } } } #endregion } class C : IComparer { protected int c_value; public C(int a) { this.c_value = a; } #region IComparer Members public int Compare(object x, object y) { return (x as C).c_value.CompareTo((y as C).c_value); } #endregion } class D : IComparer { #region IComparer Members public int Compare(object x, object y) { return 0; } #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.Runtime.Intrinsics.X86; using static System.Runtime.Intrinsics.X86.Avx; using static System.Runtime.Intrinsics.X86.Avx2; using static System.Runtime.Intrinsics.X86.Sse2; using System.Runtime.Intrinsics; using System; using ColorPacket256 = VectorPacket256; internal class Packet256Tracer { public int Width { get; } public int Height { get; } private static readonly int MaxDepth = 5; private static readonly Vector256<float> SevenToZero = Vector256.Create(0f, 1f, 2f, 3f, 4f, 5f, 6f, 7f); public Packet256Tracer(int width, int height) { if ((width % VectorPacket256.Packet256Size) != 0) { width += VectorPacket256.Packet256Size - (width % VectorPacket256.Packet256Size); } Width = width; Height = height; } internal unsafe void RenderVectorized(Scene scene, int* rgb) { Camera camera = scene.Camera; // Iterate y then x in order to preserve cache locality. for (int y = 0; y < Height; y++) { int stride = y * Width; for (int x = 0; x < Width; x += VectorPacket256.Packet256Size) { float fx = x; Vector256<float> Xs = Add(Vector256.Create(fx), SevenToZero); VectorPacket256 dirs = GetPoints(Xs, Vector256.Create((float)(y)), camera); var rayPacket256 = new RayPacket256(camera.Pos, dirs); var SoAcolors = TraceRay(rayPacket256, scene, depth: 0); var AoS = SoAcolors.Transpose(); var intAoS = AoS.ConvertToIntRGB(); int* output = &rgb[(x + stride) * 3]; // Each pixel has 3 fields (RGB) { Store(output, intAoS.Rs); Store(output + 8, intAoS.Gs); Store(output + 16, intAoS.Bs); } } } } private ColorPacket256 TraceRay(RayPacket256 rayPacket256, Scene scene, int depth) { var isect = MinIntersections(rayPacket256, scene); if (isect.AllNullIntersections()) { return ColorPacket256Helper.BackgroundColor; } var color = Shade(isect, rayPacket256, scene, depth); var isNull = Compare(isect.Distances, Intersections.NullDistance, FloatComparisonMode.OrderedEqualNonSignaling); var backgroundColor = ColorPacket256Helper.BackgroundColor.Xs; return new ColorPacket256(BlendVariable(color.Xs, backgroundColor, isNull), BlendVariable(color.Ys, backgroundColor, isNull), BlendVariable(color.Zs, backgroundColor, isNull)); } private Vector256<float> TestRay(RayPacket256 rayPacket256, Scene scene) { var isect = MinIntersections(rayPacket256, scene); if (isect.AllNullIntersections()) { return Vector256<float>.Zero; } var isNull = Compare(isect.Distances, Intersections.NullDistance, FloatComparisonMode.OrderedEqualNonSignaling); return BlendVariable(isect.Distances, Vector256<float>.Zero, isNull); } private Intersections MinIntersections(RayPacket256 rayPacket256, Scene scene) { Intersections mins = new Intersections(Intersections.NullDistance, Intersections.NullIndex); for (int i = 0; i < scene.Things.Length; i++) { Vector256<float> distance = scene.Things[i].Intersect(rayPacket256); if (!Intersections.AllNullIntersections(distance)) { var notNullMask = Compare(distance, Intersections.NullDistance, FloatComparisonMode.OrderedNotEqualNonSignaling); var nullMinMask = Compare(mins.Distances, Intersections.NullDistance, FloatComparisonMode.OrderedEqualNonSignaling); var lessMinMask = Compare(mins.Distances, distance, FloatComparisonMode.OrderedGreaterThanNonSignaling); var minMask = And(notNullMask, Or(nullMinMask, lessMinMask)); var minDis = BlendVariable(mins.Distances, distance, minMask); var minIndices = BlendVariable(mins.ThingIndices.AsSingle(), Vector256.Create(i).AsSingle(), minMask).AsInt32(); mins.Distances = minDis; mins.ThingIndices = minIndices; } } return mins; } private ColorPacket256 Shade(Intersections isect, RayPacket256 rays, Scene scene, int depth) { var ds = rays.Dirs; var pos = isect.Distances * ds + rays.Starts; var normals = scene.Normals(isect.ThingIndices, pos); var reflectDirs = ds - (Multiply(VectorPacket256.DotProduct(normals, ds), Vector256.Create(2.0f)) * normals); var colors = GetNaturalColor(isect.ThingIndices, pos, normals, reflectDirs, scene); if (depth >= MaxDepth) { return colors + new ColorPacket256(.5f, .5f, .5f); } return colors + GetReflectionColor(isect.ThingIndices, pos + (Vector256.Create(0.001f) * reflectDirs), normals, reflectDirs, scene, depth); } private ColorPacket256 GetNaturalColor(Vector256<int> things, VectorPacket256 pos, VectorPacket256 norms, VectorPacket256 rds, Scene scene) { var colors = ColorPacket256Helper.DefaultColor; for (int i = 0; i < scene.Lights.Length; i++) { var lights = scene.Lights[i]; var zero = Vector256<float>.Zero; var colorPacket = lights.Colors; var ldis = lights.Positions - pos; var livec = ldis.Normalize(); var neatIsectDis = TestRay(new RayPacket256(pos, livec), scene); // is in shadow? var mask1 = Compare(neatIsectDis, ldis.Lengths, FloatComparisonMode.OrderedLessThanOrEqualNonSignaling); var mask2 = Compare(neatIsectDis, zero, FloatComparisonMode.OrderedNotEqualNonSignaling); var isInShadow = And(mask1, mask2); Vector256<float> illum = VectorPacket256.DotProduct(livec, norms); Vector256<float> illumGraterThanZero = Compare(illum, zero, FloatComparisonMode.OrderedGreaterThanNonSignaling); var tmpColor1 = illum * colorPacket; var defaultRGB = zero; Vector256<float> lcolorR = BlendVariable(defaultRGB, tmpColor1.Xs, illumGraterThanZero); Vector256<float> lcolorG = BlendVariable(defaultRGB, tmpColor1.Ys, illumGraterThanZero); Vector256<float> lcolorB = BlendVariable(defaultRGB, tmpColor1.Zs, illumGraterThanZero); ColorPacket256 lcolor = new ColorPacket256(lcolorR, lcolorG, lcolorB); Vector256<float> specular = VectorPacket256.DotProduct(livec, rds.Normalize()); Vector256<float> specularGraterThanZero = Compare(specular, zero, FloatComparisonMode.OrderedGreaterThanNonSignaling); var difColor = new ColorPacket256(1, 1, 1); var splColor = new ColorPacket256(1, 1, 1); var roughness = Vector256.Create(1.0f); for (int j = 0; j < scene.Things.Length; j++) { Vector256<float> thingMask = CompareEqual(things, Vector256.Create(j)).AsSingle(); Vector256<float> rgh = Vector256.Create(scene.Things[j].Surface.Roughness); var dif = scene.Things[j].Surface.Diffuse(pos); var spl = scene.Things[j].Surface.Specular; roughness = BlendVariable(roughness, rgh, thingMask); difColor.Xs = BlendVariable(difColor.Xs, dif.Xs, thingMask); difColor.Ys = BlendVariable(difColor.Ys, dif.Ys, thingMask); difColor.Zs = BlendVariable(difColor.Zs, dif.Zs, thingMask); splColor.Xs = BlendVariable(splColor.Xs, spl.Xs, thingMask); splColor.Ys = BlendVariable(splColor.Ys, spl.Ys, thingMask); splColor.Zs = BlendVariable(splColor.Zs, spl.Zs, thingMask); } var tmpColor2 = VectorMath.Pow(specular, roughness) * colorPacket; Vector256<float> scolorR = BlendVariable(defaultRGB, tmpColor2.Xs, specularGraterThanZero); Vector256<float> scolorG = BlendVariable(defaultRGB, tmpColor2.Ys, specularGraterThanZero); Vector256<float> scolorB = BlendVariable(defaultRGB, tmpColor2.Zs, specularGraterThanZero); ColorPacket256 scolor = new ColorPacket256(scolorR, scolorG, scolorB); var oldColor = colors; colors = colors + ColorPacket256Helper.Times(difColor, lcolor) + ColorPacket256Helper.Times(splColor, scolor); colors = new ColorPacket256(BlendVariable(colors.Xs, oldColor.Xs, isInShadow), BlendVariable(colors.Ys, oldColor.Ys, isInShadow), BlendVariable(colors.Zs, oldColor.Zs, isInShadow)); } return colors; } private ColorPacket256 GetReflectionColor(Vector256<int> things, VectorPacket256 pos, VectorPacket256 norms, VectorPacket256 rds, Scene scene, int depth) { return scene.Reflect(things, pos) * TraceRay(new RayPacket256(pos, rds), scene, depth + 1); } private readonly static Vector256<float> ConstTwo = Vector256.Create(2.0f); private VectorPacket256 GetPoints(Vector256<float> x, Vector256<float> y, Camera camera) { Vector256<float> widthVector = Vector256.Create((float)(Width)); Vector256<float> heightVector = Vector256.Create((float)(Height)); var widthRate1 = Divide(widthVector, ConstTwo); var widthRate2 = Multiply(widthVector, ConstTwo); var heightRate1 = Divide(heightVector, ConstTwo); var heightRate2 = Multiply(heightVector, ConstTwo); var recenteredX = Divide(Subtract(x, widthRate1), widthRate2); var recenteredY = Subtract(Vector256<float>.Zero, Divide(Subtract(y, heightRate1), heightRate2)); var result = camera.Forward + (recenteredX * camera.Right) + (recenteredY * camera.Up); return result.Normalize(); } internal readonly Scene DefaultScene = CreateDefaultScene(); private static Scene CreateDefaultScene() { ObjectPacket256[] things = { new SpherePacket256(new VectorPacket256(-0.5f, 1f, 1.5f), Vector256.Create(0.5f), Surfaces.MatteShiny), new SpherePacket256(new VectorPacket256(0f, 1f, -0.25f), Vector256.Create(1f), Surfaces.Shiny), new PlanePacket256((new VectorPacket256(0, 1, 0)), Vector256.Create(0f), Surfaces.CheckerBoard) }; LightPacket256[] lights = { new LightPacket256(new Vector(-2f,2.5f,0f),new Color(.5f,.45f,.41f)), new LightPacket256(new Vector(2,4.5f,2), new Color(.99f,.95f,.8f)) }; Camera camera = Camera.Create(new VectorPacket256(2.75f, 2f, 3.75f), new VectorPacket256(-0.6f, .5f, 0f)); return new Scene(things, lights, camera); } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; namespace Encog.ML.Prg.ExpValue { /// <summary> /// Simple utility class that performs some basic operations on ExpressionValue /// objects. /// </summary> public static class EvaluateExpr { /// <summary> /// Perform an add on two expression values. a+b /// </summary> /// <param name="a">The first argument.</param> /// <param name="b">The second argument.</param> /// <returns> /// The result of adding two numbers. Concat for strings. If one is a /// string, the other is converted to string. If no string, then if /// one is float, both are converted to int. /// </returns> public static ExpressionValue Add(ExpressionValue a, ExpressionValue b) { if (a.IsString || b.IsString) { return new ExpressionValue(a.ToStringValue() + b.ToStringValue()); } if (a.IsInt && b.IsInt) { return new ExpressionValue(a.ToIntValue() + b.ToIntValue()); } return new ExpressionValue(a.ToFloatValue() + b.ToFloatValue()); } /// <summary> /// Perform a division on two expression values. a/b An Encog division by /// zero exception can occur. If one param is a float, the other is converted /// to a float. /// </summary> /// <param name="a">The first argument, must be numeric.</param> /// <param name="b">The second argument, must be numeric.</param> /// <returns> The result of the operation.</returns> public static ExpressionValue Div(ExpressionValue a, ExpressionValue b) { if (a.IsInt && b.IsInt) { long i = b.ToIntValue(); if (i == 0) { throw new DivisionByZeroError(); } return new ExpressionValue(a.ToIntValue()/i); } double denom = b.ToFloatValue(); if (Math.Abs(denom) < EncogFramework.DefaultDoubleEqual) { throw new DivisionByZeroError(); } return new ExpressionValue(a.ToFloatValue()/denom); } /// <summary> /// Perform an equal on two expressions. Booleans, ints and strings must /// exactly equal. Floating point must be equal within the default Encog /// tolerance. /// </summary> /// <param name="a">The first parameter to check.</param> /// <param name="b">The second parameter to check.</param> /// <returns>True/false.</returns> public static ExpressionValue Equ(ExpressionValue a, ExpressionValue b) { if (a.ExprType == EPLValueType.BooleanType) { return new ExpressionValue(a.ToBooleanValue() == b.ToBooleanValue()); } if (a.ExprType == EPLValueType.EnumType) { return new ExpressionValue(a.ToIntValue() == b.ToIntValue() && a.EnumType == b.EnumType); } if (a.ExprType == EPLValueType.StringType) { return new ExpressionValue(a.ToStringValue().Equals( b.ToStringValue())); } var diff = Math.Abs(a.ToFloatValue() - b.ToFloatValue()); return new ExpressionValue(diff < EncogFramework.DefaultDoubleEqual); } /// <summary> /// Perform a multiply on two expression values. a*b If one param is a float, /// the other is converted to a float. /// </summary> /// <param name="a">The first argument, must be numeric.</param> /// <param name="b">The second argument, must be numeric.</param> /// <returns>The result of the operation.</returns> public static ExpressionValue Mul(ExpressionValue a, ExpressionValue b) { if (a.IsInt && b.IsInt) { return new ExpressionValue(a.ToIntValue()*b.ToIntValue()); } return new ExpressionValue(a.ToFloatValue()*b.ToFloatValue()); } /// <summary> /// Perform a non-equal on two expressions. Booleans, ints and strings must /// exactly non-equal. Floating point must be non-equal within the default /// Encog tolerance. /// </summary> /// <param name="a">The first parameter to check.</param> /// <param name="b">The second parameter to check.</param> /// <returns>True/false.</returns> public static ExpressionValue Notequ(ExpressionValue a, ExpressionValue b) { if (a.ExprType == EPLValueType.BooleanType) { return new ExpressionValue(a.ToBooleanValue() != b.ToBooleanValue()); } if (a.ExprType == EPLValueType.EnumType) { return new ExpressionValue(a.ToIntValue() != b.ToIntValue() && a.EnumType == b.EnumType); } if (a.ExprType == EPLValueType.StringType) { return new ExpressionValue(!a.ToStringValue().Equals( b.ToStringValue())); } double diff = Math.Abs(a.ToFloatValue() - b.ToFloatValue()); return new ExpressionValue(diff > EncogFramework.DefaultDoubleEqual); } /// <summary> /// Perform a protected div on two expression values. a/b If one param is a /// float, the other is converted to a float. /// </summary> /// <param name="a">The first argument, must be numeric.</param> /// <param name="b">The second argument, must be numeric.</param> /// <returns>The result of the operation.</returns> public static ExpressionValue Pow(ExpressionValue a, ExpressionValue b) { if (a.IsInt && b.IsInt) { return new ExpressionValue(Math.Pow(a.ToIntValue(), b.ToIntValue())); } return new ExpressionValue(Math.Pow(a.ToFloatValue(), b.ToFloatValue())); } /// <summary> /// Perform a protected div on two expression values. a/b Division by zero /// results in 1. /// </summary> /// <param name="a">The first argument, must be numeric.</param> /// <param name="b">The second argument, must be numeric.</param> /// <returns>The result of the operation.</returns> public static ExpressionValue ProtectedDiv(ExpressionValue a, ExpressionValue b) { if (a.IsInt && b.IsInt) { long i = b.ToIntValue(); if (i == 0) { return new ExpressionValue(1); } return new ExpressionValue(a.ToIntValue()/i); } double denom = b.ToFloatValue(); if (Math.Abs(denom) < EncogFramework.DefaultDoubleEqual) { return new ExpressionValue(1); } return new ExpressionValue(a.ToFloatValue()/denom); } /// <summary> /// Perform a subtract on two expression values. a-b If one param is a float, /// the other is converted to a float. /// </summary> /// <param name="a">The first argument, must be numeric.</param> /// <param name="b">The second argument, must be numeric.</param> /// <returns>The result of the operation.</returns> public static ExpressionValue Sub(ExpressionValue a, ExpressionValue b) { if (a.IsInt && b.IsInt) { return new ExpressionValue(a.ToIntValue() - b.ToIntValue()); } return new ExpressionValue(a.ToFloatValue() - b.ToFloatValue()); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using System; using System.Collections.Generic; using HoloToolkit.Unity; namespace HoloToolkit.Sharing { /// <summary> /// The ServerSessionsTracker manages the list of sessions on the server and the users in these sessions. /// Instance is created by Sharing Stage when a connection is found. /// </summary> public class ServerSessionsTracker : IDisposable { private bool disposed; private SessionManager sessionManager; private SessionManagerAdapter sessionManagerAdapter; public event Action<bool, string> SessionCreated; public event Action<Session> SessionAdded; public event Action<Session> SessionClosed; public event Action<Session, User> UserChanged; public event Action<Session, User> UserJoined; public event Action<Session, User> UserLeft; public event Action<Session> CurrentUserLeft; public event Action<Session> CurrentUserJoined; public event Action ServerConnected; public event Action ServerDisconnected; /// <summary> /// List of sessions on the server. /// </summary> public List<Session> Sessions { get; private set; } /// <summary> /// Indicates whether there is a connection to the server or not. /// </summary> public bool IsServerConnected { get; private set; } public ServerSessionsTracker(SessionManager sessionMgr) { sessionManager = sessionMgr; Sessions = new List<Session>(); if (sessionManager != null) { sessionManagerAdapter = new SessionManagerAdapter(); sessionManager.AddListener(sessionManagerAdapter); sessionManagerAdapter.ServerConnectedEvent += OnServerConnected; sessionManagerAdapter.ServerDisconnectedEvent += OnServerDisconnected; sessionManagerAdapter.SessionClosedEvent += OnSessionClosed; sessionManagerAdapter.SessionAddedEvent += OnSessionAdded; sessionManagerAdapter.CreateSucceededEvent += OnSessionCreatedSuccess; sessionManagerAdapter.CreateFailedEvent += OnSessionCreatedFail; sessionManagerAdapter.UserChangedEvent += OnUserChanged; sessionManagerAdapter.UserJoinedSessionEvent += OnUserJoined; sessionManagerAdapter.UserLeftSessionEvent += OnUserLeft; } } /// <summary> /// Retrieves the current session, if any. /// </summary> /// <returns>Current session the app is in. Null if no session is joined.</returns> public Session GetCurrentSession() { return sessionManager.GetCurrentSession(); } /// <summary> /// Join the specified session. /// </summary> /// <param name="session">Session to join.</param> /// <returns>True if the session is being joined or is already joined.</returns> public bool JoinSession(Session session) { // TODO Should prevent joining multiple sessions at the same time if (session != null) { return session.IsJoined() || session.Join(); } return false; } /// <summary> /// Leave the current session. /// </summary> public void LeaveCurrentSession() { using (Session currentSession = GetCurrentSession()) { if (currentSession != null) { currentSession.Leave(); } } } /// <summary> /// Creates a new session on the server. /// </summary> /// <param name="sessionName">Name of the session.</param> /// <returns>True if a session was created, false if not.</returns> public bool CreateSession(string sessionName) { if (disposed) { return false; } return sessionManager.CreateSession(sessionName); } private void OnSessionCreatedFail(XString reason) { using (reason) { SessionCreated.RaiseEvent(false, reason.GetString()); } } private void OnSessionCreatedSuccess(Session session) { using (session) { SessionCreated.RaiseEvent(true, session.GetName().GetString()); } } private void OnUserChanged(Session session, User user) { UserChanged.RaiseEvent(session, user); } private void OnUserLeft(Session session, User user) { UserLeft.RaiseEvent(session, user); if (IsLocalUser(user)) { CurrentUserLeft.RaiseEvent(session); } } private void OnUserJoined(Session session, User newUser) { UserJoined.RaiseEvent(session, newUser); if (IsLocalUser(newUser)) { CurrentUserJoined.RaiseEvent(session); } } private void OnSessionAdded(Session newSession) { Sessions.Add(newSession); SessionAdded.RaiseEvent(newSession); } private void OnSessionClosed(Session session) { SessionClosed.RaiseEvent(session); Sessions.Remove(session); } private void OnServerDisconnected() { IsServerConnected = false; // Remove all sessions for (int i = 0; i < Sessions.Count; i++) { Sessions[i].Dispose(); } Sessions.Clear(); ServerDisconnected.RaiseEvent(); } private void OnServerConnected() { IsServerConnected = true; ServerConnected.RaiseEvent(); } private bool IsLocalUser(User user) { int changedUserId = user.GetID(); using (User localUser = sessionManager.GetCurrentUser()) { int localUserId = localUser.GetID(); return localUserId == changedUserId; } } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { OnServerDisconnected(); if (sessionManagerAdapter != null) { sessionManagerAdapter.ServerConnectedEvent -= OnServerConnected; sessionManagerAdapter.ServerDisconnectedEvent -= OnServerDisconnected; sessionManagerAdapter.SessionClosedEvent -= OnSessionClosed; sessionManagerAdapter.SessionAddedEvent -= OnSessionAdded; sessionManagerAdapter.CreateSucceededEvent -= OnSessionCreatedSuccess; sessionManagerAdapter.CreateFailedEvent -= OnSessionCreatedFail; sessionManagerAdapter.UserChangedEvent -= OnUserChanged; sessionManagerAdapter.UserJoinedSessionEvent -= OnUserJoined; sessionManagerAdapter.UserLeftSessionEvent -= OnUserLeft; sessionManagerAdapter.Dispose(); sessionManagerAdapter = null; } if (sessionManager != null) { sessionManager.Dispose(); sessionManager = null; } } disposed = true; } #endregion } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Threading; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents menu item /// </summary> [ContentProperty(nameof(Items))] [TemplatePart(Name = "PART_ScrollViewer", Type = typeof(ScrollViewer))] [TemplatePart(Name = "PART_MenuPanel", Type = typeof(Panel))] public class MenuItem : System.Windows.Controls.MenuItem, IQuickAccessItemProvider, IRibbonControl, IDropDownControl, IToggleButton { #region Fields private Panel? menuPanel; private ScrollViewer? scrollViewer; #endregion #region Properties private bool IsItemsControlMenuBase => (ItemsControlHelper.ItemsControlFromItemContainer(this) ?? VisualTreeHelper.GetParent(this)) is MenuBase; #region Size /// <inheritdoc /> public RibbonControlSize Size { get { return (RibbonControlSize)this.GetValue(SizeProperty); } set { this.SetValue(SizeProperty, value); } } /// <summary>Identifies the <see cref="Size"/> dependency property.</summary> public static readonly DependencyProperty SizeProperty = RibbonProperties.SizeProperty.AddOwner(typeof(MenuItem)); #endregion #region SizeDefinition /// <inheritdoc /> public RibbonControlSizeDefinition SizeDefinition { get { return (RibbonControlSizeDefinition)this.GetValue(SizeDefinitionProperty); } set { this.SetValue(SizeDefinitionProperty, value); } } /// <summary>Identifies the <see cref="SizeDefinition"/> dependency property.</summary> public static readonly DependencyProperty SizeDefinitionProperty = RibbonProperties.SizeDefinitionProperty.AddOwner(typeof(MenuItem)); #endregion #region KeyTip /// <inheritdoc /> public string? KeyTip { get { return (string?)this.GetValue(KeyTipProperty); } set { this.SetValue(KeyTipProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for Keys. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(MenuItem)); #endregion /// <inheritdoc /> public Popup? DropDownPopup { get; private set; } /// <inheritdoc /> public bool IsContextMenuOpened { get; set; } #region Description /// <summary> /// Useless property only used in secon level application menu items /// </summary> public string? Description { get { return (string?)this.GetValue(DescriptionProperty); } set { this.SetValue(DescriptionProperty, value); } } /// <summary>Identifies the <see cref="Description"/> dependency property.</summary> public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register(nameof(Description), typeof(string), typeof(MenuItem), new PropertyMetadata(default(string))); #endregion #region IsDropDownOpen /// <inheritdoc /> public bool IsDropDownOpen { get { return this.IsSubmenuOpen; } set { this.IsSubmenuOpen = value; } } #endregion #region IsDefinitive /// <summary> /// Gets or sets whether ribbon control click must close backstage /// </summary> public bool IsDefinitive { get { return (bool)this.GetValue(IsDefinitiveProperty); } set { this.SetValue(IsDefinitiveProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="IsDefinitive"/> dependency property.</summary> public static readonly DependencyProperty IsDefinitiveProperty = DependencyProperty.Register(nameof(IsDefinitive), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region ResizeMode /// <summary> /// Gets or sets context menu resize mode /// </summary> public ContextMenuResizeMode ResizeMode { get { return (ContextMenuResizeMode)this.GetValue(ResizeModeProperty); } set { this.SetValue(ResizeModeProperty, value); } } /// <summary>Identifies the <see cref="ResizeMode"/> dependency property.</summary> public static readonly DependencyProperty ResizeModeProperty = DependencyProperty.Register(nameof(ResizeMode), typeof(ContextMenuResizeMode), typeof(MenuItem), new PropertyMetadata(ContextMenuResizeMode.None)); #endregion #region MaxDropDownHeight /// <summary> /// Get or sets max height of drop down popup /// </summary> public double MaxDropDownHeight { get { return (double)this.GetValue(MaxDropDownHeightProperty); } set { this.SetValue(MaxDropDownHeightProperty, value); } } /// <summary>Identifies the <see cref="MaxDropDownHeight"/> dependency property.</summary> public static readonly DependencyProperty MaxDropDownHeightProperty = DependencyProperty.Register(nameof(MaxDropDownHeight), typeof(double), typeof(MenuItem), new PropertyMetadata(SystemParameters.PrimaryScreenHeight / 3.0)); #endregion #region IsSplited /// <summary> /// Gets or sets a value indicating whether menu item is splited /// </summary> public bool IsSplited { get { return (bool)this.GetValue(IsSplitedProperty); } set { this.SetValue(IsSplitedProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="IsSplited"/> dependency property.</summary> public static readonly DependencyProperty IsSplitedProperty = DependencyProperty.Register(nameof(IsSplited), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.FalseBox)); #endregion #region GroupName /// <inheritdoc /> public string? GroupName { get { return (string?)this.GetValue(GroupNameProperty); } set { this.SetValue(GroupNameProperty, value); } } /// <inheritdoc /> bool? IToggleButton.IsChecked { get { return this.IsChecked; } set { this.IsChecked = value == true; } } /// <summary>Identifies the <see cref="GroupName"/> dependency property.</summary> public static readonly DependencyProperty GroupNameProperty = DependencyProperty.Register(nameof(GroupName), typeof(string), typeof(MenuItem), new PropertyMetadata(ToggleButtonHelper.OnGroupNameChanged)); #endregion #endregion #region Events /// <inheritdoc /> public event EventHandler? DropDownOpened; /// <inheritdoc /> public event EventHandler? DropDownClosed; #endregion #region Constructors /// <summary> /// Initializes static members of the <see cref="MenuItem"/> class. /// </summary> static MenuItem() { var type = typeof(MenuItem); ToolTipService.Attach(type); //PopupService.Attach(type); ContextMenuService.Attach(type); DefaultStyleKeyProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(type)); IsCheckedProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, ToggleButtonHelper.OnIsCheckedChanged)); IconProperty.OverrideMetadata(typeof(MenuItem), new FrameworkPropertyMetadata(LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); } /// <summary> /// Initializes a new instance of the <see cref="MenuItem"/> class. /// </summary> public MenuItem() { ContextMenuService.Coerce(this); } /// <inheritdoc /> protected override void OnMouseWheel(MouseWheelEventArgs e) { base.OnMouseWheel(e); // Fix to raise MouseWhele event (this.Parent as ListBox)?.RaiseEvent(e); } #endregion /// <summary>Identifies the <see cref="RecognizesAccessKey"/> dependency property.</summary> public static readonly DependencyProperty RecognizesAccessKeyProperty = DependencyProperty.RegisterAttached( nameof(RecognizesAccessKey), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary>Helper for setting <see cref="RecognizesAccessKeyProperty"/> on <paramref name="element"/>.</summary> /// <param name="element"><see cref="DependencyObject"/> to set <see cref="RecognizesAccessKeyProperty"/> on.</param> /// <param name="value">RecognizesAccessKey property value.</param> public static void SetRecognizesAccessKey(DependencyObject element, bool value) { element.SetValue(RecognizesAccessKeyProperty, BooleanBoxes.Box(value)); } /// <summary>Helper for getting <see cref="RecognizesAccessKeyProperty"/> from <paramref name="element"/>.</summary> /// <param name="element"><see cref="DependencyObject"/> to read <see cref="RecognizesAccessKeyProperty"/> from.</param> /// <returns>RecognizesAccessKey property value.</returns> public static bool GetRecognizesAccessKey(DependencyObject element) { return (bool)element.GetValue(RecognizesAccessKeyProperty); } /// <summary> /// Defines if access keys should be recognized. /// </summary> public bool RecognizesAccessKey { get { return (bool)this.GetValue(RecognizesAccessKeyProperty); } set { this.SetValue(RecognizesAccessKeyProperty, BooleanBoxes.Box(value)); } } #region QuickAccess /// <inheritdoc /> public virtual FrameworkElement CreateQuickAccessItem() { if (this.HasItems) { if (this.IsSplited) { var button = new SplitButton { CanAddButtonToQuickAccessToolBar = false }; RibbonControl.BindQuickAccessItem(this, button); RibbonControl.Bind(this, button, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay); button.DropDownOpened += this.OnQuickAccessOpened; return button; } else { var button = new DropDownButton(); RibbonControl.BindQuickAccessItem(this, button); RibbonControl.Bind(this, button, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay); button.DropDownOpened += this.OnQuickAccessOpened; return button; } } else { var button = new Button(); RibbonControl.BindQuickAccessItem(this, button); return button; } } /// <summary> /// Handles quick access button drop down menu opened /// </summary> protected void OnQuickAccessOpened(object? sender, EventArgs e) { var buttonInQuickAccess = (DropDownButton?)sender; if (buttonInQuickAccess is not null) { buttonInQuickAccess.DropDownClosed += this.OnQuickAccessMenuClosedOrUnloaded; buttonInQuickAccess.Unloaded += this.OnQuickAccessMenuClosedOrUnloaded; ItemsControlHelper.MoveItemsToDifferentControl(this, buttonInQuickAccess); } } /// <summary> /// Handles quick access button drop down menu closed /// </summary> protected void OnQuickAccessMenuClosedOrUnloaded(object? sender, EventArgs e) { var buttonInQuickAccess = (DropDownButton?)sender; if (buttonInQuickAccess is not null) { buttonInQuickAccess.DropDownClosed -= this.OnQuickAccessMenuClosedOrUnloaded; buttonInQuickAccess.Unloaded -= this.OnQuickAccessMenuClosedOrUnloaded; ItemsControlHelper.MoveItemsToDifferentControl(buttonInQuickAccess, this); } } /// <inheritdoc /> public bool CanAddToQuickAccessToolBar { get { return (bool)this.GetValue(CanAddToQuickAccessToolBarProperty); } set { this.SetValue(CanAddToQuickAccessToolBarProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="CanAddToQuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty CanAddToQuickAccessToolBarProperty = RibbonControl.CanAddToQuickAccessToolBarProperty.AddOwner(typeof(MenuItem)); private bool isContextMenuOpening; #endregion #region Public /// <inheritdoc /> public virtual KeyTipPressedResult OnKeyTipPressed() { if (this.HasItems == false) { this.OnClick(); return KeyTipPressedResult.Empty; } else { Keyboard.Focus(this); this.IsDropDownOpen = true; return new KeyTipPressedResult(true, true); } } /// <inheritdoc /> public void OnKeyTipBack() { this.IsDropDownOpen = false; } #endregion #region Overrides /// <inheritdoc /> protected override DependencyObject GetContainerForItemOverride() { return new MenuItem(); } /// <inheritdoc /> protected override bool IsItemItsOwnContainerOverride(object item) { return item is FrameworkElement; } #region Non MenuBase ItemsControl workarounds /// <summary> /// Returns logical parent; either Parent or ItemsControlFromItemContainer(this). /// </summary> /// <remarks> /// Copied from <see cref="System.Windows.Controls.MenuItem"/>. /// </remarks> public object LogicalParent { get { if (this.Parent is not null) { return this.Parent; } return ItemsControlFromItemContainer(this); } } /// <inheritdoc /> protected override void OnIsKeyboardFocusedChanged(DependencyPropertyChangedEventArgs e) { base.OnIsKeyboardFocusedChanged(e); if (this.IsItemsControlMenuBase == false) { this.IsHighlighted = this.IsKeyboardFocused; } } /// <inheritdoc /> protected override void OnMouseEnter(MouseEventArgs e) { base.OnMouseEnter(e); if (this.IsItemsControlMenuBase == false && this.isContextMenuOpening == false) { if (this.HasItems && this.LogicalParent is DropDownButton) { this.IsSubmenuOpen = true; } } } /// <inheritdoc /> protected override void OnMouseLeave(MouseEventArgs e) { base.OnMouseLeave(e); if (this.IsItemsControlMenuBase == false && this.isContextMenuOpening == false) { if (this.HasItems && this.LogicalParent is DropDownButton // prevent too slow close on regular DropDown && this.LogicalParent is ApplicationMenu == false) // prevent eager close on ApplicationMenu { this.IsSubmenuOpen = false; } } } /// <inheritdoc /> protected override void OnContextMenuOpening(ContextMenuEventArgs e) { this.isContextMenuOpening = true; // We have to close the sub menu as soon as the context menu gets opened // but only if it should be opened on ourself if (ReferenceEquals(this, e.Source)) { this.IsSubmenuOpen = false; } base.OnContextMenuOpening(e); } /// <inheritdoc /> protected override void OnContextMenuClosing(ContextMenuEventArgs e) { this.isContextMenuOpening = false; base.OnContextMenuClosing(e); } #endregion Non MenuBase ItemsControl workarounds /// <inheritdoc /> protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { if (e.ClickCount == 1) { if (this.IsSplited) { if (this.GetTemplateChild("PART_ButtonBorder") is Border buttonBorder && PopupService.IsMousePhysicallyOver(buttonBorder)) { this.OnClick(); } } else if (this.HasItems) { this.IsSubmenuOpen = !this.IsSubmenuOpen; } } base.OnMouseLeftButtonUp(e); } /// <inheritdoc /> protected override void OnClick() { // Close popup on click if (this.IsDefinitive && (!this.HasItems || this.IsSplited)) { PopupService.RaiseDismissPopupEventAsync(this, DismissPopupMode.Always); } var revertIsChecked = false; // Rewriting everthing contained in base.OnClick causes a lot of trouble. // In case IsCheckable is true and GroupName is not empty we revert the value for IsChecked back to true to prevent unchecking all items in the group if (this.IsCheckable && string.IsNullOrEmpty(this.GroupName) == false) { // If checked revert the IsChecked value back to true after forwarding the click to base if (this.IsChecked) { revertIsChecked = true; } } base.OnClick(); if (revertIsChecked) { this.RunInDispatcherAsync(() => this.SetCurrentValue(IsCheckedProperty, BooleanBoxes.TrueBox), DispatcherPriority.Background); } } /// <inheritdoc /> public override void OnApplyTemplate() { if (this.DropDownPopup is not null) { this.DropDownPopup.Opened -= this.OnDropDownOpened; this.DropDownPopup.Closed -= this.OnDropDownClosed; } this.DropDownPopup = this.GetTemplateChild("PART_Popup") as Popup; if (this.DropDownPopup is not null) { this.DropDownPopup.Opened += this.OnDropDownOpened; this.DropDownPopup.Closed += this.OnDropDownClosed; KeyboardNavigation.SetControlTabNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); KeyboardNavigation.SetDirectionalNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); KeyboardNavigation.SetTabNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); } this.scrollViewer = this.GetTemplateChild("PART_ScrollViewer") as ScrollViewer; this.menuPanel = this.GetTemplateChild("PART_MenuPanel") as Panel; } /// <inheritdoc /> protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Escape) { if (this.IsSubmenuOpen) { this.IsSubmenuOpen = false; } else { this.CloseParentDropDownOrMenuItem(); } e.Handled = true; } else { #region Non MenuBase ItemsControl workarounds if (this.IsItemsControlMenuBase == false) { var key = e.Key; if (this.FlowDirection == FlowDirection.RightToLeft) { if (key == Key.Right) { key = Key.Left; } else if (key == Key.Left) { key = Key.Right; } } if (key == Key.Right && this.menuPanel is not null) { this.IsSubmenuOpen = true; this.menuPanel.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); e.Handled = true; } else if (key == Key.Left) { if (this.IsSubmenuOpen) { this.IsSubmenuOpen = false; } else { var parentMenuItem = UIHelper.GetParent<System.Windows.Controls.MenuItem>(this); if (parentMenuItem is not null) { parentMenuItem.IsSubmenuOpen = false; } } e.Handled = true; } if (e.Handled) { return; } } #endregion Non MenuBase ItemsControl workarounds base.OnKeyDown(e); } } private void CloseParentDropDownOrMenuItem() { var parent = UIHelper.GetParent<DependencyObject>(this, x => x is IDropDownControl || x is System.Windows.Controls.MenuItem); if (parent is null) { return; } if (parent is IDropDownControl dropDown) { dropDown.IsDropDownOpen = false; } else { ((System.Windows.Controls.MenuItem)parent).IsSubmenuOpen = false; } } #endregion #region Methods // Handles drop down opened private void OnDropDownClosed(object? sender, EventArgs e) { this.DropDownClosed?.Invoke(this, e); } // Handles drop down closed private void OnDropDownOpened(object? sender, EventArgs e) { if (this.scrollViewer is not null && this.ResizeMode != ContextMenuResizeMode.None) { this.scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; } if (this.menuPanel is not null) { this.menuPanel.Width = double.NaN; this.menuPanel.Height = double.NaN; } this.DropDownOpened?.Invoke(this, e); } #endregion /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } if (this.Icon is not null) { yield return this.Icon; } } } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using ExtensionCommands; using Oakton; using Oakton.Help; using Shouldly; using Xunit; namespace Tests { public class CommandFactoryTester { [Fact] public void get_the_command_name_for_a_class_not_decorated_with_the_attribute() { CommandFactory.CommandNameFor(typeof (MyCommand)).ShouldBe("my"); } [Fact] public void get_the_command_name_for_a_class_not_ending_in_command() { CommandFactory.CommandNameFor(typeof(SillyCommand)).ShouldBe("silly"); } [Fact] public void get_the_command_name_for_a_class_that_has_a_longer_name() { CommandFactory.CommandNameFor(typeof(RebuildAuthorizationCommand)).ShouldBe("rebuildauthorization"); } [Fact] public void get_the_command_name_for_a_class_decorated_with_the_attribute() { CommandFactory.CommandNameFor(typeof (DecoratedCommand)).ShouldBe("this"); } [Fact] public void get_the_description_for_a_class_not_decorated_with_the_attribute() { CommandFactory.DescriptionFor(typeof (MyCommand)).ShouldBe(typeof (MyCommand).FullName); } [Fact] public void get_the_description_for_a_class_decorated_with_the_attribute() { CommandFactory.DescriptionFor(typeof (My2Command)).ShouldBe("something"); } [Fact] public void get_the_command_name_for_a_class_decorated_with_the_attribute_but_without_the_name_specified() { CommandFactory.CommandNameFor(typeof (My2Command)).ShouldBe("my2"); } [Fact] public void build() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.Build("my").ShouldBeOfType<MyCommand>(); factory.Build("my2").ShouldBeOfType<My2Command>(); factory.Build("this").ShouldBeOfType<DecoratedCommand>(); } [Fact] public void trying_to_build_a_missing_command_will_list_the_existing_commands() { var factory = new CommandFactory(); factory.SetAppName("bottles"); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var commandRun = factory.BuildRun("junk"); var theInput = commandRun.Input.ShouldBeOfType<HelpInput>(); theInput.AppName.ShouldBe("bottles"); theInput.Name.ShouldBe("junk"); theInput.InvalidCommandName.ShouldBeTrue(); commandRun.Command.ShouldBeOfType<HelpCommand>(); } [Fact] public void build_help_command_with_valid_name_argument() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var commandRun = factory.BuildRun("help my"); var theInput = commandRun.Input.ShouldBeOfType<HelpInput>(); theInput.Name.ShouldBe("my"); theInput.InvalidCommandName.ShouldBeFalse(); theInput.Usage.ShouldNotBeNull(); commandRun.Command.ShouldBeOfType<HelpCommand>(); } [Fact] public void build_help_command_with_invalid_name_argument() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var commandRun = factory.BuildRun("help junk"); var theInput = commandRun.Input.ShouldBeOfType<HelpInput>(); theInput.Name.ShouldBe("junk"); theInput.InvalidCommandName.ShouldBeTrue(); theInput.Usage.ShouldBeNull(); commandRun.Command.ShouldBeOfType<HelpCommand>(); } [Fact] public void build_command_from_a_string() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.BuildRun("my Jeremy --force"); run.Command.ShouldBeOfType<MyCommand>(); var input = run.Input.ShouldBeOfType<MyCommandInput>(); input.Name.ShouldBe("Jeremy"); input.ForceFlag.ShouldBeTrue(); } [Fact] public void call_through_the_configure_run() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); object input = null; object cmd = null; factory.ConfigureRun = r => { cmd = r.Command; input = r.Input; }; var run = factory.BuildRun("my Jeremy --force"); cmd.ShouldBe(run.Command); input.ShouldBe(run.Input); } [Fact] public void fetch_the_help_command_run() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.HelpRun(new Queue<string>()); run.Command.ShouldBeOfType<HelpCommand>(); run.Input.ShouldBeOfType<HelpInput>().CommandTypes .ShouldContain(typeof (MyCommand)); } [Fact] public void fetch_the_help_command_if_the_args_are_empty() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.BuildRun(new string[0]); run.Command.ShouldBeOfType<HelpCommand>(); run.Input.ShouldBeOfType<HelpInput>().CommandTypes .ShouldContain(typeof (MyCommand)); } [Fact] public void fetch_the_help_command_if_the_command_is_help() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.BuildRun(new [] {"help"}); run.Command.ShouldBeOfType<HelpCommand>(); run.Input.ShouldBeOfType<HelpInput>().CommandTypes .ShouldContain(typeof (MyCommand)); } [Fact] public void fetch_the_help_command_if_the_command_is_question_mark() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.BuildRun(new [] {"?"}); run.Command.ShouldBeOfType<HelpCommand>(); run.Input.ShouldBeOfType<HelpInput>().CommandTypes .ShouldContain(typeof (MyCommand)); } [Fact] public void smoke_test_the_writing() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.HelpRun(new Queue<string>()).Execute(); } [Fact] public void build_command_with_multiargs() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); var run = factory.BuildRun("my Jeremy -ft"); var input = run.Input.ShouldBeOfType<MyCommandInput>(); input.ForceFlag.ShouldBeTrue(); input.SecondFlag.ShouldBeFalse(); input.ThirdFlag.ShouldBeTrue(); } [Fact] public void no_default_command_by_default() { var factory = new CommandFactory(); factory.DefaultCommand.ShouldBeNull(); } [Fact] public void default_command_is_derived_as_the_only_one() { var factory = new CommandFactory(); factory.RegisterCommand<RebuildAuthorizationCommand>(); factory.DefaultCommand.ShouldBe(typeof(RebuildAuthorizationCommand)); } [Fact] public void default_command_is_derived_as_the_only_one_2() { var factory = new CommandFactory(); factory.RegisterCommand(typeof(RebuildAuthorizationCommand)); factory.DefaultCommand.ShouldBe(typeof(RebuildAuthorizationCommand)); } [Fact] public void explicit_default_command() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(RebuildAuthorizationCommand); factory.DefaultCommand.ShouldBe(typeof(RebuildAuthorizationCommand)); } [Fact] public void build_command_with_default_command_and_empty() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(NoArgCommand); factory.BuildRun("").Command.ShouldBeOfType<NoArgCommand>(); } [Fact] public void build_command_with_default_command_and_first_arg_is_flag() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(OnlyFlagsCommand); var commandRun = factory.BuildRun("--verbose"); commandRun.Command.ShouldBeOfType<OnlyFlagsCommand>(); commandRun.Input.ShouldBeOfType<OnlyFlagsInput>() .VerboseFlag.ShouldBeTrue(); } [Fact] public void build_command_with_default_command_and_first_arg_is_flag_that_is_not_valid() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(OnlyFlagsCommand); var commandRun = factory.BuildRun("--wrong"); commandRun.Command.ShouldBeOfType<HelpCommand>(); commandRun.Input.ShouldBeOfType<HelpInput>() .Name.ShouldBe("onlyflags"); } [Fact] public void build_command_with_default_command_and_first_arg_for_the_default_command() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(SillyCommand); var commandRun = factory.BuildRun("blue"); commandRun.Command.ShouldBeOfType<SillyCommand>(); commandRun.Input.ShouldBeOfType<MyCommandInput>() .Name.ShouldBe("blue"); } [Fact] public void still_use_help_with_default_command() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(RebuildAuthorizationCommand); factory.BuildRun("help").Command.ShouldBeOfType<HelpCommand>(); } [Fact] public void build_the_default_command_using_arguments() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.DefaultCommand = typeof(RebuildAuthorizationCommand); factory.BuildRun("Hank").Input .ShouldBeOfType<MyCommandInput>() .Name.ShouldBe("Hank"); } [Fact] public void can_discover_extension_commands() { var factory = new CommandFactory(); factory.RegisterCommandsFromExtensionAssemblies(); factory.AllCommandTypes() .ShouldContain(typeof(ExtensionCommand)); factory.AllCommandTypes() .ShouldContain(typeof(Extension2Command)); } [Fact] public async Task set_up_command_prereq_using_beforebuild() { var factory = new CommandFactory(); factory.RegisterCommands(GetType().GetTypeInfo().Assembly); factory.BeforeBuild = (commandName, input) => { ConfigureMe.IsSet = true; }; var run = factory.BuildRun("depends-static"); (await run.Execute()).ShouldBe(true); } [Fact] public async Task can_execute_command_constructor_custom_usage_all_optional_arguments() { var factory = new CommandFactory(); factory.RegisterCommand<OptionalArgumentsCommand>(); var run = factory.BuildRun("optionalarguments"); (await run.Execute()).ShouldBe(true); } [Fact] public async Task can_execute_command_no_default_constructor() { var factory = new CommandFactory(new NoDefaultConstructorCommandCreator()); factory.RegisterCommand<NoDefaultConstructorCommand>(); var run = factory.BuildRun("nodefaultconstructor"); (await run.Execute()).ShouldBe(true); } } public class NulloInput { } public class NoArgCommand : OaktonCommand<NulloInput> { public override bool Execute(NulloInput input) { return true; } } public class RebuildAuthorizationCommand : OaktonCommand<MyCommandInput> { public override bool Execute(MyCommandInput input) { throw new NotImplementedException(); } } public class SillyCommand : OaktonCommand<MyCommandInput> { public override bool Execute(MyCommandInput input) { throw new NotImplementedException(); } } public class MyCommand : OaktonCommand<MyCommandInput> { public override bool Execute(MyCommandInput input) { throw new NotImplementedException(); } } public class OnlyFlagsInput { public bool VerboseFlag { get; set; } } public class OnlyFlagsCommand : OaktonCommand<OnlyFlagsInput> { public override bool Execute(OnlyFlagsInput input) { return true; } } [Description("something")] public class My2Command : OaktonCommand<MyCommandInput> { public override bool Execute(MyCommandInput input) { throw new NotImplementedException(); } } [Description("this", Name = "this")] public class DecoratedCommand : OaktonCommand<MyCommandInput> { public override bool Execute(MyCommandInput input) { throw new NotImplementedException(); } } public static class ConfigureMe { public static bool IsSet { get; set; } } [Description("Depends on some static state, e.g. configuring DI container based on inputs.", Name="depends-static")] public class DependsOnStaticCommand : OaktonCommand<NulloInput> { public override bool Execute(NulloInput input) { return ConfigureMe.IsSet; } } public class MyCommandInput { public string Name { get; set; } public bool ForceFlag { get; set; } public bool SecondFlag { get; set; } public bool ThirdFlag { get; set; } } public class OptionalArgumentsInput { [Description("Listening on defined port")] public int Port { get; set; } = 12345; [Description("Get binaries"), FlagAlias("withBinaries", 'b')] public bool WithBinariesFlag { get; set; } } public class OptionalArgumentsCommand : OaktonCommand<OptionalArgumentsInput> { public OptionalArgumentsCommand() { Usage("Listen on default port").Arguments(); Usage("Listen with explicit port").Arguments(i => i.Port); } public override bool Execute(OptionalArgumentsInput input) { return true; } } // Not exported to avoid breaking other tests that use assembly-wide command registration. internal class NoDefaultConstructorCommand : OaktonCommand<OptionalArgumentsInput> { public NoDefaultConstructorCommand(string _) { Usage("Listen on default port").Arguments(); } public override bool Execute(OptionalArgumentsInput input) { return true; } } public class NoDefaultConstructorCommandCreator : ICommandCreator { public IOaktonCommand CreateCommand(Type commandType) { return new NoDefaultConstructorCommand("required parameter"); } public object CreateModel(Type modelType) { return Activator.CreateInstance(modelType); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/field_mask.proto</summary> public static partial class FieldMaskReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/field_mask.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FieldMaskReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy", "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUJRChNjb20uZ29v", "Z2xlLnByb3RvYnVmQg5GaWVsZE1hc2tQcm90b1ABoAEBogIDR1BCqgIeR29v", "Z2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FieldMask), global::Google.Protobuf.WellKnownTypes.FieldMask.Parser, new[]{ "Paths" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// `FieldMask` represents a set of symbolic field paths, for example: /// /// paths: "f.a" /// paths: "f.b.d" /// /// Here `f` represents a field in some root message, `a` and `b` /// fields in the message found in `f`, and `d` a field found in the /// message in `f.b`. /// /// Field masks are used to specify a subset of fields that should be /// returned by a get operation or modified by an update operation. /// Field masks also have a custom JSON encoding (see below). /// /// # Field Masks in Projections /// /// When used in the context of a projection, a response message or /// sub-message is filtered by the API to only contain those fields as /// specified in the mask. For example, if the mask in the previous /// example is applied to a response message as follows: /// /// f { /// a : 22 /// b { /// d : 1 /// x : 2 /// } /// y : 13 /// } /// z: 8 /// /// The result will not contain specific values for fields x,y and z /// (their value will be set to the default, and omitted in proto text /// output): /// /// f { /// a : 22 /// b { /// d : 1 /// } /// } /// /// A repeated field is not allowed except at the last position of a /// field mask. /// /// If a FieldMask object is not present in a get operation, the /// operation applies to all fields (as if a FieldMask of all fields /// had been specified). /// /// Note that a field mask does not necessarily apply to the /// top-level response message. In case of a REST get operation, the /// field mask applies directly to the response, but in case of a REST /// list operation, the mask instead applies to each individual message /// in the returned resource list. In case of a REST custom method, /// other definitions may be used. Where the mask applies will be /// clearly documented together with its declaration in the API. In /// any case, the effect on the returned resource/resources is required /// behavior for APIs. /// /// # Field Masks in Update Operations /// /// A field mask in update operations specifies which fields of the /// targeted resource are going to be updated. The API is required /// to only change the values of the fields as specified in the mask /// and leave the others untouched. If a resource is passed in to /// describe the updated values, the API ignores the values of all /// fields not covered by the mask. /// /// If a repeated field is specified for an update operation, the existing /// repeated values in the target resource will be overwritten by the new values. /// Note that a repeated field is only allowed in the last position of a field /// mask. /// /// If a sub-message is specified in the last position of the field mask for an /// update operation, then the existing sub-message in the target resource is /// overwritten. Given the target message: /// /// f { /// b { /// d : 1 /// x : 2 /// } /// c : 1 /// } /// /// And an update message: /// /// f { /// b { /// d : 10 /// } /// } /// /// then if the field mask is: /// /// paths: "f.b" /// /// then the result will be: /// /// f { /// b { /// d : 10 /// } /// c : 1 /// } /// /// However, if the update mask was: /// /// paths: "f.b.d" /// /// then the result would be: /// /// f { /// b { /// d : 10 /// x : 2 /// } /// c : 1 /// } /// /// In order to reset a field's value to the default, the field must /// be in the mask and set to the default value in the provided resource. /// Hence, in order to reset all fields of a resource, provide a default /// instance of the resource and set all fields in the mask, or do /// not provide a mask as described below. /// /// If a field mask is not present on update, the operation applies to /// all fields (as if a field mask of all fields has been specified). /// Note that in the presence of schema evolution, this may mean that /// fields the client does not know and has therefore not filled into /// the request will be reset to their default. If this is unwanted /// behavior, a specific service may require a client to always specify /// a field mask, producing an error if not. /// /// As with get operations, the location of the resource which /// describes the updated values in the request message depends on the /// operation kind. In any case, the effect of the field mask is /// required to be honored by the API. /// /// ## Considerations for HTTP REST /// /// The HTTP kind of an update operation which uses a field mask must /// be set to PATCH instead of PUT in order to satisfy HTTP semantics /// (PUT must only be used for full updates). /// /// # JSON Encoding of Field Masks /// /// In JSON, a field mask is encoded as a single string where paths are /// separated by a comma. Fields name in each path are converted /// to/from lower-camel naming conventions. /// /// As an example, consider the following message declarations: /// /// message Profile { /// User user = 1; /// Photo photo = 2; /// } /// message User { /// string display_name = 1; /// string address = 2; /// } /// /// In proto a field mask for `Profile` may look as such: /// /// mask { /// paths: "user.display_name" /// paths: "photo" /// } /// /// In JSON, the same mask is represented as below: /// /// { /// mask: "user.displayName,photo" /// } /// /// # Field Masks and Oneof Fields /// /// Field masks treat fields in oneofs just as regular fields. Consider the /// following message: /// /// message SampleMessage { /// oneof test_oneof { /// string name = 4; /// SubMessage sub_message = 9; /// } /// } /// /// The field mask can be: /// /// mask { /// paths: "name" /// } /// /// Or: /// /// mask { /// paths: "sub_message" /// } /// /// Note that oneof type names ("test_oneof" in this case) cannot be used in /// paths. /// </summary> public sealed partial class FieldMask : pb::IMessage<FieldMask> { private static readonly pb::MessageParser<FieldMask> _parser = new pb::MessageParser<FieldMask>(() => new FieldMask()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FieldMask> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask(FieldMask other) : this() { paths_ = other.paths_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FieldMask Clone() { return new FieldMask(this); } /// <summary>Field number for the "paths" field.</summary> public const int PathsFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_paths_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> paths_ = new pbc::RepeatedField<string>(); /// <summary> /// The set of field mask paths. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Paths { get { return paths_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FieldMask); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FieldMask other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!paths_.Equals(other.paths_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= paths_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { paths_.WriteTo(output, _repeated_paths_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += paths_.CalculateSize(_repeated_paths_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FieldMask other) { if (other == null) { return; } paths_.Add(other.paths_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { paths_.AddEntriesFrom(input, _repeated_paths_codec); break; } } } } } #endregion } #endregion Designer generated code
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> instances.</summary> public sealed partial class BiddingSeasonalityAdjustmentServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>. /// </summary> /// <returns>A new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</returns> public static BiddingSeasonalityAdjustmentServiceSettings GetDefault() => new BiddingSeasonalityAdjustmentServiceSettings(); /// <summary> /// Constructs a new <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object with default settings. /// </summary> public BiddingSeasonalityAdjustmentServiceSettings() { } private BiddingSeasonalityAdjustmentServiceSettings(BiddingSeasonalityAdjustmentServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetBiddingSeasonalityAdjustmentSettings = existing.GetBiddingSeasonalityAdjustmentSettings; MutateBiddingSeasonalityAdjustmentsSettings = existing.MutateBiddingSeasonalityAdjustmentsSettings; OnCopy(existing); } partial void OnCopy(BiddingSeasonalityAdjustmentServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BiddingSeasonalityAdjustmentServiceClient.GetBiddingSeasonalityAdjustment</c> and /// <c>BiddingSeasonalityAdjustmentServiceClient.GetBiddingSeasonalityAdjustmentAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetBiddingSeasonalityAdjustmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustments</c> and /// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustmentsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateBiddingSeasonalityAdjustmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object.</returns> public BiddingSeasonalityAdjustmentServiceSettings Clone() => new BiddingSeasonalityAdjustmentServiceSettings(this); } /// <summary> /// Builder class for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class BiddingSeasonalityAdjustmentServiceClientBuilder : gaxgrpc::ClientBuilderBase<BiddingSeasonalityAdjustmentServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BiddingSeasonalityAdjustmentServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BiddingSeasonalityAdjustmentServiceClientBuilder() { UseJwtAccessWithScopes = BiddingSeasonalityAdjustmentServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BiddingSeasonalityAdjustmentServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BiddingSeasonalityAdjustmentServiceClient> task); /// <summary>Builds the resulting client.</summary> public override BiddingSeasonalityAdjustmentServiceClient Build() { BiddingSeasonalityAdjustmentServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BiddingSeasonalityAdjustmentServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BiddingSeasonalityAdjustmentServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings); } private async stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BiddingSeasonalityAdjustmentServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BiddingSeasonalityAdjustmentServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BiddingSeasonalityAdjustmentServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>BiddingSeasonalityAdjustmentService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage bidding seasonality adjustments. /// </remarks> public abstract partial class BiddingSeasonalityAdjustmentServiceClient { /// <summary> /// The default endpoint for the BiddingSeasonalityAdjustmentService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default BiddingSeasonalityAdjustmentService scopes.</summary> /// <remarks> /// The default BiddingSeasonalityAdjustmentService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns> /// The task representing the created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>. /// </returns> public static stt::Task<BiddingSeasonalityAdjustmentServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BiddingSeasonalityAdjustmentServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns> public static BiddingSeasonalityAdjustmentServiceClient Create() => new BiddingSeasonalityAdjustmentServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</param> /// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns> internal static BiddingSeasonalityAdjustmentServiceClient Create(grpccore::CallInvoker callInvoker, BiddingSeasonalityAdjustmentServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient = new BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient(callInvoker); return new BiddingSeasonalityAdjustmentServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary> public virtual BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, st::CancellationToken cancellationToken) => GetBiddingSeasonalityAdjustmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetBiddingSeasonalityAdjustment(new GetBiddingSeasonalityAdjustmentRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetBiddingSeasonalityAdjustmentAsync(new GetBiddingSeasonalityAdjustmentRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(string resourceName, st::CancellationToken cancellationToken) => GetBiddingSeasonalityAdjustmentAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(gagvr::BiddingSeasonalityAdjustmentName resourceName, gaxgrpc::CallSettings callSettings = null) => GetBiddingSeasonalityAdjustment(new GetBiddingSeasonalityAdjustmentRequest { ResourceNameAsBiddingSeasonalityAdjustmentName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(gagvr::BiddingSeasonalityAdjustmentName resourceName, gaxgrpc::CallSettings callSettings = null) => GetBiddingSeasonalityAdjustmentAsync(new GetBiddingSeasonalityAdjustmentRequest { ResourceNameAsBiddingSeasonalityAdjustmentName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the seasonality adjustment to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(gagvr::BiddingSeasonalityAdjustmentName resourceName, st::CancellationToken cancellationToken) => GetBiddingSeasonalityAdjustmentAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, st::CancellationToken cancellationToken) => MutateBiddingSeasonalityAdjustmentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateBiddingSeasonalityAdjustments(new MutateBiddingSeasonalityAdjustmentsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateBiddingSeasonalityAdjustmentsAsync(new MutateBiddingSeasonalityAdjustmentsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, st::CancellationToken cancellationToken) => MutateBiddingSeasonalityAdjustmentsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BiddingSeasonalityAdjustmentService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage bidding seasonality adjustments. /// </remarks> public sealed partial class BiddingSeasonalityAdjustmentServiceClientImpl : BiddingSeasonalityAdjustmentServiceClient { private readonly gaxgrpc::ApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment> _callGetBiddingSeasonalityAdjustment; private readonly gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> _callMutateBiddingSeasonalityAdjustments; /// <summary> /// Constructs a client wrapper for the BiddingSeasonalityAdjustmentService service, with the specified gRPC /// client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> used within this client. /// </param> public BiddingSeasonalityAdjustmentServiceClientImpl(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings settings) { GrpcClient = grpcClient; BiddingSeasonalityAdjustmentServiceSettings effectiveSettings = settings ?? BiddingSeasonalityAdjustmentServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetBiddingSeasonalityAdjustment = clientHelper.BuildApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment>(grpcClient.GetBiddingSeasonalityAdjustmentAsync, grpcClient.GetBiddingSeasonalityAdjustment, effectiveSettings.GetBiddingSeasonalityAdjustmentSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetBiddingSeasonalityAdjustment); Modify_GetBiddingSeasonalityAdjustmentApiCall(ref _callGetBiddingSeasonalityAdjustment); _callMutateBiddingSeasonalityAdjustments = clientHelper.BuildApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse>(grpcClient.MutateBiddingSeasonalityAdjustmentsAsync, grpcClient.MutateBiddingSeasonalityAdjustments, effectiveSettings.MutateBiddingSeasonalityAdjustmentsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateBiddingSeasonalityAdjustments); Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref _callMutateBiddingSeasonalityAdjustments); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetBiddingSeasonalityAdjustmentApiCall(ref gaxgrpc::ApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment> call); partial void Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> call); partial void OnConstruction(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary> public override BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient { get; } partial void Modify_GetBiddingSeasonalityAdjustmentRequest(ref GetBiddingSeasonalityAdjustmentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref MutateBiddingSeasonalityAdjustmentsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBiddingSeasonalityAdjustmentRequest(ref request, ref callSettings); return _callGetBiddingSeasonalityAdjustment.Sync(request, callSettings); } /// <summary> /// Returns the requested seasonality adjustment in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBiddingSeasonalityAdjustmentRequest(ref request, ref callSettings); return _callGetBiddingSeasonalityAdjustment.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings); return _callMutateBiddingSeasonalityAdjustments.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings); return _callMutateBiddingSeasonalityAdjustments.Async(request, callSettings); } } }
using GalaSoft.MvvmLight; using System; using System.Windows.Media.Imaging; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Face.Contract; using System.Windows.Media; using System.Threading.Tasks; using System.Windows; using System.IO; using System.Drawing; using System.Linq; using FaceRecognitionEMGU; using System.Xml; using System.Text; using FaceRecognitionBetaface; using System.Collections.Generic; using System.Windows.Threading; namespace Demo1.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { public const string ImageSourcePathPropertyName = "ImageSourcePath"; private String _imageSourcePath; public String ImageSourcePath { get { return _imageSourcePath; } set { if (_imageSourcePath == value) { return; } _imageSourcePath = value; RaisePropertyChanged(ImageSourcePathPropertyName); } } public const string EmguResultPropertyName = "EmguResult"; private String _emguResult; public String EmguResult { get { return _emguResult; } set { if (_emguResult == value) { return; } _emguResult = value; RaisePropertyChanged(EmguResultPropertyName); } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { } #region Emgu EmguFaceDetector emguDetector; public const string EMGUImageResultPropertyName = "EMGUImageResult"; private BitmapSource _emguImageResult = null; public BitmapSource EMGUImageResult { get { return _emguImageResult; } set { if (_emguImageResult == value) { return; } _emguImageResult = value; RaisePropertyChanged(EMGUImageResultPropertyName); } } public async void Emgu() { StringBuilder sb = new StringBuilder(); EmguResult = "Training"; EmguFaceDetector emguDetector = new EmguFaceDetector("Default"); EmguResult = "Detecting"; Bitmap res = new Bitmap(ImageSourcePath); List<EMGUFace> faces = await emguDetector.detect(res); foreach (var item in faces) { if(item.gender == Gender.Female) res = InsertShape(res, "rectangle", item.x, item.y, (int)item.width, (int)item.height, "Purple", 4f); else if (item.gender == Gender.Male) res = InsertShape(res, "rectangle", item.x, item.y, (int)item.width, (int)item.height, "Cyan", 4f); foreach (var eye in item.eyes) { res = InsertShape(res, "filledellipse", item.x + (int)eye.X, item.y + (int)eye.Y, 10, 10, "Red", 4f); } sb.AppendLine(item.ToString()); } EMGUImageResult = ConvertBitmap(res); EmguResult = sb.ToString(); } #endregion #region Oxford public const string OxfordResultPropertyName = "OxfordResult"; private String _oxfordResult; public String OxfordResult { get { return _oxfordResult; } set { if (_oxfordResult == value) { return; } _oxfordResult = value; RaisePropertyChanged(OxfordResultPropertyName); } } public const string OxfordImageResultPropertyName = "OxfordImageResult"; private BitmapSource _oxfordImageResult = null; public BitmapSource OxfordImageResult { get { return _oxfordImageResult; } set { if (_oxfordImageResult == value) { return; } _oxfordImageResult = value; RaisePropertyChanged(OxfordImageResultPropertyName); } } private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("eb03b136ac4247e99e5f9e8587f3580c"); //PrimaryKey internal async void Oxford() { StringBuilder builder = new StringBuilder(); OxfordResult = "Detecting..."; Bitmap res = new Bitmap(ImageSourcePath); Face[] face = await UploadAndDetectFaces(ImageSourcePath); OxfordResult = String.Format("Detection Finished. {0} face(s) detected", face.Length); if (face.Length > 0) { foreach (var item in face) { if(item.Attributes.Gender.Equals("female")) res = InsertShape(res, "rectangle", item.FaceRectangle.Left, item.FaceRectangle.Top, item.FaceRectangle.Width, item.FaceRectangle.Height, "Purple", 4f); else res = InsertShape(res, "rectangle", item.FaceRectangle.Left, item.FaceRectangle.Top, item.FaceRectangle.Width, item.FaceRectangle.Height, "Cyan", 4f); res = InsertShape(res, "filledellipse", (int)item.FaceLandmarks.EyeLeftInner.X, (int)item.FaceLandmarks.EyeLeftInner.Y, 10, 10, "Red", 4f); res = InsertShape(res, "filledellipse", (int)item.FaceLandmarks.EyeRightInner.X, (int)item.FaceLandmarks.EyeRightInner.Y, 10, 10, "Red", 4f); res = InsertShape(res, "filledellipse", (int)item.FaceLandmarks.NoseTip.X, (int)item.FaceLandmarks.NoseTip.Y, 10, 10, "Red", 4f); res = InsertShape(res, "filledellipse", (int)item.FaceLandmarks.MouthLeft.X, (int)item.FaceLandmarks.MouthLeft.Y, 10, 10, "Red", 4f); res = InsertShape(res, "filledellipse", (int)item.FaceLandmarks.MouthRight.X, (int)item.FaceLandmarks.MouthRight.Y, 10, 10, "Red", 4f); builder.Append("X = " +item.FaceRectangle.Left + ";"); builder.Append("Y = " +item.FaceRectangle.Top + ";"); builder.Append("Width = " +item.FaceRectangle.Width + ";"); builder.Append("Height = " +item.FaceRectangle.Height + ";"); builder.Append("Gender = " +item.Attributes.Gender + ";"); builder.AppendLine("Age = " +item.Attributes.Age + ";"); OxfordResult = builder.ToString(); } } OxfordImageResult = ConvertBitmap(res); } private async Task<Face[]> UploadAndDetectFaces(string imageFilePath) { try { using (Stream imageFileStream = File.OpenRead(imageFilePath)) { var faces = await faceServiceClient.DetectAsync(imageFileStream, true, true, true, false); return faces.ToArray(); } } catch (Exception e) { return new Face[0]; } } #endregion #region Betaface BetafaceDetector betafaceDetector; BetafaceDetectorResult betafaceDetectorResult; Bitmap betafaceBitmapResult; Task betafaceTask; StringBuilder BetafaceBuilder; public const string BetafaceXMLResultPropertyName = "BetafaceXMLResult"; private String _betafaceXMLResult; public String BetafaceXMLResult { get { return _betafaceXMLResult; } set { if (_betafaceXMLResult == value) { return; } _betafaceXMLResult = value; RaisePropertyChanged(BetafaceXMLResultPropertyName); } } public const string BetafaceImageResultPropertyName = "BetafaceImageResult"; private BitmapSource _betafaceImageResult = null; public BitmapSource BetafaceImageResult { get { return _betafaceImageResult; } set { if (_betafaceImageResult == value) { return; } _betafaceImageResult = value; RaisePropertyChanged(BetafaceImageResultPropertyName); } } internal void Betaface() { BetafaceBuilder = new StringBuilder(); betafaceDetectorResult = null; betafaceBitmapResult = new Bitmap(ImageSourcePath); if (ImageSourcePath != null) { BetafaceXMLResult = "Detecting..."; betafaceDetector = new BetafaceDetector(); betafaceTask = new Task( () => { Image userImage = Image.FromFile(ImageSourcePath); //Start user detection betafaceDetectorResult = betafaceDetector.StartUserDetection(userImage); }); betafaceTask.Start(); betafaceTask.ContinueWith( (continuation) => { if(betafaceDetectorResult != null) { //Draw results on image foreach (var face in betafaceDetectorResult.BetafaceObjectResponse.faces) { if (face.tags.Any(x => x.value=="female")) betafaceBitmapResult = InsertShape(betafaceBitmapResult, "rectangle", (int)(face.x - (face.width / 2)), (int)(face.y - (face.height / 2)), (int)face.width, (int)face.height, "Purple", 4f); else betafaceBitmapResult = InsertShape(betafaceBitmapResult, "rectangle", (int)(face.x - (face.width / 2)), (int)(face.y - (face.height / 2)), (int)face.width, (int)face.height, "Cyan", 4f); betafaceBitmapResult = InsertShape(betafaceBitmapResult, "filledellipse", (int)(face.points.Where(x => x.name == "basic eye left").First().x), (int)(face.points.Where(x => x.name == "basic eye left").First().y), 10, 10, "Red", 4f); betafaceBitmapResult = InsertShape(betafaceBitmapResult, "filledellipse", (int)(face.points.Where(x => x.name == "basic eye right").First().x), (int)(face.points.Where(x => x.name == "basic eye right").First().y), 10, 10, "Red", 4f); betafaceBitmapResult = InsertShape(betafaceBitmapResult, "filledellipse", (int)(face.points.Where(x => x.name == "basic nose tip").First().x), (int)(face.points.Where(x => x.name == "basic nose tip").First().y), 10, 10, "Red", 4f); betafaceBitmapResult = InsertShape(betafaceBitmapResult, "filledellipse", (int)(face.points.Where(x => x.name == "basic mouth left").First().x), (int)(face.points.Where(x => x.name == "basic mouth left").First().y), 10, 10, "Red", 4f); betafaceBitmapResult = InsertShape(betafaceBitmapResult, "filledellipse", (int)(face.points.Where(x => x.name == "basic mouth right").First().x), (int)(face.points.Where(x => x.name == "basic mouth right").First().y), 10, 10, "Red", 4f); BetafaceBuilder.Append("X = " + face.x + "; "); BetafaceBuilder.Append("Y = " + face.y + "; "); BetafaceBuilder.Append("Width = " + face.width + "; "); BetafaceBuilder.Append("Height = " + face.height + "; "); BetafaceBuilder.Append("Gender = " + face.tags.Where(x => x.name == "gender").First().value + "; "); BetafaceBuilder.AppendLine("Age = " + face.tags.Where(x => x.name == "age").First().value + ";"); } //write XML reponse BetafaceXMLResult = BetafaceBuilder.ToString() + "\n"; BetafaceXMLResult += FormatXml(betafaceDetectorResult.BetafaceXMLResponse); var temp = ConvertBitmap(betafaceBitmapResult); temp.Freeze(); Application.Current.Dispatcher.Invoke(new Action(() => { BetafaceImageResult = temp; })); } else { BetafaceXMLResult = "No user detected!"; } }); } else { BetafaceXMLResult = "No user image available"; } } private string FormatXml(string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); var stringBuilder = new StringBuilder(); var xmlWriterSettings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }; doc.Save(XmlWriter.Create(stringBuilder, xmlWriterSettings)); return stringBuilder.ToString(); } #endregion internal void Initialize() { } internal void SelectImage() { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".png"; dlg.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document string filename = dlg.FileName; ImageSourcePath = filename; } } public Bitmap InsertShape(Bitmap image, string shapeType, int xPosition, int yPosition, int width, int height, string colorName, float thickness) { Bitmap bmap = (Bitmap)image.Clone(); Graphics gr = Graphics.FromImage(bmap); if (string.IsNullOrEmpty(colorName)) colorName = "Black"; System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.FromName(colorName), thickness); switch (shapeType.ToLower()) { case "filledellipse": gr.FillEllipse(pen.Brush, xPosition, yPosition, width, height); break; case "filledrectangle": gr.FillRectangle(pen.Brush, xPosition, yPosition, width, height); break; case "ellipse": gr.DrawEllipse(pen, xPosition, yPosition, width, height); break; case "rectangle": default: gr.DrawRectangle(pen, xPosition, yPosition, width, height); break; } return (Bitmap)bmap.Clone(); } public static BitmapSource ConvertBitmap(Bitmap source) { return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } public static Bitmap BitmapFromSource(BitmapSource bitmapsource) { Bitmap bitmap; using (var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapsource)); enc.Save(outStream); bitmap = new Bitmap(outStream); } return bitmap; } } }
using System; using System.IO.Compression; using Helios.Util; namespace Helios.Buffers { /// <summary> /// Abstract base class implementation of a <see cref="IByteBuf"/> /// </summary> public abstract class AbstractByteBuf : IByteBuf { private int _markedReaderIndex; private int _markedWriterIndex; protected AbstractByteBuf(int maxCapacity) { MaxCapacity = maxCapacity; } public abstract int Capacity { get; } public abstract IByteBuf AdjustCapacity(int newCapacity); public int MaxCapacity { get; private set; } public abstract IByteBufAllocator Allocator { get; } public virtual int ReaderIndex { get; protected set; } public virtual int WriterIndex { get; protected set; } public virtual IByteBuf SetWriterIndex(int writerIndex) { if (writerIndex < ReaderIndex || writerIndex > Capacity) throw new IndexOutOfRangeException(string.Format("WriterIndex: {0} (expected: 0 <= readerIndex({1}) <= writerIndex <= capacity ({2})", writerIndex, ReaderIndex, Capacity)); WriterIndex = writerIndex; return this; } public virtual IByteBuf SetReaderIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > WriterIndex) throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0} (expected: 0 <= readerIndex <= writerIndex({1})", readerIndex, WriterIndex)); ReaderIndex = readerIndex; return this; } public virtual IByteBuf SetIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > Capacity) throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0}, WriterIndex: {1} (expected: 0 <= readerIndex <= writerIndex <= capacity ({2})", readerIndex, writerIndex, Capacity)); ReaderIndex = readerIndex; WriterIndex = writerIndex; return this; } public virtual int ReadableBytes { get { return WriterIndex - ReaderIndex; } } public virtual int WritableBytes { get { return Capacity - WriterIndex; } } public virtual int MaxWritableBytes { get { return MaxCapacity - WriterIndex; } } public bool IsReadable() { return WriterIndex > ReaderIndex; } public bool IsReadable(int size) { return WriterIndex - ReaderIndex >= size; } public bool IsWritable() { return Capacity > WriterIndex; } public bool IsWritable(int size) { return Capacity - WriterIndex >= size; } public virtual IByteBuf Clear() { ReaderIndex = WriterIndex = 0; return this; } public virtual IByteBuf MarkReaderIndex() { _markedReaderIndex = ReaderIndex; return this; } public virtual IByteBuf ResetReaderIndex() { SetReaderIndex(_markedReaderIndex); return this; } public virtual IByteBuf MarkWriterIndex() { _markedWriterIndex = WriterIndex; return this; } public virtual IByteBuf ResetWriterIndex() { SetWriterIndex(_markedWriterIndex); return this; } public virtual IByteBuf DiscardReadBytes() { EnsureAccessible(); if (ReaderIndex == 0) return this; if (ReaderIndex != WriterIndex) { SetBytes(0, this, ReaderIndex, WriterIndex - ReaderIndex); WriterIndex -= ReaderIndex; AdjustMarkers(ReaderIndex); ReaderIndex = 0; } else { AdjustMarkers(ReaderIndex); WriterIndex = ReaderIndex = 0; } return this; } public virtual IByteBuf EnsureWritable(int minWritableBytes) { if (minWritableBytes < 0) throw new ArgumentOutOfRangeException("minWritableBytes", "expected minWritableBytes to be greater than zero"); if (minWritableBytes <= WritableBytes) return this; if (minWritableBytes > MaxCapacity - WriterIndex) { throw new IndexOutOfRangeException(string.Format( "writerIndex({0}) + minWritableBytes({1}) exceeds maxCapacity({2}): {3}", WriterIndex, minWritableBytes, MaxCapacity, this)); } //Normalize the current capacity to the power of 2 var newCapacity = CalculateNewCapacity(WriterIndex + minWritableBytes); //Adjust to the new capacity AdjustCapacity(newCapacity); return this; } private int CalculateNewCapacity(int minNewCapacity) { var maxCapacity = MaxCapacity; var threshold = 1048576 * 4; // 4 MiB page var newCapacity = 0; if (minNewCapacity == threshold) { return threshold; } // If over threshold, do not double but just increase by threshold. if (minNewCapacity > threshold) { newCapacity = minNewCapacity / threshold * threshold; if (newCapacity > maxCapacity - threshold) { newCapacity = maxCapacity; } else { newCapacity += threshold; } return newCapacity; } // Not over threshold. Double up to 4 MiB, starting from 64. newCapacity = 64; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } return Math.Min(newCapacity, maxCapacity); } public virtual bool GetBoolean(int index) { CheckIndex(index); return GetByte(index) != 0; } public virtual byte GetByte(int index) { CheckIndex(index); return _GetByte(index); } protected abstract byte _GetByte(int index); public virtual short GetShort(int index) { CheckIndex(index, 2); return _GetShort(index); } protected abstract short _GetShort(int index); public virtual ushort GetUnsignedShort(int index) { unchecked { return (ushort)(GetShort(index)); } } public virtual int GetInt(int index) { CheckIndex(index, 4); return _GetInt(index); } protected abstract int _GetInt(int index); public virtual uint GetUnsignedInt(int index) { unchecked { return (uint)(GetInt(index)); } } public virtual long GetLong(int index) { CheckIndex(index, 8); return _GetLong(index); } protected abstract long _GetLong(int index); public virtual char GetChar(int index) { return Convert.ToChar(GetShort(index)); } public virtual double GetDouble(int index) { return BitConverter.Int64BitsToDouble(GetLong(index)); } public virtual IByteBuf GetBytes(int index, IByteBuf destination) { GetBytes(index, destination, destination.WritableBytes); return this; } public virtual IByteBuf GetBytes(int index, IByteBuf destination, int length) { GetBytes(index, destination, destination.WriterIndex, length); return this; } public abstract IByteBuf GetBytes(int index, IByteBuf destination, int dstIndex, int length); public virtual IByteBuf GetBytes(int index, byte[] destination) { GetBytes(index, destination, 0, destination.Length); return this; } public abstract IByteBuf GetBytes(int index, byte[] destination, int dstIndex, int length); public virtual IByteBuf SetBoolean(int index, bool value) { SetByte(index, value ? 1 : 0); return this; } public virtual IByteBuf SetByte(int index, int value) { CheckIndex(index); _SetByte(index, value); return this; } protected abstract IByteBuf _SetByte(int index, int value); public virtual IByteBuf SetShort(int index, int value) { CheckIndex(index, 2); _SetShort(index, value); return this; } public IByteBuf SetUnsignedShort(int index, int value) { SetShort(index, value); return this; } protected abstract IByteBuf _SetShort(int index, int value); public virtual IByteBuf SetInt(int index, int value) { CheckIndex(index, 4); _SetInt(index, value); return this; } public IByteBuf SetUnsignedInt(int index, uint value) { unchecked { SetInt(index, (int)value); } return this; } protected abstract IByteBuf _SetInt(int index, int value); public virtual IByteBuf SetLong(int index, long value) { CheckIndex(index, 8); _SetLong(index, value); return this; } protected abstract IByteBuf _SetLong(int index, long value); public virtual IByteBuf SetChar(int index, char value) { SetShort(index, value); return this; } public virtual IByteBuf SetDouble(int index, double value) { SetLong(index, BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuf SetBytes(int index, IByteBuf src) { SetBytes(index, src, src.ReadableBytes); return this; } public virtual IByteBuf SetBytes(int index, IByteBuf src, int length) { CheckIndex(index, length); if(src == null) throw new NullReferenceException("src cannot be null"); if (length > src.ReadableBytes) throw new IndexOutOfRangeException(string.Format( "length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src)); SetBytes(index, src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public abstract IByteBuf SetBytes(int index, IByteBuf src, int srcIndex, int length); public virtual IByteBuf SetBytes(int index, byte[] src) { SetBytes(index, src, 0, src.Length); return this; } public abstract IByteBuf SetBytes(int index, byte[] src, int srcIndex, int length); public virtual bool ReadBoolean() { return ReadByte() != 0; } public virtual byte ReadByte() { CheckReadableBytes(1); var i = ReaderIndex; var b = GetByte(i); ReaderIndex = i + 1; return b; } public virtual short ReadShort() { CheckReadableBytes(2); var v = _GetShort(ReaderIndex); ReaderIndex += 2; return v; } public virtual ushort ReadUnsignedShort() { unchecked { return (ushort)(ReadShort()); } } public virtual int ReadInt() { CheckReadableBytes(4); var v = _GetInt(ReaderIndex); ReaderIndex += 4; return v; } public virtual uint ReadUnsignedInt() { unchecked { return (uint)(ReadInt()); } } public virtual long ReadLong() { CheckReadableBytes(8); var v = _GetLong(ReaderIndex); ReaderIndex += 8; return v; } public virtual char ReadChar() { return (char) ReadShort(); } public virtual double ReadDouble() { return BitConverter.Int64BitsToDouble(ReadLong()); } public virtual IByteBuf ReadBytes(int length) { CheckReadableBytes(length); if (length == 0) return Unpooled.Empty; var buf = Unpooled.Buffer(length, MaxCapacity); buf.WriteBytes(this, ReaderIndex, length); ReaderIndex += length; return buf; } public virtual IByteBuf ReadBytes(IByteBuf destination) { ReadBytes(destination, destination.WritableBytes); return this; } public virtual IByteBuf ReadBytes(IByteBuf destination, int length) { if(length > destination.WritableBytes) throw new IndexOutOfRangeException(string.Format("length({0}) exceeds destination.WritableBytes({1}) where destination is: {2}", length, destination.WritableBytes, destination)); ReadBytes(destination, destination.WriterIndex, length); destination.SetWriterIndex(destination.WriterIndex + length); return this; } public virtual IByteBuf ReadBytes(IByteBuf destination, int dstIndex, int length) { CheckReadableBytes(length); GetBytes(ReaderIndex, destination, dstIndex, length); ReaderIndex += length; return this; } public virtual IByteBuf ReadBytes(byte[] destination) { ReadBytes(destination, 0, destination.Length); return this; } public virtual IByteBuf ReadBytes(byte[] destination, int dstIndex, int length) { CheckReadableBytes(length); GetBytes(ReaderIndex, destination, dstIndex, length); ReaderIndex += length; return this; } public virtual IByteBuf SkipBytes(int length) { CheckReadableBytes(length); var newReaderIndex = ReaderIndex + length; if(newReaderIndex > WriterIndex) throw new IndexOutOfRangeException(string.Format( "length: {0} (expected: readerIndex({1}) + length <= writerIndex({2}))", length, ReaderIndex, WriterIndex)); ReaderIndex = newReaderIndex; return this; } public virtual IByteBuf WriteBoolean(bool value) { WriteByte(value ? 1 : 0); return this; } public virtual IByteBuf WriteByte(int value) { EnsureWritable(1); SetByte(WriterIndex, value); WriterIndex += 1; return this; } public virtual IByteBuf WriteShort(int value) { EnsureWritable(2); _SetShort(WriterIndex, value); WriterIndex += 2; return this; } public IByteBuf WriteUnsignedShort(int value) { throw new NotImplementedException(); } public virtual IByteBuf WriteInt(int value) { EnsureWritable(4); _SetInt(WriterIndex, value); WriterIndex += 4; return this; } public IByteBuf WriteUnsignedInt(uint value) { unchecked { WriteInt((int) value); } return this; } public virtual IByteBuf WriteLong(long value) { EnsureWritable(8); _SetLong(WriterIndex, value); WriterIndex += 8; return this; } public virtual IByteBuf WriteChar(char value) { WriteShort(value); return this; } public virtual IByteBuf WriteDouble(double value) { WriteLong(BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuf WriteBytes(IByteBuf src) { WriteBytes(src, src.ReadableBytes); return this; } public virtual IByteBuf WriteBytes(IByteBuf src, int length) { if (length > src.ReadableBytes) throw new IndexOutOfRangeException(string.Format("length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src)); WriteBytes(src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public virtual IByteBuf WriteBytes(IByteBuf src, int srcIndex, int length) { EnsureWritable(length); SetBytes(WriterIndex, src, srcIndex, length); WriterIndex += length; return this; } public virtual IByteBuf WriteBytes(byte[] src) { WriteBytes(src, 0, src.Length); return this; } public virtual IByteBuf WriteBytes(byte[] src, int srcIndex, int length) { EnsureWritable(length); SetBytes(WriterIndex, src, srcIndex, length); WriterIndex += length; return this; } public abstract bool HasArray { get; } public abstract byte[] InternalArray(); public virtual byte[] ToArray() { if (HasArray) { return InternalArray().Slice(ReaderIndex, ReadableBytes); } var bytes = new byte[ReadableBytes]; GetBytes(ReaderIndex, bytes); return bytes; } public abstract bool IsDirect { get; } public virtual IByteBuf Duplicate() { return new DuplicateByteBuf(this); } public abstract IByteBuf Unwrap(); public abstract ByteBuffer InternalNioBuffer(int index, int length); public abstract IByteBuf Compact(); public abstract IByteBuf CompactIfNecessary(); protected void AdjustMarkers(int decrement) { var markedReaderIndex = _markedReaderIndex; if (markedReaderIndex <= decrement) { _markedReaderIndex = 0; var markedWriterIndex = _markedWriterIndex; if (markedWriterIndex <= decrement) { _markedWriterIndex = 0; } else { _markedWriterIndex = markedWriterIndex - decrement; } } else { _markedReaderIndex = markedReaderIndex - decrement; _markedWriterIndex -= decrement; } } protected void CheckIndex(int index) { EnsureAccessible(); if (index < 0 || index >= Capacity) { throw new IndexOutOfRangeException(string.Format("index: {0} (expected: range(0, {1})", index, Capacity)); } } protected void CheckIndex(int index, int fieldLength) { EnsureAccessible(); if (fieldLength < 0) { throw new IndexOutOfRangeException(string.Format("length: {0} (expected: >= 0)", fieldLength)); } if (index < 0 || index > Capacity - fieldLength) { throw new IndexOutOfRangeException(string.Format("index: {0}, length: {1} (expected: range(0, {2})", index, fieldLength, Capacity)); } } protected void CheckSrcIndex(int index, int length, int srcIndex, int srcCapacity) { CheckIndex(index, length); if (srcIndex < 0 || srcIndex > srcCapacity - length) { throw new IndexOutOfRangeException(string.Format( "srcIndex: {0}, length: {1} (expected: range(0, {2}))", srcIndex, length, srcCapacity)); } } protected void CheckDstIndex(int index, int length, int dstIndex, int dstCapacity) { CheckIndex(index, length); if (dstIndex < 0 || dstIndex > dstCapacity - length) { throw new IndexOutOfRangeException(string.Format( "dstIndex: {0}, length: {1} (expected: range(0, {2}))", dstIndex, length, dstCapacity)); } } /// <summary> /// Throws a <see cref="IndexOutOfRangeException"/> if the current <see cref="ReadableBytes"/> of this buffer /// is less than <see cref="minimumReadableBytes"/>. /// </summary> protected void CheckReadableBytes(int minimumReadableBytes) { EnsureAccessible(); if (minimumReadableBytes < 0) throw new ArgumentOutOfRangeException("minimumReadableBytes", string.Format("minimumReadableBytes: {0} (expected: >= 0)", minimumReadableBytes)); if(ReaderIndex > WriterIndex - minimumReadableBytes) throw new IndexOutOfRangeException(string.Format( "readerIndex({0}) + length({1}) exceeds writerIndex({2}): {3}", ReaderIndex, minimumReadableBytes, WriterIndex, this)); } protected void EnsureAccessible() { //TODO: add reference counting in the future if applicable } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using System; using System.Reflection; using System.Reflection.Emit; using System.Diagnostics; internal enum PostOrPrefix{PostfixDecrement, PostfixIncrement, PrefixDecrement, PrefixIncrement}; public class PostOrPrefixOperator : UnaryOp{ internal MethodInfo operatorMeth; internal PostOrPrefix operatorTok; private Object metaData; private Type type; internal PostOrPrefixOperator(Context context, AST operand) : base(context, operand) { } internal PostOrPrefixOperator(Context context, AST operand, PostOrPrefix operatorTok) : base(context, operand) { this.operatorMeth = null; this.operatorTok = operatorTok; this.metaData = null; this.type = null; } public PostOrPrefixOperator(int operatorTok) : this(null, null, (PostOrPrefix)operatorTok){ } private Object DoOp(int i){ switch (this.operatorTok){ case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: if (i == int.MaxValue) return (double)int.MaxValue + 1.0; return i + 1; default: if (i == int.MinValue) return (double)int.MinValue - 1.0; return i - 1; } } private Object DoOp(uint i){ switch (this.operatorTok){ case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: if (i == uint.MaxValue) return (double)uint.MaxValue + 1.0; return i + 1; default: if (i == uint.MinValue) return (double)uint.MinValue - 1.0; return i - 1; } } private Object DoOp(long i){ switch (this.operatorTok) { case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: if (i == long.MaxValue) return (double)long.MaxValue + 1.0; return i + 1; default: if (i == long.MinValue) return (double)long.MinValue - 1.0; return i - 1; } } private Object DoOp(ulong i){ switch (this.operatorTok) { case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: if (i == ulong.MaxValue) return (double)ulong.MaxValue + 1.0; return i + 1; default: if (i == ulong.MinValue) return (double)ulong.MinValue - 1.0; return i - 1; } } private Object DoOp(double d){ switch (this.operatorTok){ case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: return d+1; default: return d-1; } } internal override Object Evaluate(){ try{ Object oldval = this.operand.Evaluate(); Object newval = this.EvaluatePostOrPrefix(ref oldval); this.operand.SetValue(newval); switch (this.operatorTok){ case PostOrPrefix.PostfixDecrement: case PostOrPrefix.PostfixIncrement: return oldval; case PostOrPrefix.PrefixDecrement: case PostOrPrefix.PrefixIncrement: return newval; default: throw new JScriptException(JSError.InternalError, this.context); } }catch(JScriptException e){ if (e.context == null) e.context = this.context; throw e; }catch(Exception e){ throw new JScriptException(e, this.context); }catch{ throw new JScriptException(JSError.NonClsException, this.context); } } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif public Object EvaluatePostOrPrefix(ref Object v){ int i; uint ui; long l; ulong ul; double d; IConvertible ic = Convert.GetIConvertible(v); switch (Convert.GetTypeCode(v, ic)){ case TypeCode.Empty: v = Double.NaN; return v; case TypeCode.DBNull: v = 0; return this.DoOp(0); case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: v = i = ic.ToInt32(null); return this.DoOp(i); case TypeCode.Char: i = ic.ToInt32(null); return ((IConvertible)this.DoOp(i)).ToChar(null); case TypeCode.UInt32: v = ui = ic.ToUInt32(null); return this.DoOp(ui); case TypeCode.Int64: v = l = ic.ToInt64(null); return this.DoOp(l); case TypeCode.UInt64: v = ul = ic.ToUInt64(null); return this.DoOp(ul); case TypeCode.Single: case TypeCode.Double: v = d = ic.ToDouble(null); return this.DoOp(d); } MethodInfo oper = this.GetOperator(v.GetType()); if (oper != null) return oper.Invoke(null, (BindingFlags)0, JSBinder.ob, new Object[]{v}, null); else{ v = d = Convert.ToNumber(v, ic); return this.DoOp(d); } } private MethodInfo GetOperator(IReflect ir){ Type t = ir is Type ? (Type)ir : Typeob.Object; if (this.type == t) return this.operatorMeth; this.type = t; if (Convert.IsPrimitiveNumericType(t) || Typeob.JSObject.IsAssignableFrom(t)){ this.operatorMeth = null; return null; } switch (this.operatorTok){ case PostOrPrefix.PostfixDecrement: case PostOrPrefix.PrefixDecrement: this.operatorMeth = t.GetMethod("op_Decrement", BindingFlags.Public|BindingFlags.Static, JSBinder.ob, new Type[]{t}, null); break; case PostOrPrefix.PostfixIncrement: case PostOrPrefix.PrefixIncrement: this.operatorMeth = t.GetMethod("op_Increment", BindingFlags.Public|BindingFlags.Static, JSBinder.ob, new Type[]{t}, null); break; default: throw new JScriptException(JSError.InternalError, this.context); } if (this.operatorMeth != null && (!this.operatorMeth.IsStatic || (operatorMeth.Attributes & MethodAttributes.SpecialName) == (MethodAttributes)0 || operatorMeth.GetParameters().Length != 1)) this.operatorMeth = null; if (this.operatorMeth != null) this.operatorMeth = new JSMethodInfo(this.operatorMeth); return this.operatorMeth; } internal override IReflect InferType(JSField inference_target){ Debug.Assert(Globals.TypeRefs.InReferenceContext(this.type)); MethodInfo oper; if (this.type == null || inference_target != null){ oper = this.GetOperator(this.operand.InferType(inference_target)); }else oper = this.GetOperator(this.type); if (oper != null){ this.metaData = oper; return oper.ReturnType; } if (Convert.IsPrimitiveNumericType(this.type)) return this.type; else if (this.type == Typeob.Char) return this.type; else if (Typeob.JSObject.IsAssignableFrom(this.type)) return Typeob.Double; else return Typeob.Object; } internal override AST PartiallyEvaluate(){ this.operand = this.operand.PartiallyEvaluateAsReference(); this.operand.SetPartialValue(this); return this; } private void TranslateToILForNoOverloadCase(ILGenerator il, Type rtype){ Type type = Convert.ToType(this.operand.InferType(null)); this.operand.TranslateToILPreSetPlusGet(il); if (rtype == Typeob.Void){ Type rt = Typeob.Double; if (Convert.IsPrimitiveNumericType(type)) if (type == Typeob.SByte || type == Typeob.Int16) rt = Typeob.Int32; else if (type == Typeob.Byte || type == Typeob.UInt16 || type == Typeob.Char) rt = Typeob.UInt32; else rt = type; Convert.Emit(this, il, type, rt); il.Emit(OpCodes.Ldc_I4_1); Convert.Emit(this, il, Typeob.Int32, rt); if (rt == Typeob.Double || rt == Typeob.Single){ if (this.operatorTok == PostOrPrefix.PostfixDecrement || this.operatorTok == PostOrPrefix.PrefixDecrement){ il.Emit(OpCodes.Sub); }else{ il.Emit(OpCodes.Add); } }else if (rt == Typeob.Int32 || rt == Typeob.Int64){ if (this.operatorTok == PostOrPrefix.PostfixDecrement || this.operatorTok == PostOrPrefix.PrefixDecrement){ il.Emit(OpCodes.Sub_Ovf); }else{ il.Emit(OpCodes.Add_Ovf); } }else{ if (this.operatorTok == PostOrPrefix.PostfixDecrement || this.operatorTok == PostOrPrefix.PrefixDecrement){ il.Emit(OpCodes.Sub_Ovf_Un); }else{ il.Emit(OpCodes.Add_Ovf_Un); } } Convert.Emit(this, il, rt, type); this.operand.TranslateToILSet(il); }else{ //set rt to be the smallest type that is precise enough for the result and the variable Type rt = Typeob.Double; if (Convert.IsPrimitiveNumericType(rtype) && Convert.IsPromotableTo(type, rtype)) rt = rtype; else if (Convert.IsPrimitiveNumericType(type) && Convert.IsPromotableTo(rtype, type)) rt = type; if (rt == Typeob.SByte || rt == Typeob.Int16) rt = Typeob.Int32; else if (rt == Typeob.Byte || rt == Typeob.UInt16 || rt == Typeob.Char) rt = Typeob.UInt32; LocalBuilder result = il.DeclareLocal(rtype); Convert.Emit(this, il, type, rt); if (this.operatorTok == PostOrPrefix.PostfixDecrement){ il.Emit(OpCodes.Dup); if (type == Typeob.Char){ Convert.Emit(this, il, rt, Typeob.Char); Convert.Emit(this, il, Typeob.Char, rtype); }else Convert.Emit(this, il, rt, rtype); il.Emit(OpCodes.Stloc, result); il.Emit(OpCodes.Ldc_I4_1); Convert.Emit(this, il, Typeob.Int32, rt); if (rt == Typeob.Double || rt == Typeob.Single) il.Emit(OpCodes.Sub); else if (rt == Typeob.Int32 || rt == Typeob.Int64) il.Emit(OpCodes.Sub_Ovf); else il.Emit(OpCodes.Sub_Ovf_Un); }else if (this.operatorTok == PostOrPrefix.PostfixIncrement){ il.Emit(OpCodes.Dup); if (type == Typeob.Char){ Convert.Emit(this, il, rt, Typeob.Char); Convert.Emit(this, il, Typeob.Char, rtype); }else Convert.Emit(this, il, rt, rtype); il.Emit(OpCodes.Stloc, result); il.Emit(OpCodes.Ldc_I4_1); Convert.Emit(this, il, Typeob.Int32, rt); if (rt == Typeob.Double || rt == Typeob.Single) il.Emit(OpCodes.Add); else if (rt == Typeob.Int32 || rt == Typeob.Int64) il.Emit(OpCodes.Add_Ovf); else il.Emit(OpCodes.Add_Ovf_Un); }else if (this.operatorTok == PostOrPrefix.PrefixDecrement){ il.Emit(OpCodes.Ldc_I4_1); Convert.Emit(this, il, Typeob.Int32, rt); if (rt == Typeob.Double || rt == Typeob.Single) il.Emit(OpCodes.Sub); else if (rt == Typeob.Int32 || rt == Typeob.Int64) il.Emit(OpCodes.Sub_Ovf); else il.Emit(OpCodes.Sub_Ovf_Un); il.Emit(OpCodes.Dup); if (type == Typeob.Char){ Convert.Emit(this, il, rt, Typeob.Char); Convert.Emit(this, il, Typeob.Char, rtype); } else Convert.Emit(this, il, rt, rtype); il.Emit(OpCodes.Stloc, result); }else{ //if (this.operatorTok == PostOrPrefix.PrefixIncrement) il.Emit(OpCodes.Ldc_I4_1); Convert.Emit(this, il, Typeob.Int32, rt); if (rt == Typeob.Double || rt == Typeob.Single) il.Emit(OpCodes.Add); else if (rt == Typeob.Int32 || rt == Typeob.Int64) il.Emit(OpCodes.Add_Ovf); else il.Emit(OpCodes.Add_Ovf_Un); il.Emit(OpCodes.Dup); if (type == Typeob.Char){ Convert.Emit(this, il, rt, Typeob.Char); Convert.Emit(this, il, Typeob.Char, rtype); } else Convert.Emit(this, il, rt, rtype); il.Emit(OpCodes.Stloc, result); } Convert.Emit(this, il, rt, type); this.operand.TranslateToILSet(il); il.Emit(OpCodes.Ldloc, result); } } internal override void TranslateToIL(ILGenerator il, Type rtype){ if (this.metaData == null){ TranslateToILForNoOverloadCase(il, rtype); return; } if (this.metaData is MethodInfo){ Object result = null; Type type = Convert.ToType(this.operand.InferType(null)); this.operand.TranslateToILPreSetPlusGet(il); if (rtype != Typeob.Void){ result = il.DeclareLocal(rtype); if (this.operatorTok == PostOrPrefix.PostfixDecrement || this.operatorTok == PostOrPrefix.PostfixIncrement){ il.Emit(OpCodes.Dup); Convert.Emit(this, il, type, rtype); il.Emit(OpCodes.Stloc, (LocalBuilder)result); } } MethodInfo oper = (MethodInfo)this.metaData; ParameterInfo[] pars = oper.GetParameters(); Convert.Emit(this, il, type, pars[0].ParameterType); il.Emit(OpCodes.Call, oper); if (rtype != Typeob.Void){ if (this.operatorTok == PostOrPrefix.PrefixDecrement || this.operatorTok == PostOrPrefix.PrefixIncrement){ il.Emit(OpCodes.Dup); Convert.Emit(this, il, type, rtype); il.Emit(OpCodes.Stloc, (LocalBuilder)result); } } Convert.Emit(this, il, oper.ReturnType, type); this.operand.TranslateToILSet(il); if (rtype != Typeob.Void) il.Emit(OpCodes.Ldloc, (LocalBuilder)result); }else{ //Getting here is just too bad. We do not know until the code runs whether or not to call an overloaded operator method. //Compile operands to objects and devolve the decision making to run time thunks Type type = Convert.ToType(this.operand.InferType(null)); LocalBuilder result = il.DeclareLocal(Typeob.Object); this.operand.TranslateToILPreSetPlusGet(il); Convert.Emit(this, il, type, Typeob.Object); il.Emit(OpCodes.Stloc, result); il.Emit(OpCodes.Ldloc, (LocalBuilder)this.metaData); il.Emit(OpCodes.Ldloca, result); il.Emit(OpCodes.Call, CompilerGlobals.evaluatePostOrPrefixOperatorMethod); if (rtype != Typeob.Void){ if (this.operatorTok == PostOrPrefix.PrefixDecrement || this.operatorTok == PostOrPrefix.PrefixIncrement){ il.Emit(OpCodes.Dup); il.Emit(OpCodes.Stloc, result); } } Convert.Emit(this, il, Typeob.Object, type); this.operand.TranslateToILSet(il); if (rtype != Typeob.Void){ il.Emit(OpCodes.Ldloc, result); Convert.Emit(this, il, Typeob.Object, rtype); } } } internal override void TranslateToILInitializer(ILGenerator il){ IReflect rtype = this.InferType(null); this.operand.TranslateToILInitializer(il); if (rtype != Typeob.Object) return; this.metaData = il.DeclareLocal(Typeob.PostOrPrefixOperator); ConstantWrapper.TranslateToILInt(il, (int)this.operatorTok); il.Emit(OpCodes.Newobj, CompilerGlobals.postOrPrefixConstructor); il.Emit(OpCodes.Stloc, (LocalBuilder)this.metaData); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MS.Internal.Xml.XPath; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Xml; using System.Xml.Schema; namespace System.Xml.XPath { // Provides a navigation interface API using XPath data model. [DebuggerDisplay("{debuggerDisplayProxy}")] public abstract class XPathNavigator : XPathItem, IXPathNavigable, IXmlNamespaceResolver { internal static readonly XPathNavigatorKeyComparer comparer = new XPathNavigatorKeyComparer(); //----------------------------------------------- // Object //----------------------------------------------- public override string ToString() { return Value; } //----------------------------------------------- // XPathItem //----------------------------------------------- public override sealed bool IsNode { get { return true; } } public virtual void SetValue(string value) { throw new NotSupportedException(); } public override object TypedValue { get { return Value; } } public virtual void SetTypedValue(object typedValue) { if (typedValue == null) { throw new ArgumentNullException("typedValue"); } switch (NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: break; default: throw new InvalidOperationException(SR.Xpn_BadPosition); } SetValue(XmlUntypedConverter.ToString(typedValue, this)); } public override Type ValueType { get { return typeof(string); } } public override bool ValueAsBoolean { get { return XmlUntypedConverter.ToBoolean(Value); } } public override DateTime ValueAsDateTime { get { return XmlUntypedConverter.ToDateTime(Value); } } public override double ValueAsDouble { get { return XmlUntypedConverter.ToDouble(Value); } } public override int ValueAsInt { get { return XmlUntypedConverter.ToInt32(Value); } } public override long ValueAsLong { get { return XmlUntypedConverter.ToInt64(Value); } } public override object ValueAs(Type returnType, IXmlNamespaceResolver nsResolver) { if (nsResolver == null) { nsResolver = this; } return XmlUntypedConverter.ChangeType(Value, returnType, nsResolver); } //----------------------------------------------- // IXPathNavigable //----------------------------------------------- public virtual XPathNavigator CreateNavigator() { return Clone(); } //----------------------------------------------- // IXmlNamespaceResolver //----------------------------------------------- public abstract XmlNameTable NameTable { get; } public virtual string LookupNamespace(string prefix) { if (prefix == null) return null; if (NodeType != XPathNodeType.Element) { XPathNavigator navSave = Clone(); // If current item is not an element, then try parent if (navSave.MoveToParent()) return navSave.LookupNamespace(prefix); } else if (MoveToNamespace(prefix)) { string namespaceURI = Value; MoveToParent(); return namespaceURI; } // Check for "", "xml", and "xmlns" prefixes if (prefix.Length == 0) return string.Empty; else if (prefix == "xml") return XmlConst.ReservedNsXml; else if (prefix == "xmlns") return XmlConst.ReservedNsXmlNs; return null; } public virtual string LookupPrefix(string namespaceURI) { if (namespaceURI == null) return null; XPathNavigator navClone = Clone(); if (NodeType != XPathNodeType.Element) { // If current item is not an element, then try parent if (navClone.MoveToParent()) return navClone.LookupPrefix(namespaceURI); } else { if (navClone.MoveToFirstNamespace(XPathNamespaceScope.All)) { // Loop until a matching namespace is found do { if (namespaceURI == navClone.Value) return navClone.LocalName; } while (navClone.MoveToNextNamespace(XPathNamespaceScope.All)); } } // Check for default, "xml", and "xmlns" namespaces if (namespaceURI == LookupNamespace(string.Empty)) return string.Empty; else if (namespaceURI == XmlConst.ReservedNsXml) return "xml"; else if (namespaceURI == XmlConst.ReservedNsXmlNs) return "xmlns"; return null; } public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { XPathNodeType nt = NodeType; if ((nt != XPathNodeType.Element && scope != XmlNamespaceScope.Local) || nt == XPathNodeType.Attribute || nt == XPathNodeType.Namespace) { XPathNavigator navSave = Clone(); // If current item is not an element, then try parent if (navSave.MoveToParent()) return navSave.GetNamespacesInScope(scope); } Dictionary<string, string> dict = new Dictionary<string, string>(); // "xml" prefix always in scope if (scope == XmlNamespaceScope.All) dict["xml"] = XmlConst.ReservedNsXml; // Now add all in-scope namespaces if (MoveToFirstNamespace((XPathNamespaceScope)scope)) { do { string prefix = LocalName; string ns = Value; // Exclude xmlns="" declarations unless scope = Local if (prefix.Length != 0 || ns.Length != 0 || scope == XmlNamespaceScope.Local) dict[prefix] = ns; } while (MoveToNextNamespace((XPathNamespaceScope)scope)); MoveToParent(); } return dict; } //----------------------------------------------- // XPathNavigator //----------------------------------------------- // Returns an object of type IKeyComparer. Using this the navigators can be hashed // on the basis of actual position it represents rather than the clr reference of // the navigator object. public static IEqualityComparer NavigatorComparer { get { return comparer; } } public abstract XPathNavigator Clone(); public abstract XPathNodeType NodeType { get; } public abstract string LocalName { get; } public abstract string Name { get; } public abstract string NamespaceURI { get; } public abstract string Prefix { get; } public abstract string BaseURI { get; } public abstract bool IsEmptyElement { get; } public virtual string XmlLang { get { XPathNavigator navClone = Clone(); do { if (navClone.MoveToAttribute("lang", XmlConst.ReservedNsXml)) return navClone.Value; } while (navClone.MoveToParent()); return string.Empty; } } public virtual XmlReader ReadSubtree() { switch (NodeType) { case XPathNodeType.Root: case XPathNodeType.Element: break; default: throw new InvalidOperationException(SR.Xpn_BadPosition); } return CreateReader(); } public virtual void WriteSubtree(XmlWriter writer) { if (null == writer) throw new ArgumentNullException("writer"); writer.WriteNode(this, true); } public virtual object UnderlyingObject { get { return null; } } public virtual bool HasAttributes { get { if (!MoveToFirstAttribute()) return false; MoveToParent(); return true; } } public virtual string GetAttribute(string localName, string namespaceURI) { string value; if (!MoveToAttribute(localName, namespaceURI)) return ""; value = Value; MoveToParent(); return value; } public virtual bool MoveToAttribute(string localName, string namespaceURI) { if (MoveToFirstAttribute()) { do { if (localName == LocalName && namespaceURI == NamespaceURI) return true; } while (MoveToNextAttribute()); MoveToParent(); } return false; } public abstract bool MoveToFirstAttribute(); public abstract bool MoveToNextAttribute(); public virtual string GetNamespace(string name) { string value; if (!MoveToNamespace(name)) { if (name == "xml") return XmlConst.ReservedNsXml; if (name == "xmlns") return XmlConst.ReservedNsXmlNs; return string.Empty; } value = Value; MoveToParent(); return value; } public virtual bool MoveToNamespace(string name) { if (MoveToFirstNamespace(XPathNamespaceScope.All)) { do { if (name == LocalName) return true; } while (MoveToNextNamespace(XPathNamespaceScope.All)); MoveToParent(); } return false; } public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope); public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope); public bool MoveToFirstNamespace() { return MoveToFirstNamespace(XPathNamespaceScope.All); } public bool MoveToNextNamespace() { return MoveToNextNamespace(XPathNamespaceScope.All); } public abstract bool MoveToNext(); public abstract bool MoveToPrevious(); public virtual bool MoveToFirst() { switch (NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: // MoveToFirst should only succeed for content-typed nodes return false; } if (!MoveToParent()) return false; return MoveToFirstChild(); } public abstract bool MoveToFirstChild(); public abstract bool MoveToParent(); public virtual void MoveToRoot() { while (MoveToParent()) ; } public abstract bool MoveTo(XPathNavigator other); public abstract bool MoveToId(string id); public virtual bool MoveToChild(string localName, string namespaceURI) { if (MoveToFirstChild()) { do { if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI) return true; } while (MoveToNext()); MoveToParent(); } return false; } public virtual bool MoveToChild(XPathNodeType type) { if (MoveToFirstChild()) { int mask = XPathNavigatorEx.GetContentKindMask(type); do { if (((1 << (int)NodeType) & mask) != 0) return true; } while (MoveToNext()); MoveToParent(); } return false; } public virtual bool MoveToFollowing(string localName, string namespaceURI) { return MoveToFollowing(localName, namespaceURI, null); } public virtual bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNavigator navSave = Clone(); if (end != null) { switch (end.NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: // Scan until we come to the next content-typed node // after the attribute or namespace node end = end.Clone(); end.MoveToNonDescendant(); break; } } switch (NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: if (!MoveToParent()) { return false; } break; } do { if (!MoveToFirstChild()) { // Look for next sibling while (true) { if (MoveToNext()) break; if (!MoveToParent()) { // Restore previous position and return false MoveTo(navSave); return false; } } } // Have we reached the end of the scan? if (end != null && IsSamePosition(end)) { // Restore previous position and return false MoveTo(navSave); return false; } } while (NodeType != XPathNodeType.Element || localName != LocalName || namespaceURI != NamespaceURI); return true; } public virtual bool MoveToFollowing(XPathNodeType type) { return MoveToFollowing(type, null); } public virtual bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathNavigator navSave = Clone(); int mask = XPathNavigatorEx.GetContentKindMask(type); if (end != null) { switch (end.NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: // Scan until we come to the next content-typed node // after the attribute or namespace node end = end.Clone(); end.MoveToNonDescendant(); break; } } switch (NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: if (!MoveToParent()) { return false; } break; } do { if (!MoveToFirstChild()) { // Look for next sibling while (true) { if (MoveToNext()) break; if (!MoveToParent()) { // Restore previous position and return false MoveTo(navSave); return false; } } } // Have we reached the end of the scan? if (end != null && IsSamePosition(end)) { // Restore previous position and return false MoveTo(navSave); return false; } } while (((1 << (int)NodeType) & mask) == 0); return true; } public virtual bool MoveToNext(string localName, string namespaceURI) { XPathNavigator navClone = Clone(); while (MoveToNext()) { if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI) return true; } MoveTo(navClone); return false; } public virtual bool MoveToNext(XPathNodeType type) { XPathNavigator navClone = Clone(); int mask = XPathNavigatorEx.GetContentKindMask(type); while (MoveToNext()) { if (((1 << (int)NodeType) & mask) != 0) return true; } MoveTo(navClone); return false; } public virtual bool HasChildren { get { if (MoveToFirstChild()) { MoveToParent(); return true; } return false; } } public abstract bool IsSamePosition(XPathNavigator other); public virtual bool IsDescendant(XPathNavigator nav) { if (nav != null) { nav = nav.Clone(); while (nav.MoveToParent()) if (nav.IsSamePosition(this)) return true; } return false; } public virtual XmlNodeOrder ComparePosition(XPathNavigator nav) { if (nav == null) { return XmlNodeOrder.Unknown; } if (IsSamePosition(nav)) return XmlNodeOrder.Same; XPathNavigator n1 = this.Clone(); XPathNavigator n2 = nav.Clone(); int depth1 = GetDepth(n1.Clone()); int depth2 = GetDepth(n2.Clone()); if (depth1 > depth2) { while (depth1 > depth2) { n1.MoveToParent(); depth1--; } if (n1.IsSamePosition(n2)) return XmlNodeOrder.After; } if (depth2 > depth1) { while (depth2 > depth1) { n2.MoveToParent(); depth2--; } if (n1.IsSamePosition(n2)) return XmlNodeOrder.Before; } XPathNavigator parent1 = n1.Clone(); XPathNavigator parent2 = n2.Clone(); while (true) { if (!parent1.MoveToParent() || !parent2.MoveToParent()) return XmlNodeOrder.Unknown; if (parent1.IsSamePosition(parent2)) { if (n1.GetType().ToString() != "Microsoft.VisualStudio.Modeling.StoreNavigator") { Debug.Assert(CompareSiblings(n1.Clone(), n2.Clone()) != CompareSiblings(n2.Clone(), n1.Clone()), "IsSamePosition() on custom navigator returns incosistent results"); } return CompareSiblings(n1, n2); } n1.MoveToParent(); n2.MoveToParent(); } } public virtual XPathExpression Compile(string xpath) { return XPathExpression.Compile(xpath); } public virtual XPathNavigator SelectSingleNode(string xpath) { return SelectSingleNode(XPathExpression.Compile(xpath)); } public virtual XPathNavigator SelectSingleNode(string xpath, IXmlNamespaceResolver resolver) { return SelectSingleNode(XPathExpression.Compile(xpath, resolver)); } public virtual XPathNavigator SelectSingleNode(XPathExpression expression) { XPathNodeIterator iter = this.Select(expression); if (iter.MoveNext()) { return iter.Current; } return null; } public virtual XPathNodeIterator Select(string xpath) { Contract.Ensures(Contract.Result<XPathNodeIterator>() != null); return this.Select(XPathExpression.Compile(xpath)); } public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver resolver) { Contract.Ensures(Contract.Result<XPathNodeIterator>() != null); return this.Select(XPathExpression.Compile(xpath, resolver)); } public virtual XPathNodeIterator Select(XPathExpression expr) { Contract.Ensures(Contract.Result<XPathNodeIterator>() != null); XPathNodeIterator result = Evaluate(expr) as XPathNodeIterator; if (result == null) { throw XPathException.Create(SR.Xp_NodeSetExpected); } return result; } public virtual object Evaluate(string xpath) { return Evaluate(XPathExpression.Compile(xpath), null); } public virtual object Evaluate(string xpath, IXmlNamespaceResolver resolver) { return this.Evaluate(XPathExpression.Compile(xpath, resolver)); } public virtual object Evaluate(XPathExpression expr) { return Evaluate(expr, null); } public virtual object Evaluate(XPathExpression expr, XPathNodeIterator context) { CompiledXpathExpr cexpr = expr as CompiledXpathExpr; if (cexpr == null) { throw XPathException.Create(SR.Xp_BadQueryObject); } Query query = Query.Clone(cexpr.QueryTree); query.Reset(); if (context == null) { context = new XPathSingletonIterator(this.Clone(), /*moved:*/true); } object result = query.Evaluate(context); if (result is XPathNodeIterator) { return new XPathSelectionIterator(context.Current, query); } return result; } public virtual bool Matches(XPathExpression expr) { CompiledXpathExpr cexpr = expr as CompiledXpathExpr; if (cexpr == null) throw XPathException.Create(SR.Xp_BadQueryObject); // We should clone query because some Query.MatchNode() alter expression state and this may brake // SelectionIterators that are runing using this Query // Example of MatchNode() that alret the state is FilterQuery.MatchNode() Query query = Query.Clone(cexpr.QueryTree); try { return query.MatchNode(this) != null; } catch (XPathException) { throw XPathException.Create(SR.Xp_InvalidPattern, cexpr.Expression); } } public virtual bool Matches(string xpath) { return Matches(CompileMatchPattern(xpath)); } public virtual XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathChildIterator(this.Clone(), type); } public virtual XPathNodeIterator SelectChildren(string name, string namespaceURI) { return new XPathChildIterator(this.Clone(), name, namespaceURI); } public virtual XPathNodeIterator SelectAncestors(XPathNodeType type, bool matchSelf) { return new XPathAncestorIterator(this.Clone(), type, matchSelf); } public virtual XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf) { return new XPathAncestorIterator(this.Clone(), name, namespaceURI, matchSelf); } public virtual XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDescendantIterator(this.Clone(), type, matchSelf); } public virtual XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { return new XPathDescendantIterator(this.Clone(), name, namespaceURI, matchSelf); } public virtual bool CanEdit { get { return false; } } public virtual XmlWriter PrependChild() { throw new NotSupportedException(); } public virtual XmlWriter AppendChild() { throw new NotSupportedException(); } public virtual XmlWriter InsertAfter() { throw new NotSupportedException(); } public virtual XmlWriter InsertBefore() { throw new NotSupportedException(); } public virtual XmlWriter CreateAttributes() { throw new NotSupportedException(); } public virtual XmlWriter ReplaceRange(XPathNavigator lastSiblingToReplace) { throw new NotSupportedException(); } public virtual void ReplaceSelf(string newNode) { XmlReader reader = CreateContextReader(newNode, false); ReplaceSelf(reader); } public virtual void ReplaceSelf(XmlReader newNode) { if (newNode == null) { throw new ArgumentNullException("newNode"); } XPathNodeType type = NodeType; if (type == XPathNodeType.Root || type == XPathNodeType.Attribute || type == XPathNodeType.Namespace) { throw new InvalidOperationException(SR.Xpn_BadPosition); } XmlWriter writer = ReplaceRange(this); BuildSubtree(newNode, writer); writer.Dispose(); } public virtual void ReplaceSelf(XPathNavigator newNode) { if (newNode == null) { throw new ArgumentNullException("newNode"); } XmlReader reader = newNode.CreateReader(); ReplaceSelf(reader); } // Returns the markup representing the current node and all of its children. public virtual string OuterXml { get { StringWriter stringWriter; XmlWriterSettings writerSettings; // Attributes and namespaces are not allowed at the top-level by the well-formed writer if (NodeType == XPathNodeType.Attribute) { return string.Concat(Name, "=\"", Value, "\""); } else if (NodeType == XPathNodeType.Namespace) { if (LocalName.Length == 0) return string.Concat("xmlns=\"", Value, "\""); else return string.Concat("xmlns:", LocalName, "=\"", Value, "\""); } stringWriter = new StringWriter(CultureInfo.InvariantCulture); writerSettings = new XmlWriterSettings(); writerSettings.Indent = true; writerSettings.OmitXmlDeclaration = true; writerSettings.ConformanceLevel = ConformanceLevel.Auto; using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings)) { xmlWriter.WriteNode(this, true); } return stringWriter.ToString(); } set { ReplaceSelf(value); } } // Returns the markup representing just the children of the current node. public virtual string InnerXml { get { switch (NodeType) { case XPathNodeType.Root: case XPathNodeType.Element: StringWriter stringWriter; XmlWriterSettings writerSettings; XmlWriter xmlWriter; stringWriter = new StringWriter(CultureInfo.InvariantCulture); writerSettings = new XmlWriterSettings(); writerSettings.Indent = true; writerSettings.OmitXmlDeclaration = true; writerSettings.ConformanceLevel = ConformanceLevel.Auto; xmlWriter = XmlWriter.Create(stringWriter, writerSettings); try { if (MoveToFirstChild()) { do { xmlWriter.WriteNode(this, true); } while (MoveToNext()); // Restore position MoveToParent(); } } finally { xmlWriter.Dispose(); } return stringWriter.ToString(); case XPathNodeType.Attribute: case XPathNodeType.Namespace: return Value; default: return string.Empty; } } set { if (value == null) { throw new ArgumentNullException("value"); } switch (NodeType) { case XPathNodeType.Root: case XPathNodeType.Element: XPathNavigator edit = CreateNavigator(); while (edit.MoveToFirstChild()) { edit.DeleteSelf(); } if (value.Length != 0) { edit.AppendChild(value); } break; case XPathNodeType.Attribute: SetValue(value); break; default: throw new InvalidOperationException(SR.Xpn_BadPosition); } } } public virtual void AppendChild(string newChild) { XmlReader reader = CreateContextReader(newChild, true); AppendChild(reader); } public virtual void AppendChild(XmlReader newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } XmlWriter writer = AppendChild(); BuildSubtree(newChild, writer); writer.Dispose(); } public virtual void AppendChild(XPathNavigator newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); } XmlReader reader = newChild.CreateReader(); AppendChild(reader); } public virtual void PrependChild(string newChild) { XmlReader reader = CreateContextReader(newChild, true); PrependChild(reader); } public virtual void PrependChild(XmlReader newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } XmlWriter writer = PrependChild(); BuildSubtree(newChild, writer); writer.Dispose(); } public virtual void PrependChild(XPathNavigator newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); } XmlReader reader = newChild.CreateReader(); PrependChild(reader); } public virtual void InsertBefore(string newSibling) { XmlReader reader = CreateContextReader(newSibling, false); InsertBefore(reader); } public virtual void InsertBefore(XmlReader newSibling) { if (newSibling == null) { throw new ArgumentNullException("newSibling"); } XmlWriter writer = InsertBefore(); BuildSubtree(newSibling, writer); writer.Dispose(); } public virtual void InsertBefore(XPathNavigator newSibling) { if (newSibling == null) { throw new ArgumentNullException("newSibling"); } if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); } XmlReader reader = newSibling.CreateReader(); InsertBefore(reader); } public virtual void InsertAfter(string newSibling) { XmlReader reader = CreateContextReader(newSibling, false); InsertAfter(reader); } public virtual void InsertAfter(XmlReader newSibling) { if (newSibling == null) { throw new ArgumentNullException("newSibling"); } XmlWriter writer = InsertAfter(); BuildSubtree(newSibling, writer); writer.Dispose(); } public virtual void InsertAfter(XPathNavigator newSibling) { if (newSibling == null) { throw new ArgumentNullException("newSibling"); } if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); } XmlReader reader = newSibling.CreateReader(); InsertAfter(reader); } public virtual void DeleteRange(XPathNavigator lastSiblingToDelete) { throw new NotSupportedException(); } public virtual void DeleteSelf() { DeleteRange(this); } // base for following methods private static void WriteElement(XmlWriter writer, string prefix, string localName, string namespaceURI, string value) { writer.WriteStartElement(prefix, localName, namespaceURI); if (value != null) { writer.WriteString(value); } writer.WriteEndElement(); writer.Dispose(); } public virtual void PrependChildElement(string prefix, string localName, string namespaceURI, string value) { WriteElement(PrependChild(), prefix, localName, namespaceURI, value); } public virtual void AppendChildElement(string prefix, string localName, string namespaceURI, string value) { WriteElement(AppendChild(), prefix, localName, namespaceURI, value); } public virtual void InsertElementBefore(string prefix, string localName, string namespaceURI, string value) { WriteElement(InsertBefore(), prefix, localName, namespaceURI, value); } public virtual void InsertElementAfter(string prefix, string localName, string namespaceURI, string value) { WriteElement(InsertAfter(), prefix, localName, namespaceURI, value); } public virtual void CreateAttribute(string prefix, string localName, string namespaceURI, string value) { XmlWriter writer = CreateAttributes(); writer.WriteStartAttribute(prefix, localName, namespaceURI); if (value != null) { writer.WriteString(value); } writer.WriteEndAttribute(); writer.Dispose(); } //----------------------------------------------- // Internal //----------------------------------------------- internal bool MoveToNonDescendant() { // If current node is document, there is no next non-descendant if (NodeType == XPathNodeType.Root) return false; // If sibling exists, it is the next non-descendant if (MoveToNext()) return true; // The current node is either an attribute, namespace, or last child node XPathNavigator navSave = Clone(); if (!MoveToParent()) return false; switch (navSave.NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Namespace: // Next node in document order is first content-child of parent if (MoveToFirstChild()) return true; break; } while (!MoveToNext()) { if (!MoveToParent()) { // Restore original position and return false MoveTo(navSave); return false; } } return true; } /// <summary> /// Returns ordinal number of attribute, namespace or child node within its parent. /// Order is reversed for attributes and child nodes to avoid O(N**2) running time. /// This property is useful for debugging, and also used in UniqueId implementation. /// </summary> internal uint IndexInParent { get { XPathNavigator nav = this.Clone(); uint idx = 0; switch (NodeType) { case XPathNodeType.Attribute: while (nav.MoveToNextAttribute()) { idx++; } break; case XPathNodeType.Namespace: while (nav.MoveToNextNamespace()) { idx++; } break; default: while (nav.MoveToNext()) { idx++; } break; } return idx; } } internal static readonly char[] NodeTypeLetter = new char[] { 'R', // Root 'E', // Element 'A', // Attribute 'N', // Namespace 'T', // Text 'S', // SignificantWhitespace 'W', // Whitespace 'P', // ProcessingInstruction 'C', // Comment 'X', // All }; internal static readonly char[] UniqueIdTbl = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6' }; // Requirements for id: // 1. must consist of alphanumeric characters only // 2. must begin with an alphabetic character // 3. same id is generated for the same node // 4. ids are unique // // id = node type letter + reverse path to root in terms of encoded IndexInParent integers from node to root seperated by 0's if needed internal virtual string UniqueId { get { XPathNavigator nav = this.Clone(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Ensure distinguishing attributes, namespaces and child nodes sb.Append(NodeTypeLetter[(int)NodeType]); while (true) { uint idx = nav.IndexInParent; if (!nav.MoveToParent()) { break; } if (idx <= 0x1f) { sb.Append(UniqueIdTbl[idx]); } else { sb.Append('0'); do { sb.Append(UniqueIdTbl[idx & 0x1f]); idx >>= 5; } while (idx != 0); sb.Append('0'); } } return sb.ToString(); } } private static XPathExpression CompileMatchPattern(string xpath) { bool hasPrefix; Query query = new QueryBuilder().BuildPatternQuery(xpath, out hasPrefix); return new CompiledXpathExpr(query, xpath, hasPrefix); } private static int GetDepth(XPathNavigator nav) { int depth = 0; while (nav.MoveToParent()) { depth++; } return depth; } // XPath based comparison for namespaces, attributes and other // items with the same parent element. // // n2 // namespace(0) attribute(-1) other(-2) // n1 // namespace(0) ?(0) before(-1) before(-2) // attribute(1) after(1) ?(0) before(-1) // other (2) after(2) after(1) ?(0) private static XmlNodeOrder CompareSiblings(XPathNavigator n1, XPathNavigator n2) { int cmp = 0; #if DEBUG Debug.Assert(!n1.IsSamePosition(n2)); XPathNavigator p1 = n1.Clone(), p2 = n2.Clone(); Debug.Assert(p1.MoveToParent() && p2.MoveToParent() && p1.IsSamePosition(p2)); #endif switch (n1.NodeType) { case XPathNodeType.Namespace: break; case XPathNodeType.Attribute: cmp += 1; break; default: cmp += 2; break; } switch (n2.NodeType) { case XPathNodeType.Namespace: if (cmp == 0) { while (n1.MoveToNextNamespace()) { if (n1.IsSamePosition(n2)) { return XmlNodeOrder.Before; } } } break; case XPathNodeType.Attribute: cmp -= 1; if (cmp == 0) { while (n1.MoveToNextAttribute()) { if (n1.IsSamePosition(n2)) { return XmlNodeOrder.Before; } } } break; default: cmp -= 2; if (cmp == 0) { while (n1.MoveToNext()) { if (n1.IsSamePosition(n2)) { return XmlNodeOrder.Before; } } } break; } return cmp < 0 ? XmlNodeOrder.Before : XmlNodeOrder.After; } internal static bool IsText(XPathNodeType type) { return (uint)(type - XPathNodeType.Text) <= (XPathNodeType.Whitespace - XPathNodeType.Text); } // Lax check for potential child item. private bool IsValidChildType(XPathNodeType type) { switch (NodeType) { case XPathNodeType.Root: switch (type) { case XPathNodeType.Element: case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return true; } break; case XPathNodeType.Element: switch (type) { case XPathNodeType.Element: case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return true; } break; } return false; } // Lax check for potential sibling item. private bool IsValidSiblingType(XPathNodeType type) { switch (NodeType) { case XPathNodeType.Element: case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: switch (type) { case XPathNodeType.Element: case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return true; } break; } return false; } private XmlReader CreateReader() { return XPathNavigatorReader.Create(this); } private XmlReader CreateContextReader(string xml, bool fromCurrentNode) { if (xml == null) { throw new ArgumentNullException("xml"); } // We have to set the namespace context for the reader. XPathNavigator editor = CreateNavigator(); // scope starts from parent. XmlNamespaceManager mgr = new XmlNamespaceManager(NameTable); if (!fromCurrentNode) { editor.MoveToParent(); // should always succeed. } if (editor.MoveToFirstNamespace(XPathNamespaceScope.All)) { do { mgr.AddNamespace(editor.LocalName, editor.Value); } while (editor.MoveToNextNamespace(XPathNamespaceScope.All)); } XmlParserContext context = new XmlParserContext(NameTable, mgr, null, XmlSpace.Default); return XmlReader.Create(new StringReader(xml), new XmlReaderSettings(), context); } internal static void BuildSubtree(XmlReader reader, XmlWriter writer) { // important (perf) string literal... string xmlnsUri = XmlConst.ReservedNsXmlNs; // http://www.w3.org/2000/xmlns/ ReadState readState = reader.ReadState; if (readState != ReadState.Initial && readState != ReadState.Interactive) { throw new ArgumentException(SR.Xml_InvalidOperation, "reader"); } int level = 0; if (readState == ReadState.Initial) { if (!reader.Read()) return; level++; // if start in initial, read everything (not just first) } do { switch (reader.NodeType) { case XmlNodeType.Element: writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); bool isEmptyElement = reader.IsEmptyElement; while (reader.MoveToNextAttribute()) { if ((object)reader.NamespaceURI == (object)xmlnsUri) { if (reader.Prefix.Length == 0) { // Default namespace declaration "xmlns" Debug.Assert(reader.LocalName == "xmlns"); writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value); } else { Debug.Assert(reader.Prefix == "xmlns"); writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value); } } else { writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteString(reader.Value); writer.WriteEndAttribute(); } } reader.MoveToElement(); if (isEmptyElement) { // there might still be a value, if there is a default value specified in the schema writer.WriteEndElement(); } else { level++; } break; case XmlNodeType.EndElement: writer.WriteFullEndElement(); //should not read beyond the level of the reader's original position. level--; break; case XmlNodeType.Text: case XmlNodeType.CDATA: writer.WriteString(reader.Value); break; case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: writer.WriteString(reader.Value); break; case XmlNodeType.Comment: writer.WriteComment(reader.Value); break; case XmlNodeType.ProcessingInstruction: writer.WriteProcessingInstruction(reader.LocalName, reader.Value); break; case XmlNodeType.EntityReference: reader.ResolveEntity(); break; case XmlNodeType.EndEntity: case XmlNodeType.None: case XmlNodeType.DocumentType: case XmlNodeType.XmlDeclaration: break; case XmlNodeType.Attribute: if ((object)reader.NamespaceURI == (object)xmlnsUri) { if (reader.Prefix.Length == 0) { // Default namespace declaration "xmlns" Debug.Assert(reader.LocalName == "xmlns"); writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value); } else { Debug.Assert(reader.Prefix == "xmlns"); writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value); } } else { writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteString(reader.Value); writer.WriteEndAttribute(); } break; } } while (reader.Read() && (level > 0)); } private object debuggerDisplayProxy { get { return new DebuggerDisplayProxy(this); } } [DebuggerDisplay("{ToString()}")] internal struct DebuggerDisplayProxy { XPathNavigator nav; public DebuggerDisplayProxy(XPathNavigator nav) { this.nav = nav; } public override string ToString() { string result = nav.NodeType.ToString(); switch (nav.NodeType) { case XPathNodeType.Element: result += ", Name=\"" + nav.Name + '"'; break; case XPathNodeType.Attribute: case XPathNodeType.Namespace: case XPathNodeType.ProcessingInstruction: result += ", Name=\"" + nav.Name + '"'; result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(nav.Value) + '"'; break; case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.Comment: result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(nav.Value) + '"'; break; } 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.VisualBasic { public enum CallType { Get = 2, Let = 4, Method = 1, Set = 8, } public sealed partial class Collection : System.Collections.ICollection, System.Collections.IList { public Collection() { } public int Count { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public object this[int Index] { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public object this[object Index] { get { throw null; } } public object this[string Key] { get { throw null; } } public void Add(object Item, string Key = null, object Before = null, object After = null) { } public void Clear() { } public bool Contains(string Key) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } public void Remove(int Index) { } public void Remove(string Key) { } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=false, AllowMultiple=false)] public sealed partial class ComClassAttribute : System.Attribute { public ComClassAttribute() { } public ComClassAttribute(string _ClassID) { } public ComClassAttribute(string _ClassID, string _InterfaceID) { } public ComClassAttribute(string _ClassID, string _InterfaceID, string _EventId) { } public string ClassID { get { throw null; } } public string EventID { get { throw null; } } public string InterfaceID { get { throw null; } } public bool InterfaceShadows { get { throw null; } set { } } } public enum CompareMethod { Binary = 0, Text = 1, } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class Constants { internal Constants() { } public const string vbBack = "\b"; public const Microsoft.VisualBasic.CompareMethod vbBinaryCompare = Microsoft.VisualBasic.CompareMethod.Binary; public const string vbCr = "\r"; public const string vbCrLf = "\r\n"; public const string vbFormFeed = "\f"; public const string vbLf = "\n"; [System.ObsoleteAttribute("For a carriage return and line feed, use vbCrLf. For the current platform's newline, use System.Environment.NewLine.")] public const string vbNewLine = "\r\n"; public const string vbNullChar = "\0"; public const string vbNullString = null; public const string vbTab = "\t"; public const Microsoft.VisualBasic.CompareMethod vbTextCompare = Microsoft.VisualBasic.CompareMethod.Text; public const string vbVerticalTab = "\v"; } public sealed partial class ControlChars { public const char Back = '\b'; public const char Cr = '\r'; public const string CrLf = "\r\n"; public const char FormFeed = '\f'; public const char Lf = '\n'; public const string NewLine = "\r\n"; public const char NullChar = '\0'; public const char Quote = '"'; public const char Tab = '\t'; public const char VerticalTab = '\v'; public ControlChars() { } } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class DateAndTime { internal DateAndTime() { } public static System.DateTime Now { get { throw null; } } public static System.DateTime Today { get { throw null; } } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class HideModuleNameAttribute : System.Attribute { public HideModuleNameAttribute() { } } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class Information { internal Information() { } public static bool IsArray(object VarName) { throw null; } public static bool IsDate(object Expression) { throw null; } public static bool IsDBNull(object Expression) { throw null; } public static bool IsError(object Expression) { throw null; } public static bool IsNothing(object Expression) { throw null; } public static bool IsNumeric(object Expression) { throw null; } public static bool IsReference(object Expression) { throw null; } public static int LBound(System.Array Array, int Rank = 1) { throw null; } public static int QBColor(int Color) { throw null; } public static int RGB(int Red, int Green, int Blue) { throw null; } public static string SystemTypeName(string VbName) { throw null; } public static int UBound(System.Array Array, int Rank = 1) { throw null; } public static Microsoft.VisualBasic.VariantType VarType(object VarName) { throw null; } public static string VbTypeName(string UrtName) { throw null; } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public sealed partial class MyGroupCollectionAttribute : System.Attribute { public MyGroupCollectionAttribute(string typeToCollect, string createInstanceMethodName, string disposeInstanceMethodName, string defaultInstanceAlias) { } public string CreateMethod { get { throw null; } } public string DefaultInstanceAlias { get { throw null; } } public string DisposeMethod { get { throw null; } } public string MyGroupName { get { throw null; } } } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class Strings { internal Strings() { } public static int Asc(char String) { throw null; } public static int Asc(string String) { throw null; } public static int AscW(char String) { throw null; } public static int AscW(string String) { throw null; } public static char Chr(int CharCode) { throw null; } public static char ChrW(int CharCode) { throw null; } public static string[] Filter(object[] Source, string Match, bool Include = true, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = (Microsoft.VisualBasic.CompareMethod)(0)) { throw null; } public static string[] Filter(string[] Source, string Match, bool Include = true, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute]Microsoft.VisualBasic.CompareMethod Compare = (Microsoft.VisualBasic.CompareMethod)(0)) { throw null; } public static int InStr(string String1, string String2, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute] CompareMethod Compare = CompareMethod.Binary) { throw null; } public static int InStr(int StartPos, string String1, string String2, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute] CompareMethod Compare = CompareMethod.Binary) { throw null; } public static int InStrRev(string StringCheck, string StringMatch, int Start = -1, [Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute] CompareMethod Compare = CompareMethod.Binary) { throw null; } public static int Len(bool Expression) { throw null; } [System.CLSCompliantAttribute(false)] public static int Len(sbyte Expression) { throw null; } public static int Len(byte Expression) { throw null; } public static int Len(short Expression) { throw null; } [System.CLSCompliantAttribute(false)] public static int Len(ushort Expression) { throw null; } public static int Len(int Expression) { throw null; } [System.CLSCompliantAttribute(false)] public static int Len(uint Expression) { throw null; } public static int Len(long Expression) { throw null; } [System.CLSCompliantAttribute(false)] public static int Len(ulong Expression) { throw null; } public static int Len(decimal Expression) { throw null; } public static int Len(float Expression) { throw null; } public static int Len(double Expression) { throw null; } public static int Len(System.DateTime Expression) { throw null; } public static int Len(char Expression) { throw null; } public static int Len(string Expression) { throw null; } public static int Len(object Expression) { throw null; } public static string Left(string str, int Length) { throw null; } public static string LTrim(string str) { throw null; } public static string Mid(string str, int Start) { throw null; } public static string Mid(string str, int Start, int Length) { throw null; } public static string Right(string str, int Length) { throw null; } public static string RTrim(string str) { throw null; } public static string Trim(string str) { throw null; } } public enum VariantType { Array = 8192, Boolean = 11, Byte = 17, Char = 18, Currency = 6, DataObject = 13, Date = 7, Decimal = 14, Double = 5, Empty = 0, Error = 10, Integer = 3, Long = 20, Null = 1, Object = 9, Short = 2, Single = 4, String = 8, UserDefinedType = 36, Variant = 12, } [System.AttributeUsageAttribute((System.AttributeTargets)(256), Inherited=false, AllowMultiple=false)] public sealed partial class VBFixedArrayAttribute : System.Attribute { public VBFixedArrayAttribute(int UpperBound1) { } public VBFixedArrayAttribute(int UpperBound1, int UpperBound2) { } public int[] Bounds { get { throw null; } } public int Length { get { throw null; } } } [System.AttributeUsageAttribute((System.AttributeTargets)(256), Inherited=false, AllowMultiple=false)] public sealed partial class VBFixedStringAttribute : System.Attribute { public VBFixedStringAttribute(int Length) { } public int Length { get { throw null; } } } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class VBMath { internal VBMath() { } public static void Randomize() { } public static void Randomize(double Number) { } public static float Rnd() { throw null; } public static float Rnd(float Number) { throw null; } } } namespace Microsoft.VisualBasic.ApplicationServices { public partial class StartupEventArgs : System.ComponentModel.CancelEventArgs { public StartupEventArgs(System.Collections.ObjectModel.ReadOnlyCollection<string> args) { } public System.Collections.ObjectModel.ReadOnlyCollection<string> CommandLine { get { throw null; } } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public partial class StartupNextInstanceEventArgs : System.EventArgs { public StartupNextInstanceEventArgs(System.Collections.ObjectModel.ReadOnlyCollection<string> args, bool bringToForegroundFlag) { } public bool BringToForeground { get { throw null; } set { } } public System.Collections.ObjectModel.ReadOnlyCollection<string> CommandLine { get { throw null; } } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public partial class UnhandledExceptionEventArgs : System.Threading.ThreadExceptionEventArgs { public UnhandledExceptionEventArgs(bool exitApplication, System.Exception exception) : base (default(System.Exception)) { } public bool ExitApplication { get { throw null; } set { } } } } namespace Microsoft.VisualBasic.CompilerServices { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Conversions { internal Conversions() { } public static object ChangeType(object Expression, System.Type TargetType) { throw null; } [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackUserDefinedConversion(object Expression, System.Type TargetType) { throw null; } public static string FromCharAndCount(char Value, int Count) { throw null; } public static string FromCharArray(char[] Value) { throw null; } public static string FromCharArraySubset(char[] Value, int StartIndex, int Length) { throw null; } public static bool ToBoolean(object Value) { throw null; } public static bool ToBoolean(string Value) { throw null; } public static byte ToByte(object Value) { throw null; } public static byte ToByte(string Value) { throw null; } public static char ToChar(object Value) { throw null; } public static char ToChar(string Value) { throw null; } public static char[] ToCharArrayRankOne(object Value) { throw null; } public static char[] ToCharArrayRankOne(string Value) { throw null; } public static System.DateTime ToDate(object Value) { throw null; } public static System.DateTime ToDate(string Value) { throw null; } public static decimal ToDecimal(bool Value) { throw null; } public static decimal ToDecimal(object Value) { throw null; } public static decimal ToDecimal(string Value) { throw null; } public static double ToDouble(object Value) { throw null; } public static double ToDouble(string Value) { throw null; } public static T ToGenericParameter<T>(object Value) { throw null; } public static int ToInteger(object Value) { throw null; } public static int ToInteger(string Value) { throw null; } public static long ToLong(object Value) { throw null; } public static long ToLong(string Value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(object Value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string Value) { throw null; } public static short ToShort(object Value) { throw null; } public static short ToShort(string Value) { throw null; } public static float ToSingle(object Value) { throw null; } public static float ToSingle(string Value) { throw null; } public static string ToString(bool Value) { throw null; } public static string ToString(byte Value) { throw null; } public static string ToString(char Value) { throw null; } public static string ToString(System.DateTime Value) { throw null; } public static string ToString(decimal Value) { throw null; } public static string ToString(decimal Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static string ToString(double Value) { throw null; } public static string ToString(double Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static string ToString(short Value) { throw null; } public static string ToString(int Value) { throw null; } public static string ToString(long Value) { throw null; } public static string ToString(object Value) { throw null; } public static string ToString(float Value) { throw null; } public static string ToString(float Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(uint Value) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(ulong Value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInteger(object Value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInteger(string Value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToULong(object Value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToULong(string Value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUShort(object Value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUShort(string Value) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class BooleanType { internal BooleanType() { } public static System.Boolean FromObject(object Value) { throw null; } public static System.Boolean FromString(string Value) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class DecimalType { internal DecimalType() { } public static decimal FromBoolean(bool Value) { throw null; } public static decimal FromObject(object Value) { throw null; } public static decimal FromObject(object Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static decimal FromString(string Value) { throw null; } public static decimal FromString(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static decimal Parse(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple=false, Inherited=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class DesignerGeneratedAttribute : System.Attribute { public DesignerGeneratedAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class DoubleType { internal DoubleType() { } public static double FromObject(object Value) { throw null; } public static double FromObject(object Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static double FromString(string Value) { throw null; } public static double FromString(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } public static double Parse(string Value) { throw null; } public static double Parse(string Value, System.Globalization.NumberFormatInfo NumberFormat) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class IncompleteInitialization : System.Exception { public IncompleteInitialization() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class NewLateBinding { internal NewLateBinding() { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackCall(object Instance, string MemberName, object[] Arguments, string[] ArgumentNames, bool IgnoreReturn) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackGet(object Instance, string MemberName, object[] Arguments, string[] ArgumentNames) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static void FallbackIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static void FallbackIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackInvokeDefault1(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackInvokeDefault2(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static void FallbackSet(object Instance, string MemberName, object[] Arguments) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("do not use this method", true)] public static void FallbackSetComplex(object Instance, string MemberName, object[] Arguments, bool OptimisticSet, bool RValueBase) { } public static object LateCall(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack, bool IgnoreReturn) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public static object LateCallInvokeDefault(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; } public static object LateGet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public static object LateGetInvokeDefault(object Instance, object[] Arguments, string[] ArgumentNames, bool ReportErrors) { throw null; } public static object LateIndexGet(object Instance, object[] Arguments, string[] ArgumentNames) { throw null; } public static void LateIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { } public static void LateIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { } public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments) { } public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase, Microsoft.VisualBasic.CallType CallType) { } public static void LateSetComplex(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase) { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ObjectFlowControl { internal ObjectFlowControl() { } public static void CheckForSyncLockOnValueType(object Expression) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ForLoopControl { internal ForLoopControl() { } public static bool ForLoopInitObj(object Counter, object Start, object Limit, object StepValue, ref object LoopForResult, ref object CounterResult) { throw null; } public static bool ForNextCheckDec(decimal count, decimal limit, decimal StepValue) { throw null; } public static bool ForNextCheckObj(object Counter, object LoopObj, ref object CounterResult) { throw null; } public static bool ForNextCheckR4(float count, float limit, float StepValue) { throw null; } public static bool ForNextCheckR8(double count, double limit, double StepValue) { throw null; } } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Operators { internal Operators() { } public static object AddObject(object Left, object Right) { throw null; } public static object AndObject(object Left, object Right) { throw null; } public static object CompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; } public static object CompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; } public static object CompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; } public static object CompareObjectLess(object Left, object Right, bool TextCompare) { throw null; } public static object CompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; } public static object CompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; } public static int CompareString(string Left, string Right, bool TextCompare) { throw null; } public static object ConcatenateObject(object Left, object Right) { throw null; } public static bool ConditionalCompareObjectEqual(object Left, object Right, bool TextCompare) { throw null; } public static bool ConditionalCompareObjectGreater(object Left, object Right, bool TextCompare) { throw null; } public static bool ConditionalCompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { throw null; } public static bool ConditionalCompareObjectLess(object Left, object Right, bool TextCompare) { throw null; } public static bool ConditionalCompareObjectLessEqual(object Left, object Right, bool TextCompare) { throw null; } public static bool ConditionalCompareObjectNotEqual(object Left, object Right, bool TextCompare) { throw null; } public static object DivideObject(object Left, object Right) { throw null; } public static object ExponentObject(object Left, object Right) { throw null; } [System.ObsoleteAttribute("do not use this method", true)] public static object FallbackInvokeUserDefinedOperator(object vbOp, object[] arguments) { throw null; } public static object IntDivideObject(object Left, object Right) { throw null; } public static object LeftShiftObject(object Operand, object Amount) { throw null; } public static object ModObject(object Left, object Right) { throw null; } public static object MultiplyObject(object Left, object Right) { throw null; } public static object NegateObject(object Operand) { throw null; } public static object NotObject(object Operand) { throw null; } public static object OrObject(object Left, object Right) { throw null; } public static object PlusObject(object Operand) { throw null; } public static object RightShiftObject(object Operand, object Amount) { throw null; } public static object SubtractObject(object Left, object Right) { throw null; } public static object XorObject(object Left, object Right) { throw null; } } [System.AttributeUsageAttribute((System.AttributeTargets)(2048), Inherited=false, AllowMultiple=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class OptionCompareAttribute : System.Attribute { public OptionCompareAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=false, AllowMultiple=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class OptionTextAttribute : System.Attribute { public OptionTextAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ProjectData { internal ProjectData() { } public static void ClearProjectError() { } public static void SetProjectError(System.Exception ex) { } public static void SetProjectError(System.Exception ex, int lErl) { } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited=false, AllowMultiple=false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class StandardModuleAttribute : System.Attribute { public StandardModuleAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class StaticLocalInitFlag { public short State; public StaticLocalInitFlag() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Utils { internal Utils() { } public static System.Array CopyArray(System.Array arySrc, System.Array aryDest) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Versioned { internal Versioned() { } public static bool IsNumeric(object Expression) { throw null; } public static string SystemTypeName(string VbName) { throw null; } public static string VbTypeName(string SystemName) { throw null; } } } namespace Microsoft.VisualBasic.Devices { public partial class NetworkAvailableEventArgs : System.EventArgs { public NetworkAvailableEventArgs(bool networkAvailable) { } public bool IsNetworkAvailable { get { throw null; } } } }
using GuiLabs.Canvas.Shapes; namespace GuiLabs.Canvas.Controls { public class Layouter { #region PutAt /// <summary> /// Moves shapeToMove so that its topleft corner /// corresponds with the topleft corner of reference. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutAt( IDrawableRect reference, IDrawableRect shapeToMove) { PutAt(reference, shapeToMove, 0); } /// <summary> /// Moves shapeToMove so that its topleft corner /// corresponds with the topleft corner of reference. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutAt( IDrawableRect reference, IDrawableRect shapeToMove, int Margin) { shapeToMove.MoveTo( reference.Bounds.Location.X + Margin, reference.Bounds.Location.Y + Margin); } /// <summary> /// Moves shapeToMove so that its topleft corner /// corresponds with the topleft corner of reference. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutAtRight( IDrawableRect reference, IDrawableRect shapeToMove, int Margin) { shapeToMove.MoveTo( reference.Bounds.Location.X + Margin, reference.Bounds.Location.Y); } #endregion #region PutRight /// <summary> /// Puts a shapeToMove to the right from reference. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutRight(IDrawableRect reference, IDrawableRect shapeToMove) { PutRight(reference, shapeToMove, 0); } /// <summary> /// Puts a shapeToMove to the right from reference. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutRight( IDrawableRect reference, IDrawableRect shapeToMove, int Margin) { shapeToMove.MoveTo( reference.Bounds.Right + 1 + Margin, reference.Bounds.Location.Y ); } /// <summary> /// Puts a shapeToMove to the right from reference. /// </summary> /// <param name="xreference"></param> /// <param name="yreference"></param> /// <param name="shapeToMove"></param> public static void PutRight( IDrawableRect xreference, IDrawableRect yreference, IDrawableRect shapeToMove, int Margin) { shapeToMove.MoveTo( xreference.Bounds.Right + 1 + Margin, yreference.Bounds.Location.Y ); } #endregion #region PutUnder /// <summary> /// Moves a shapeToMove so that it is left-aligned with reference /// and is below it. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutUnder( IDrawableRect reference, IDrawableRect shapeToMove ) { PutUnder(reference, shapeToMove, 0); } /// <summary> /// Moves a shapeToMove so that it is left-aligned with reference /// and is below it. /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> public static void PutUnder( IDrawableRect reference, IDrawableRect shapeToMove, int Margin ) { shapeToMove.MoveTo( reference.Bounds.Location.X, reference.Bounds.Bottom + 1 + Margin ); } /// <summary> /// Moves a shapeToMove so that it is left-aligned with reference /// and is below it. /// </summary> /// <param name="xreference"></param> /// <param name="yreference"></param> /// <param name="shapeToMove"></param> public static void PutUnder( IDrawableRect xreference, IDrawableRect yreference, IDrawableRect shapeToMove, int Margin ) { shapeToMove.MoveTo( xreference.Bounds.Location.X, yreference.Bounds.Bottom + 1 + Margin ); } #endregion #region PutUnderAndIndent /// <summary> /// Puts the shapeToMove under reference /// and "indent" pixels to the right /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> /// <param name="indent"></param> public static void PutUnderAndIndent( IDrawableRect reference, IDrawableRect shapeToMove, int indent ) { PutUnderAndIndent(reference, shapeToMove, indent, 0); } /// <summary> /// Puts the shapeToMove under reference /// and "indent" pixels to the right /// </summary> /// <param name="reference"></param> /// <param name="shapeToMove"></param> /// <param name="indent"></param> public static void PutUnderAndIndent( IDrawableRect reference, IDrawableRect shapeToMove, int indent, int margin ) { shapeToMove.MoveTo( reference.Bounds.Location.X + indent, reference.Bounds.Bottom + 1 + margin ); } public static void PutUnderAndIndentFrom( IDrawableRect xReference, IDrawableRect yReference, IDrawableRect shapeToMove, int indent, int margin ) { shapeToMove.MoveTo( xReference.Bounds.Location.X + indent, yReference.Bounds.Bottom + margin ); } #endregion #region PutAround /// <summary> /// Resizes a shapeToResize to be a minimal rectangle /// which fully contains leftTopShape in the top left corner /// and fully contains bottomRightShape in the bottom right corner. /// </summary> public static void PutAround( IDrawableRect leftTopShape, IDrawableRect bottomRightShape, IDrawableRect shapeToResize ) { PutAround(leftTopShape, bottomRightShape, shapeToResize, 0, 0); } /// <summary> /// Resizes a shapeToResize to be a minimal rectangle /// which fully contains leftTopShape in the top left corner /// and fully contains bottomRightShape in the bottom right corner. /// </summary> public static void PutAround( IDrawableRect leftTopShape, IDrawableRect bottomRightShape, IDrawableRect shapeToResize, int xMargin, int yMargin ) { shapeToResize.MoveTo( leftTopShape.Bounds.Location.X - xMargin, leftTopShape.Bounds.Location.Y - yMargin); shapeToResize.Bounds.Size.Set( bottomRightShape.Bounds.Right - leftTopShape.Bounds.Location.X + 2 * xMargin, bottomRightShape.Bounds.Bottom - leftTopShape.Bounds.Location.Y + 2 * yMargin ); } /// <summary> /// Resizes a shapeToResize to be a minimal rectangle /// which fully contains leftTopShape in the top left corner /// and fully contains bottomRightShape in the bottom right corner. /// </summary> public static void PutAround( IDrawableRect leftTopShape, IDrawableRect RightShape, IDrawableRect bottomShape, IDrawableRect shapeToResize, int xMargin, int yMargin ) { shapeToResize.MoveTo( leftTopShape.Bounds.Location.X - xMargin, leftTopShape.Bounds.Location.Y - yMargin); shapeToResize.Bounds.Size.Set( RightShape.Bounds.Right - leftTopShape.Bounds.Location.X + 2 * xMargin, bottomShape.Bounds.Bottom - leftTopShape.Bounds.Location.Y + 2 * yMargin ); } #endregion #region GrowToInclude /// <summary> /// Increases size of shapeToResize, /// so that its right edge and bottom contain containedShape /// </summary> /// <param name="shapeToResize">The shape the size of which to increased.</param> /// <param name="containedShape">The shape to embrace.</param> public static void GrowToInclude( IDrawableRect shapeToResize, IDrawableRect containedShape ) { GrowToInclude(shapeToResize, containedShape, 0, 0); } /// <summary> /// Increases size of shapeToResize, /// so that its right edge and bottom contain containedShape /// </summary> /// <param name="shapeToResize">The shape the size of which to increased.</param> /// <param name="containedShape">The shape to embrace.</param> /// <param name="xMargin">x-Distance between edges of shapes.</param> /// <param name="yMargin">y-Distance between edges of shapes.</param> public static void GrowToInclude( IDrawableRect shapeToResize, IDrawableRect containedShape, int xMargin, int yMargin ) { if (containedShape.Bounds.Bottom + yMargin > shapeToResize.Bounds.Bottom) { shapeToResize.Bounds.Size.Y = containedShape.Bounds.Bottom + yMargin - shapeToResize.Bounds.Location.Y; } if (containedShape.Bounds.Right + xMargin > shapeToResize.Bounds.Right) { shapeToResize.Bounds.Size.X = containedShape.Bounds.Right + xMargin - shapeToResize.Bounds.Location.X; } } #endregion #region MaxChildSizes public static int MaxChildWidth(ContainerControl parent) { int max = 0; foreach (Control child in parent.Children) { if (child.Visible && child.Bounds.Size.X > max) { max = child.Bounds.Size.X; } } return max; } public static int MaxChildHeight(ContainerControl parent) { int max = 0; foreach (Control child in parent.Children) { if (child.Visible && child.Bounds.Size.Y > max) { max = child.Bounds.Size.Y; } } return max; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Management.Automation; using System.Threading; namespace NetworkUtility { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public class UriQueryList : IList<UriQueryItem>, IDictionary<string, string>, IList, IDictionary, INotifyCollectionChanged, INotifyPropertyChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; public event PropertyChangedEventHandler PropertyChanged; public const string PropertyName_Keys = "Keys"; public const string PropertyName_Values = "Values"; public const string PropertyName_Count = "Count"; private static StringComparer _keyComparer = StringComparer.InvariantCultureIgnoreCase; private object _syncRoot = new object(); private int _count = 0; private Collection<UriQueryItem> _allItems = new Collection<UriQueryItem>(); private Collection<int> _keyItemIndexes = new Collection<int>(); private KeyCollection _keys; private ValueCollection _values; private Queue<Tuple<Delegate, object[]>> _queuedEvents = null; public int Count { get { Monitor.Enter(_syncRoot); try { return _count; } finally { Monitor.Exit(_syncRoot); } } } int ICollection<KeyValuePair<string, string>>.Count { get { Monitor.Enter(_syncRoot); try { return _keyItemIndexes.Count; } finally { Monitor.Exit(_syncRoot); } } } bool IList.IsFixedSize { get { return false; } } bool IDictionary.IsFixedSize { get { return false; } } bool ICollection<UriQueryItem>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<string, string>>.IsReadOnly { get { return false; } } bool IList.IsReadOnly { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } bool ICollection.IsSynchronized { get { return true; } } public ICollection<string> Keys { get { return _keys; } } ICollection IDictionary.Keys { get { return _keys; } } object ICollection.SyncRoot { get { return _syncRoot; } } public ICollection<string> Values { get { return _values; } } ICollection IDictionary.Values { get { return _values; } } private T GetSafe<T>(Func<T> func) { return EventQueueManager.Get(_syncRoot, func); } private void InvokeSafe(Action method) { EventQueueManager.Invoke(_syncRoot, method); } public UriQueryItem this[int index] { get { return GetSafe<UriQueryItem>(() => _allItems[index]); } set { if (value == null) throw new ArgumentNullException(); if (index < 0) throw new IndexOutOfRangeException(); InvokeSafe(() => { if (index == _allItems.Count) { Add(value); return; } UriQueryItem oldItem = _allItems[index]; if (ReferenceEquals(oldItem, value)) return; for (int i = 0; i < _allItems.Count; i++) { if (ReferenceEquals(_allItems[i], value)) { MoveItem(i, index); return; } } oldItem.PropertyChanged -= Item_PropertyChanged; _allItems[index] = value; value.PropertyChanged += Item_PropertyChanged; if (_keyComparer.Equals(oldItem.Key, value.Key)) { if (IndexOf(oldItem.Key) == index) { if (oldItem.Key != value.Key) EventQueueManager.Raise(PropertyName_Keys, RaisePropertyChanged); if ((oldItem.Value == null) ? value.Value != null : (value.Value == null || oldItem.Value != value.Value)) EventQueueManager.Raise(PropertyName_Values, RaisePropertyChanged); } } else { int keyIndex = IndexOf(value.Key); if (keyIndex > index) _keyItemIndexes.Remove(keyIndex); else if (keyIndex > -1) _keyItemIndexes.Remove(index); for (int i = index + 1; i < _allItems.Count; i++) { if (_keyComparer.Equals(_allItems[i].Key, oldItem.Key)) { _keyItemIndexes.Add(i); break; } } EventQueueManager.Raise(PropertyName_Keys, RaisePropertyChanged); EventQueueManager.Raise(PropertyName_Values, RaisePropertyChanged); } }); } } object IList.this[int index] { get { return this[index]; } set { this[index] = AssertItemValue(value); } } public string this[string key] { get { if (key == null) return null; return GetSafe<string>(() => { int index = IndexOf(key); if (index < 0) return null; return _allItems[index].Value; }); } set { if (key == null) throw new ArgumentNullException(); InvokeSafe(() => { int index = IndexOf(key); if (index < 0) { index = _allItems.Count; _allItems.Add(new UriQueryItem(key, value)); _keyItemIndexes.Add(index); EventQueueManager.Raise(PropertyName_Keys, RaisePropertyChanged); EventQueueManager.Raise(PropertyName_Values, RaisePropertyChanged); EventQueueManager.Raise(PropertyName_Count, RaisePropertyChanged); } else { UriQueryItem item = _allItems[index]; if ((item.Value == null) ? value == null : value != null && item.Value == value) return; item.Value = value; EventQueueManager.Raise(PropertyName_Values, RaisePropertyChanged); } }); } } object IDictionary.this[object key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public UriQueryList() { _keys = new KeyCollection(this); _values = new ValueCollection(this); } private static UriQueryItem AssertItemValue(object obj) { try { if (!(obj == null || obj is UriQueryItem)) { if (obj is PSObject) return AssertItemValue(((PSObject)obj).BaseObject); if (obj is IConvertible) return (UriQueryItem)(((IConvertible)obj).ToType(typeof(UriQueryItem), System.Globalization.CultureInfo.CurrentCulture)); } } catch { try { return (UriQueryItem)obj; } catch { } throw; } return (UriQueryItem)obj; } private static string AssertStringValue(object obj) { if (obj == null) return null; if (obj is PSObject) return AssertStringValue(((PSObject)obj).BaseObject); if (obj is IConvertible) { try { return (string)(((IConvertible)obj).ToString(System.Globalization.CultureInfo.CurrentCulture)); } catch { try { return (string)obj; } catch { } throw; } } return (string)obj; } private static string AsStringValue(object obj) { if (obj == null) return null; if (obj is PSObject) return AsStringValue(((PSObject)obj).BaseObject); if (obj is IConvertible) { try { return (string)(((IConvertible)obj).ToString(System.Globalization.CultureInfo.CurrentCulture)); } catch { } } try { return (string)obj; } catch { } return obj as string; } private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args) { throw new NotImplementedException(); } private void RaisePropertyChanged(string propertyName) { throw new NotImplementedException(); } public int IndexOf(UriQueryItem item) { throw new NotImplementedException(); } public int IndexOf(string key) { throw new NotImplementedException(); } public void Insert(int index, UriQueryItem item) { throw new NotImplementedException(); } private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e) { throw new NotImplementedException(); } private void MoveItem(int i, int index) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public void Add(UriQueryItem item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(UriQueryItem item) { throw new NotImplementedException(); } public void CopyTo(UriQueryItem[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(UriQueryItem item) { throw new NotImplementedException(); } public IEnumerator<UriQueryItem> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } public bool ContainsKey(string key) { throw new NotImplementedException(); } public void Add(string key, string value) { throw new NotImplementedException(); } public bool Remove(string key) { throw new NotImplementedException(); } public bool TryGetValue(string key, out string value) { throw new NotImplementedException(); } void ICollection<KeyValuePair<string, string>>.Add(KeyValuePair<string, string> item) { throw new NotImplementedException(); } bool ICollection<KeyValuePair<string, string>>.Contains(KeyValuePair<string, string> item) { throw new NotImplementedException(); } void ICollection<KeyValuePair<string, string>>.CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { throw new NotImplementedException(); } bool ICollection<KeyValuePair<string, string>>.Remove(KeyValuePair<string, string> item) { throw new NotImplementedException(); } IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { throw new NotImplementedException(); } int IList.Add(object value) { throw new NotImplementedException(); } bool IList.Contains(object value) { throw new NotImplementedException(); } int IList.IndexOf(object value) { throw new NotImplementedException(); } void IList.Insert(int index, object value) { throw new NotImplementedException(); } void IList.Remove(object value) { throw new NotImplementedException(); } void ICollection.CopyTo(Array array, int index) { throw new NotImplementedException(); } bool IDictionary.Contains(object key) { throw new NotImplementedException(); } void IDictionary.Add(object key, object value) { throw new NotImplementedException(); } IDictionaryEnumerator IDictionary.GetEnumerator() { throw new NotImplementedException(); } void IDictionary.Remove(object key) { throw new NotImplementedException(); } #warning Not implemented public int CompareTo(UriQueryList other) { throw new NotImplementedException(); } public int CompareTo(object obj) { return CompareTo(obj as UriQueryList); } public bool Equals(UriQueryList other) { throw new NotImplementedException(); } public override bool Equals(object obj) { return Equals(obj as UriQueryList); } public override int GetHashCode() { return ToString().GetHashCode(); } public override string ToString() { Monitor.Enter(_syncRoot); try { throw new NotImplementedException(); } finally { Monitor.Exit(_syncRoot); } } class KeyCollection : ICollection<string>, ICollection { private object _syncRoot; UriQueryList _parent; internal KeyCollection(UriQueryList parent) { _parent = parent; _syncRoot = parent._syncRoot; } public int Count { get { Monitor.Enter(_syncRoot); try { return _parent._keyItemIndexes.Count; } finally { Monitor.Exit(_syncRoot); } } } bool ICollection<string>.IsReadOnly { get { return true; } } object ICollection.SyncRoot { get { return _syncRoot; } } bool ICollection.IsSynchronized { get { return true; } } void ICollection<string>.Add(string item) { throw new NotSupportedException(); } void ICollection<string>.Clear() { throw new NotSupportedException(); } public bool Contains(string item) { if (item == null) return false; Monitor.Enter(_syncRoot); try { return GetKeys().Any(k => _keyComparer.Equals(item, k)); } finally { Monitor.Exit(_syncRoot); } } void ICollection<string>.CopyTo(string[] array, int arrayIndex) { GetKeys().ToList().CopyTo(array, arrayIndex); } void ICollection.CopyTo(Array array, int index) { GetKeys().ToArray().CopyTo(array, index); } public IEnumerator<string> GetEnumerator() { Monitor.Enter(_syncRoot); try { return GetKeys().GetEnumerator(); } finally { Monitor.Exit(_syncRoot); } } IEnumerator IEnumerable.GetEnumerator() { return GetKeys().ToArray().GetEnumerator(); } private IEnumerable<string> GetKeys() { foreach (int index in _parent._keyItemIndexes) yield return _parent._allItems[index].Key; } bool ICollection<string>.Remove(string item) { throw new NotSupportedException(); } } class ValueCollection : ICollection<string>, ICollection { private object _syncRoot; UriQueryList _parent; internal ValueCollection(UriQueryList parent) { _parent = parent; _syncRoot = parent._syncRoot; } public int Count { get { Monitor.Enter(_syncRoot); try { return _parent._keyItemIndexes.Count; } finally { Monitor.Exit(_syncRoot); } } } bool ICollection<string>.IsReadOnly { get { return true; } } object ICollection.SyncRoot { get { return _syncRoot; } } bool ICollection.IsSynchronized { get { return true; } } void ICollection<string>.Add(string item) { throw new NotSupportedException(); } void ICollection<string>.Clear() { throw new NotSupportedException(); } public bool Contains(string item) { Monitor.Enter(_syncRoot); try { if (item == null) return GetValues().Any(v => v == null); return GetValues().Any(v => v != null && v == item); } finally { Monitor.Exit(_syncRoot); } } void ICollection<string>.CopyTo(string[] array, int arrayIndex) { GetValues().ToList().CopyTo(array, arrayIndex); } void ICollection.CopyTo(Array array, int index) { GetValues().ToArray().CopyTo(array, index); } public IEnumerator<string> GetEnumerator() { Monitor.Enter(_syncRoot); try { return GetValues().GetEnumerator(); } finally { Monitor.Exit(_syncRoot); } } IEnumerator IEnumerable.GetEnumerator() { return GetValues().ToArray().GetEnumerator(); } private IEnumerable<string> GetValues() { foreach (int index in _parent._keyItemIndexes) yield return _parent._allItems[index].Value; } bool ICollection<string>.Remove(string item) { throw new NotSupportedException(); } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using System; using System.Collections.Generic; using System.Text; using System.Threading; using NLog.Internal; using NLog.Internal.Pooling; using NLog.Internal.Pooling.Pools; namespace NLog.Common { /// <summary> /// Helpers for asynchronous operations. /// </summary> public static class AsyncHelpers { /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { ForEachItemInParallel(null, items, asyncContinuation, action); } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="configuration">The logging configuration.</param> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially<T>(LoggingConfiguration configuration, IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; IEnumerator<T> enumerator = items.GetEnumerator(); invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (!enumerator.MoveNext()) { asyncContinuation(null); return; } action(enumerator.Current, PreventMultipleCalls(configuration, invokeNext)); }; invokeNext(null); } /// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { Repeat(null, repeatCount, asyncContinuation, action); } /// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="loggingConfiguration">The logging configuration.</param> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(LoggingConfiguration loggingConfiguration, int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; int remaining = repeatCount; invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (remaining-- <= 0) { asyncContinuation(null); return; } action(PreventMultipleCalls(loggingConfiguration,invokeNext)); }; invokeNext(null); } /// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { return PrecededBy(null, asyncContinuation, action); } /// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="loggingConfiguration">The logging configuration.</param> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(LoggingConfiguration loggingConfiguration, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation continuation = ex => { if (ex != null) { // if got exception from from original invocation, don't execute action asyncContinuation(ex); return; } // call the action and continue action(PreventMultipleCalls(loggingConfiguration, asyncContinuation)); }; return continuation; } /// <summary> /// Attaches a timeout to a continuation which will invoke the continuation when the specified /// timeout has elapsed. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">The timeout.</param> /// <returns>Wrapped continuation.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Continuation will be disposed of elsewhere.")] public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout) { return new TimeoutContinuation(asyncContinuation, timeout).Function; } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel<T>(IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { ForEachItemInParallel(null, values, asyncContinuation, action); } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="configuration">The logging configuration</param> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel<T>(LoggingConfiguration configuration, IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); var items = new List<T>(values); int remaining = items.Count; var exceptions = new List<Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); int r; if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r.AsString()); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (T item in items) { T itemCopy = item; ThreadPool.QueueUserWorkItem(s => action(itemCopy, PreventMultipleCalls(configuration,continuation))); } } /// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(AsynchronousAction action) { RunSynchronously(null, action); } /// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="loggingConfiguration"></param> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(LoggingConfiguration loggingConfiguration, AsynchronousAction action) { var ev = new ManualResetEvent(false); Exception lastException = null; action(PreventMultipleCalls(loggingConfiguration, ex => { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } } /// <summary> /// Wraps the continuation with a guard which will only make sure that the continuation function /// is invoked only once. /// Please only call this from unit tests, since it will not pool objects. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Wrapped asynchronous continuation.</returns> public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation) { return PreventMultipleCalls(null, asyncContinuation); } /// <summary> /// Wraps the continuation with a guard which will only make sure that the continuation function /// is invoked only once. /// </summary> /// <param name="configuration">The configuration to use for pooling</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Wrapped asynchronous continuation.</returns> public static AsyncContinuation PreventMultipleCalls(LoggingConfiguration configuration, AsyncContinuation asyncContinuation) { if (asyncContinuation == null) { throw new ArgumentNullException("asyncContinuation"); } if (asyncContinuation.Target is SingleCallContinuation) { return asyncContinuation; } if (configuration.PoolingEnabled()) { return configuration.PoolFactory.Get<SingleCallContinuationPool,SingleCallContinuation>().Get(asyncContinuation).Delegate; } return new SingleCallContinuation(asyncContinuation).Delegate; } /// <summary> /// Gets the combined exception from all exceptions in the list. /// </summary> /// <param name="exceptions">The exceptions.</param> /// <returns>Combined exception or null if no exception was thrown.</returns> public static Exception GetCombinedException(IList<Exception> exceptions) { if (exceptions == null) { return null; } if (exceptions.Count == 0) { return null; } if (exceptions.Count == 1) { return exceptions[0]; } var sb = new StringBuilder(); string separator = string.Empty; string newline = EnvironmentHelper.NewLine; foreach (var ex in exceptions) { sb.Append(separator); sb.Append(ex.ToString()); sb.Append(newline); separator = newline; } return new NLogRuntimeException("Got multiple exceptions:\r\n" + sb); } internal static Exception GetCombinedException(params Exception[] exceptions) { return new CombinedException(exceptions); } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { return cont => { try { action(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } private static AsynchronousAction<T> ExceptionGuard<T>(AsynchronousAction<T> action) { return (T argument, AsyncContinuation cont) => { try { action(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using AutoMapper.Internal; using AutoMapper.Configuration.Internal; namespace AutoMapper.Configuration { using static Expression; public class MappingExpression : MappingExpression<object, object>, IMappingExpression { public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types.SourceType, types.DestinationType) { } public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap(); public IMappingExpression Substitute(Func<object, object> substituteFunc) => (IMappingExpression) base.Substitute(substituteFunc); public new IMappingExpression ConstructUsingServiceLocator() => (IMappingExpression)base.ConstructUsingServiceLocator(); public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions) => base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts)); void IMappingExpression.ConvertUsing<TTypeConverter>() => ConvertUsing(typeof(TTypeConverter)); public void ConvertUsing(Type typeConverterType) => TypeMapActions.Add(tm => tm.TypeConverterType = typeConverterType); public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions) => base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o)); public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) => (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c)); public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) => (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions); public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType) => (IMappingExpression)base.Include(otherSourceType, otherDestinationType); public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter() => (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter(); public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter() => (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase) => (IMappingExpression)base.IncludeBase(sourceBase, destinationBase); public new IMappingExpression BeforeMap(Action<object, object> beforeFunction) => (IMappingExpression)base.BeforeMap(beforeFunction); public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> => (IMappingExpression)base.BeforeMap<TMappingAction>(); public new IMappingExpression AfterMap(Action<object, object> afterFunction) => (IMappingExpression)base.AfterMap(afterFunction); public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> => (IMappingExpression)base.AfterMap<TMappingAction>(); public new IMappingExpression ConstructUsing(Func<object, object> ctor) => (IMappingExpression)base.ConstructUsing(ctor); public new IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor) => (IMappingExpression)base.ConstructUsing(ctor); public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor) { TypeMapActions.Add(tm => tm.ConstructExpression = ctor); return this; } public new IMappingExpression MaxDepth(int depth) => (IMappingExpression)base.MaxDepth(depth); public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions) => (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions); public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences(); protected override IPropertyMapConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType) => new MemberConfigurationExpression(member, sourceType); protected override MappingExpression<object, object> CreateReverseMapExpression() => new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source); internal class MemberConfigurationExpression : MemberConfigurationExpression<object, object, object>, IMemberConfigurationExpression { public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType) : base(destinationMember, sourceType) { } public void ResolveUsing(Type valueResolverType) { var config = new ValueResolverConfiguration(valueResolverType, valueResolverType.GetGenericInterface(typeof(IValueResolver<,,>))); PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing(Type valueResolverType, string memberName) { var config = new ValueResolverConfiguration(valueResolverType, valueResolverType.GetGenericInterface(typeof(IMemberValueResolver<,,,>))) { SourceMemberName = memberName }; PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing<TSource, TDestination, TSourceMember, TDestMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember> resolver, string memberName) { var config = new ValueResolverConfiguration(resolver, typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember>)) { SourceMemberName = memberName }; PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } } } public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration { private readonly List<IPropertyMapConfiguration> _memberConfigurations = new List<IPropertyMapConfiguration>(); private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>(); private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>(); private MappingExpression<TDestination, TSource> _reverseMap; private Action<IMemberConfigurationExpression<TSource, TDestination, object>> _allMemberOptions; private Func<MemberInfo, bool> _memberFilter; public MappingExpression(MemberList memberList) : this(memberList, typeof(TSource), typeof(TDestination)) { } public MappingExpression(MemberList memberList, Type sourceType, Type destinationType) { MemberList = memberList; Types = new TypePair(sourceType, destinationType); IsOpenGeneric = sourceType.IsGenericTypeDefinition() || destinationType.IsGenericTypeDefinition(); } public MemberList MemberList { get; } public TypePair Types { get; } public Type SourceType => Types.SourceType; public Type DestinationType => Types.DestinationType; public bool IsOpenGeneric { get; } public ITypeMapConfiguration ReverseTypeMap => _reverseMap; protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>(); public IMappingExpression<TSource, TDestination> PreserveReferences() { TypeMapActions.Add(tm => tm.PreserveReferences = true); return this; } protected virtual IPropertyMapConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType) => new MemberConfigurationExpression<TSource, TDestination, TMember>(member, sourceType); protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression() => new MappingExpression<TDestination, TSource>(MemberList.None, DestinationType, SourceType); public IMappingExpression<TSource, TDestination> ForPath<TMember>(Expression<Func<TDestination, TMember>> destinationMember, Action<IPathConfigurationExpression<TSource, TDestination>> memberOptions) { if(!destinationMember.IsMemberPath()) { throw new ArgumentOutOfRangeException(nameof(destinationMember), "Only member accesses are allowed."); } var expression = new PathConfigurationExpression<TSource, TDestination>(destinationMember); var firstMember = expression.MemberPath.First; var firstMemberConfig = GetDestinationMemberConfiguration(firstMember); if(firstMemberConfig == null) { IgnoreDestinationMember(firstMember, ignorePaths: false); } _memberConfigurations.Add(expression); memberOptions(expression); return this; } public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember, Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(destinationMember); return ForDestinationMember(memberInfo, memberOptions); } public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions) { var member = DestinationType.GetFieldOrProperty(name); return ForDestinationMember(member, memberOptions); } public void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions) { _allMemberOptions = memberOptions; _memberFilter = m => GetDestinationMemberConfiguration(m) == null; } public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions) { _allMemberOptions = memberOptions; _memberFilter = _ => true; } public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter() { foreach(var property in DestinationType.PropertiesWithAnInaccessibleSetter()) { IgnoreDestinationMember(property); } return this; } private void IgnoreDestinationMember(MemberInfo property, bool ignorePaths = true) => ForDestinationMember<object>(property, options => options.Ignore(ignorePaths)); public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { foreach(var property in SourceType.PropertiesWithAnInaccessibleSetter()) { ForSourceMember(property.Name, options => options.Ignore()); } return this; } public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination => IncludeCore(typeof(TOtherSource), typeof(TOtherDestination)); public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType) { CheckIsDerived(otherSourceType, typeof(TSource)); CheckIsDerived(otherDestinationType, typeof(TDestination)); return IncludeCore(otherSourceType, otherDestinationType); } IMappingExpression<TSource, TDestination> IncludeCore(Type otherSourceType, Type otherDestinationType) { TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType)); return this; } public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>() => IncludeBase(typeof(TSourceBase), typeof(TDestinationBase)); public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase) { CheckIsDerived(typeof(TSource), sourceBase); CheckIsDerived(typeof(TDestination), destinationBase); TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase)); return this; } public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression) { TypeMapActions.Add(tm => tm.CustomProjection = projectionExpression); } public IMappingExpression<TSource, TDestination> MaxDepth(int depth) { TypeMapActions.Add(tm => tm.MaxDepth = depth); return PreserveReferences(); } public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator() { TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true); return this; } public IMappingExpression<TDestination, TSource> ReverseMap() { _reverseMap = CreateReverseMapExpression(); _reverseMap._memberConfigurations.AddRange(_memberConfigurations.Select(m => m.Reverse()).Where(m=>m!=null)); return _reverseMap; } public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(sourceMember); var srcConfig = new SourceMappingExpression(memberInfo); memberOptions(srcConfig); _sourceMemberConfigurations.Add(srcConfig); return this; } public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = SourceType.GetFieldOrProperty(sourceMemberName); var srcConfig = new SourceMappingExpression(memberInfo); memberOptions(srcConfig); _sourceMemberConfigurations.Add(srcConfig); return this; } public IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc) { TypeMapActions.Add(tm => { Expression<Func<TSource, TDestination, ResolutionContext, TSubstitute>> expr = (src, dest, ctxt) => substituteFunc(src); tm.Substitution = expr; }); return this; } public void ConvertUsing(Func<TSource, TDestination> mappingFunction) { TypeMapActions.Add(tm => { Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr = (src, dest, ctxt) => mappingFunction(src); tm.CustomMapper = expr; }); } public void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction) { TypeMapActions.Add(tm => { Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr = (src, dest, ctxt) => mappingFunction(src, dest); tm.CustomMapper = expr; }); } public void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction) { TypeMapActions.Add(tm => { Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr = (src, dest, ctxt) => mappingFunction(src, dest, ctxt); tm.CustomMapper = expr; }); } public void ConvertUsing(ITypeConverter<TSource, TDestination> converter) { ConvertUsing(converter.Convert); } public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination> { TypeMapActions.Add(tm => tm.TypeConverterType = typeof (TTypeConverter)); } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction) { TypeMapActions.Add(tm => { Expression<Action<TSource, TDestination, ResolutionContext>> expr = (src, dest, ctxt) => beforeFunction(src, dest); tm.AddBeforeMapAction(expr); }); return this; } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction) { TypeMapActions.Add(tm => { Expression<Action<TSource, TDestination, ResolutionContext>> expr = (src, dest, ctxt) => beforeFunction(src, dest, ctxt); tm.AddBeforeMapAction(expr); }); return this; } public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { void BeforeFunction(TSource src, TDestination dest, ResolutionContext ctxt) => ((TMappingAction) ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest); return BeforeMap(BeforeFunction); } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction) { TypeMapActions.Add(tm => { Expression<Action<TSource, TDestination, ResolutionContext>> expr = (src, dest, ctxt) => afterFunction(src, dest); tm.AddAfterMapAction(expr); }); return this; } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction) { TypeMapActions.Add(tm => { Expression<Action<TSource, TDestination, ResolutionContext>> expr = (src, dest, ctxt) => afterFunction(src, dest, ctxt); tm.AddAfterMapAction(expr); }); return this; } public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { void AfterFunction(TSource src, TDestination dest, ResolutionContext ctxt) => ((TMappingAction) ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest); return AfterMap(AfterFunction); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor) { TypeMapActions.Add(tm => { Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src); tm.DestinationCtor = expr; }); return this; } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor) { TypeMapActions.Add(tm => { Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src, ctxt); tm.DestinationCtor = expr; }); return this; } public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor) { TypeMapActions.Add(tm => { tm.ConstructExpression = ctor; var ctxtParam = Parameter(typeof (ResolutionContext), "ctxt"); var srcParam = Parameter(typeof (TSource), "src"); var body = ctor.ReplaceParameters(srcParam); tm.DestinationCtor = Lambda(body, srcParam, ctxtParam); }); return this; } private IMappingExpression<TSource, TDestination> ForDestinationMember<TMember>(MemberInfo destinationProperty, Action<MemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions) { var expression = (MemberConfigurationExpression<TSource, TDestination, TMember>) CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType); _memberConfigurations.Add(expression); memberOptions(expression); return this; } public void As<T>() where T : TDestination => As(typeof(T)); public void As(Type typeOverride) { CheckIsDerived(typeOverride, DestinationType); TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride); } private void CheckIsDerived(Type derivedType, Type baseType) { if(!baseType.IsAssignableFrom(derivedType) && !derivedType.IsGenericTypeDefinition() && !baseType.IsGenericTypeDefinition()) { throw new ArgumentOutOfRangeException(nameof(derivedType), $"{derivedType} is not derived from {baseType}."); } } public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions) { var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName); paramOptions(ctorParamExpression); _ctorParamConfigurations.Add(ctorParamExpression); return this; } public IMappingExpression<TSource, TDestination> DisableCtorValidation() { TypeMapActions.Add(tm => { tm.DisableConstructorValidation = true; }); return this; } private IPropertyMapConfiguration GetDestinationMemberConfiguration(MemberInfo destinationMember) => _memberConfigurations.FirstOrDefault(m => m.DestinationMember == destinationMember); public void Configure(TypeMap typeMap) { foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors) { var attrs = destProperty.GetCustomAttributes(true); if (attrs.Any(x => x is IgnoreMapAttribute)) { IgnoreDestinationMember(destProperty); var sourceProperty = typeMap.SourceType.GetInheritedMember(destProperty.Name); if (sourceProperty != null) { _reverseMap?.IgnoreDestinationMember(sourceProperty); } } if (typeMap.Profile.GlobalIgnores.Contains(destProperty.Name) && GetDestinationMemberConfiguration(destProperty) == null) { IgnoreDestinationMember(destProperty); } } if (_allMemberOptions != null) { foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Where(_memberFilter)) { ForDestinationMember(accessor, _allMemberOptions); } } foreach (var action in TypeMapActions) { action(typeMap); } foreach (var memberConfig in _memberConfigurations) { memberConfig.Configure(typeMap); } foreach (var memberConfig in _sourceMemberConfigurations) { memberConfig.Configure(typeMap); } foreach (var paramConfig in _ctorParamConfigurations) { paramConfig.Configure(typeMap); } if (_reverseMap != null) { ReverseSourceMembers(typeMap); foreach(var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.Ignored)) { _reverseMap.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore()); } foreach(var includedDerivedType in typeMap.IncludedDerivedTypes) { _reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType); } foreach(var includedBaseType in typeMap.IncludedBaseTypes) { _reverseMap.IncludeBase(includedBaseType.DestinationType, includedBaseType.SourceType); } } } private void ReverseSourceMembers(TypeMap typeMap) { foreach(var propertyMap in typeMap.GetPropertyMaps().Where(p => p.SourceMembers.Count > 1 && !p.SourceMembers.Any(s=>s is MethodInfo))) { _reverseMap.TypeMapActions.Add(reverseTypeMap => { var memberPath = new MemberPath(propertyMap.SourceMembers); var newDestination = Parameter(reverseTypeMap.DestinationType, "destination"); var path = propertyMap.SourceMembers.MemberAccesses(newDestination); var forPathLambda = Lambda(path, newDestination); var pathMap = reverseTypeMap.FindOrCreatePathMapFor(forPathLambda, memberPath, reverseTypeMap); var newSource = Parameter(reverseTypeMap.SourceType, "source"); pathMap.SourceExpression = Lambda(MakeMemberAccess(newSource, propertyMap.DestinationProperty), newSource); }); } } } }
// // SqlInt16Test.cs - NUnit Test Cases for System.Data.SqlTypes.SqlInt16 // // Authors: // Ville Palo ([email protected]) // Martin Willemoes Hansen ([email protected]) // // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // // // 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 NUnit.Framework; using System; using System.Data.SqlTypes; namespace MonoTests.System.Data.SqlTypes { [TestFixture] public class SqlInt16Test : Assertion { // Test constructor [Test] public void Create() { SqlInt16 TestShort = new SqlInt16 (29); AssertEquals ("Test#1", (short)29, TestShort.Value); TestShort = new SqlInt16 (-9000); AssertEquals ("Test#2", (short)-9000, TestShort.Value); } // Test public fields [Test] public void PublicFields() { AssertEquals ("Test#1", (SqlInt16)32767, SqlInt16.MaxValue); AssertEquals ("Test#2", (SqlInt16)(-32768), SqlInt16.MinValue); Assert ("Test#3", SqlInt16.Null.IsNull); AssertEquals ("Test#4", (short)0, SqlInt16.Zero.Value); } // Test properties [Test] public void Properties() { SqlInt16 Test5443 = new SqlInt16 (5443); SqlInt16 Test1 = new SqlInt16 (1); Assert ("Test#1", SqlInt16.Null.IsNull); AssertEquals ("Test#2", (short)5443, Test5443.Value); AssertEquals ("Test#3", (short)1, Test1.Value); } // PUBLIC METHODS [Test] public void ArithmeticMethods() { SqlInt16 Test64 = new SqlInt16 (64); SqlInt16 Test0 = new SqlInt16 (0); SqlInt16 Test164 = new SqlInt16 (164); SqlInt16 TestMax = new SqlInt16 (SqlInt16.MaxValue.Value); // Add() AssertEquals ("Test#1", (short)64, SqlInt16.Add (Test64, Test0).Value); AssertEquals ("Test#2", (short)228, SqlInt16.Add (Test64, Test164).Value); AssertEquals ("Test#3", (short)164, SqlInt16.Add (Test0, Test164).Value); AssertEquals ("Test#4", (short)SqlInt16.MaxValue, SqlInt16.Add (TestMax, Test0).Value); try { SqlInt16.Add (TestMax, Test64); Fail ("Test#5"); } catch (Exception e) { AssertEquals ("Test#6", typeof (OverflowException), e.GetType ()); } // Divide() AssertEquals ("Test#7", (short)2, SqlInt16.Divide (Test164, Test64).Value); AssertEquals ("Test#8", (short)0, SqlInt16.Divide (Test64, Test164).Value); try { SqlInt16.Divide(Test64, Test0); Fail ("Test#9"); } catch(Exception e) { AssertEquals ("Test#10", typeof (DivideByZeroException), e.GetType ()); } // Mod() AssertEquals ("Test#11", (SqlInt16)36, SqlInt16.Mod (Test164, Test64)); AssertEquals ("Test#12", (SqlInt16)64, SqlInt16.Mod (Test64, Test164)); // Multiply() AssertEquals ("Test#13", (short)10496, SqlInt16.Multiply (Test64, Test164).Value); AssertEquals ("Test#14", (short)0, SqlInt16.Multiply (Test64, Test0).Value); try { SqlInt16.Multiply (TestMax, Test64); Fail ("Test#15"); } catch(Exception e) { AssertEquals ("Test#16", typeof (OverflowException), e.GetType ()); } // Subtract() AssertEquals ("Test#17", (short)100, SqlInt16.Subtract (Test164, Test64).Value); try { SqlInt16.Subtract (SqlInt16.MinValue, Test164); Fail("Test#18"); } catch(Exception e) { AssertEquals ("Test#19", typeof (OverflowException), e.GetType ()); } #if NET_2_0 // Modulus () AssertEquals ("Test#20", (SqlInt16)36, SqlInt16.Modulus (Test164, Test64)); AssertEquals ("Test#21", (SqlInt16)64, SqlInt16.Modulus (Test64, Test164)); #endif } [Test] public void BitwiseMethods() { short MaxValue = SqlInt16.MaxValue.Value; SqlInt16 TestInt = new SqlInt16 (0); SqlInt16 TestIntMax = new SqlInt16 (MaxValue); SqlInt16 TestInt2 = new SqlInt16 (10922); SqlInt16 TestInt3 = new SqlInt16 (21845); // BitwiseAnd AssertEquals ("Test#1", (short)21845, SqlInt16.BitwiseAnd (TestInt3, TestIntMax).Value); AssertEquals ("Test#2", (short)0, SqlInt16.BitwiseAnd (TestInt2, TestInt3).Value); AssertEquals ("Test#3", (short)10922, SqlInt16.BitwiseAnd (TestInt2, TestIntMax).Value); //BitwiseOr AssertEquals ("Test#4", (short)MaxValue, SqlInt16.BitwiseOr (TestInt2, TestInt3).Value); AssertEquals ("Test#5", (short)21845, SqlInt16.BitwiseOr (TestInt, TestInt3).Value); AssertEquals ("Test#6", (short)MaxValue, SqlInt16.BitwiseOr (TestIntMax, TestInt2).Value); } [Test] public void CompareTo() { SqlInt16 TestInt4000 = new SqlInt16 (4000); SqlInt16 TestInt4000II = new SqlInt16 (4000); SqlInt16 TestInt10 = new SqlInt16 (10); SqlInt16 TestInt10000 = new SqlInt16 (10000); SqlString TestString = new SqlString ("This is a test"); Assert ("Test#1", TestInt4000.CompareTo (TestInt10) > 0); Assert ("Test#2", TestInt10.CompareTo (TestInt4000) < 0); Assert ("Test#3", TestInt4000II.CompareTo (TestInt4000) == 0); Assert ("Test#4", TestInt4000II.CompareTo (SqlInt16.Null) > 0); try { TestInt10.CompareTo (TestString); Fail ("Test#5"); } catch(Exception e) { AssertEquals ("Test#6", typeof (ArgumentException), e.GetType ()); } } [Test] public void EqualsMethod() { SqlInt16 Test0 = new SqlInt16 (0); SqlInt16 Test158 = new SqlInt16 (158); SqlInt16 Test180 = new SqlInt16 (180); SqlInt16 Test180II = new SqlInt16 (180); Assert ("Test#1", !Test0.Equals (Test158)); Assert ("Test#2", !Test158.Equals (Test180)); Assert ("Test#3", !Test180.Equals (new SqlString ("TEST"))); Assert ("Test#4", Test180.Equals (Test180II)); } [Test] public void StaticEqualsMethod() { SqlInt16 Test34 = new SqlInt16 (34); SqlInt16 Test34II = new SqlInt16 (34); SqlInt16 Test15 = new SqlInt16 (15); Assert ("Test#1", SqlInt16.Equals (Test34, Test34II).Value); Assert ("Test#2", !SqlInt16.Equals (Test34, Test15).Value); Assert ("Test#3", !SqlInt16.Equals (Test15, Test34II).Value); } [Test] public void GetHashCodeTest() { SqlInt16 Test15 = new SqlInt16 (15); // FIXME: Better way to test GetHashCode()-methods AssertEquals ("Test#1", Test15.GetHashCode (), Test15.GetHashCode ()); } [Test] public void GetTypeTest() { SqlInt16 Test = new SqlInt16 (84); AssertEquals ("Test#1", "System.Data.SqlTypes.SqlInt16", Test.GetType ().ToString ()); } [Test] public void Greaters() { SqlInt16 Test10 = new SqlInt16 (10); SqlInt16 Test10II = new SqlInt16 (10); SqlInt16 Test110 = new SqlInt16 (110); // GreateThan () Assert ("Test#1", !SqlInt16.GreaterThan (Test10, Test110).Value); Assert ("Test#2", SqlInt16.GreaterThan (Test110, Test10).Value); Assert ("Test#3", !SqlInt16.GreaterThan (Test10II, Test10).Value); // GreaterTharOrEqual () Assert ("Test#4", !SqlInt16.GreaterThanOrEqual (Test10, Test110).Value); Assert ("Test#5", SqlInt16.GreaterThanOrEqual (Test110, Test10).Value); Assert ("Test#6", SqlInt16.GreaterThanOrEqual (Test10II, Test10).Value); } [Test] public void Lessers() { SqlInt16 Test10 = new SqlInt16 (10); SqlInt16 Test10II = new SqlInt16 (10); SqlInt16 Test110 = new SqlInt16 (110); // LessThan() Assert ("Test#1", SqlInt16.LessThan (Test10, Test110).Value); Assert ("Test#2", !SqlInt16.LessThan (Test110, Test10).Value); Assert ("Test#3", !SqlInt16.LessThan (Test10II, Test10).Value); // LessThanOrEqual () Assert ("Test#4", SqlInt16.LessThanOrEqual (Test10, Test110).Value); Assert ("Test#5", !SqlInt16.LessThanOrEqual (Test110, Test10).Value); Assert ("Test#6", SqlInt16.LessThanOrEqual (Test10II, Test10).Value); Assert ("Test#7", SqlInt16.LessThanOrEqual (Test10II, SqlInt16.Null).IsNull); } [Test] public void NotEquals() { SqlInt16 Test12 = new SqlInt16 (12); SqlInt16 Test128 = new SqlInt16 (128); SqlInt16 Test128II = new SqlInt16 (128); Assert ("Test#1", SqlInt16.NotEquals (Test12, Test128).Value); Assert ("Test#2", SqlInt16.NotEquals (Test128, Test12).Value); Assert ("Test#3", SqlInt16.NotEquals (Test128II, Test12).Value); Assert ("Test#4", !SqlInt16.NotEquals (Test128II, Test128).Value); Assert ("Test#5", !SqlInt16.NotEquals (Test128, Test128II).Value); Assert ("Test#6", SqlInt16.NotEquals (SqlInt16.Null, Test128II).IsNull); Assert ("Test#7", SqlInt16.NotEquals (SqlInt16.Null, Test128II).IsNull); } [Test] public void OnesComplement() { SqlInt16 Test12 = new SqlInt16(12); SqlInt16 Test128 = new SqlInt16(128); AssertEquals ("Test#1", (SqlInt16)(-13), SqlInt16.OnesComplement (Test12)); AssertEquals ("Test#2", (SqlInt16)(-129), SqlInt16.OnesComplement (Test128)); } [Test] public void Parse() { try { SqlInt16.Parse (null); Fail ("Test#1"); } catch (Exception e) { AssertEquals ("Test#2", typeof (ArgumentNullException), e.GetType ()); } try { SqlInt16.Parse ("not-a-number"); Fail ("Test#3"); } catch (Exception e) { AssertEquals ("Test#4", typeof (FormatException), e.GetType ()); } try { int OverInt = (int)SqlInt16.MaxValue + 1; SqlInt16.Parse (OverInt.ToString ()); Fail ("Test#5"); } catch (Exception e) { AssertEquals ("Test#6", typeof (OverflowException), e.GetType ()); } AssertEquals("Test#7", (short)150, SqlInt16.Parse ("150").Value); } [Test] public void Conversions() { SqlInt16 Test12 = new SqlInt16 (12); SqlInt16 Test0 = new SqlInt16 (0); SqlInt16 TestNull = SqlInt16.Null; SqlInt16 Test1000 = new SqlInt16 (1000); SqlInt16 Test288 = new SqlInt16(288); // ToSqlBoolean () Assert ("TestA#1", Test12.ToSqlBoolean ().Value); Assert ("TestA#2", !Test0.ToSqlBoolean ().Value); Assert ("TestA#3", TestNull.ToSqlBoolean ().IsNull); // ToSqlByte () AssertEquals ("TestB#1", (byte)12, Test12.ToSqlByte ().Value); AssertEquals ("TestB#2", (byte)0, Test0.ToSqlByte ().Value); try { SqlByte b = (byte)Test1000.ToSqlByte (); Fail ("TestB#4"); } catch (Exception e) { AssertEquals ("TestB#5", typeof (OverflowException), e.GetType ()); } // ToSqlDecimal () AssertEquals ("TestC#1", (decimal)12, Test12.ToSqlDecimal ().Value); AssertEquals ("TestC#2", (decimal)0, Test0.ToSqlDecimal ().Value); AssertEquals ("TestC#3", (decimal)288, Test288.ToSqlDecimal ().Value); // ToSqlDouble () AssertEquals ("TestD#1", (double)12, Test12.ToSqlDouble ().Value); AssertEquals ("TestD#2", (double)0, Test0.ToSqlDouble ().Value); AssertEquals ("TestD#3", (double)1000, Test1000.ToSqlDouble ().Value); // ToSqlInt32 () AssertEquals ("TestE#1", (int)12, Test12.ToSqlInt32 ().Value); AssertEquals ("TestE#2", (int)0, Test0.ToSqlInt32 ().Value); AssertEquals ("TestE#3", (int)288, Test288.ToSqlInt32().Value); // ToSqlInt64 () AssertEquals ("TestF#1", (long)12, Test12.ToSqlInt64 ().Value); AssertEquals ("TestF#2", (long)0, Test0.ToSqlInt64 ().Value); AssertEquals ("TestF#3", (long)288, Test288.ToSqlInt64 ().Value); // ToSqlMoney () AssertEquals ("TestG#1", 12.0000M, Test12.ToSqlMoney ().Value); AssertEquals ("TestG#2", (decimal)0, Test0.ToSqlMoney ().Value); AssertEquals ("TestG#3", 288.0000M, Test288.ToSqlMoney ().Value); // ToSqlSingle () AssertEquals ("TestH#1", (float)12, Test12.ToSqlSingle ().Value); AssertEquals ("TestH#2", (float)0, Test0.ToSqlSingle ().Value); AssertEquals ("TestH#3", (float)288, Test288.ToSqlSingle().Value); // ToSqlString () AssertEquals ("TestI#1", "12", Test12.ToSqlString ().Value); AssertEquals ("TestI#2", "0", Test0.ToSqlString ().Value); AssertEquals ("TestI#3", "288", Test288.ToSqlString ().Value); // ToString () AssertEquals ("TestJ#1", "12", Test12.ToString ()); AssertEquals ("TestJ#2", "0", Test0.ToString ()); AssertEquals ("TestJ#3", "288", Test288.ToString ()); } [Test] public void Xor() { SqlInt16 Test14 = new SqlInt16 (14); SqlInt16 Test58 = new SqlInt16 (58); SqlInt16 Test130 = new SqlInt16 (130); SqlInt16 TestMax = new SqlInt16 (SqlInt16.MaxValue.Value); SqlInt16 Test0 = new SqlInt16 (0); AssertEquals ("Test#1", (short)52, SqlInt16.Xor (Test14, Test58).Value); AssertEquals ("Test#2", (short)140, SqlInt16.Xor (Test14, Test130).Value); AssertEquals ("Test#3", (short)184, SqlInt16.Xor (Test58, Test130).Value); AssertEquals ("Test#4", (short)0, SqlInt16.Xor (TestMax, TestMax).Value); AssertEquals ("Test#5", TestMax.Value, SqlInt16.Xor (TestMax, Test0).Value); } // OPERATORS [Test] public void ArithmeticOperators() { SqlInt16 Test24 = new SqlInt16 (24); SqlInt16 Test64 = new SqlInt16 (64); SqlInt16 Test2550 = new SqlInt16 (2550); SqlInt16 Test0 = new SqlInt16 (0); // "+"-operator AssertEquals ("TestA#1", (SqlInt16)2614,Test2550 + Test64); try { SqlInt16 result = Test64 + SqlInt16.MaxValue; Fail ("TestA#2"); } catch (Exception e) { AssertEquals ("TestA#3", typeof (OverflowException), e.GetType ()); } // "/"-operator AssertEquals ("TestB#1", (SqlInt16)39, Test2550 / Test64); AssertEquals ("TestB#2", (SqlInt16)0, Test24 / Test64); try { SqlInt16 result = Test2550 / Test0; Fail ("TestB#3"); } catch (Exception e) { AssertEquals ("TestB#4", typeof (DivideByZeroException), e.GetType ()); } // "*"-operator AssertEquals ("TestC#1", (SqlInt16)1536, Test64 * Test24); try { SqlInt16 test = (SqlInt16.MaxValue * Test64); Fail ("TestC#2"); } catch (Exception e) { AssertEquals ("TestC#3", typeof (OverflowException), e.GetType ()); } // "-"-operator AssertEquals ("TestD#1", (SqlInt16)2526, Test2550 - Test24); try { SqlInt16 test = SqlInt16.MinValue - Test64; Fail ("TestD#2"); } catch (Exception e) { AssertEquals ("OverflowException", typeof (OverflowException), e.GetType ()); } // "%"-operator AssertEquals ("TestE#1", (SqlInt16)54, Test2550 % Test64); AssertEquals ("TestE#2", (SqlInt16)24, Test24 % Test64); AssertEquals ("TestE#1", (SqlInt16)0, new SqlInt16 (100) % new SqlInt16 (10)); } [Test] public void BitwiseOperators() { SqlInt16 Test2 = new SqlInt16 (2); SqlInt16 Test4 = new SqlInt16 (4); SqlInt16 Test2550 = new SqlInt16 (2550); // & -operator AssertEquals ("TestA#1", (SqlInt16)0, Test2 & Test4); AssertEquals ("TestA#2", (SqlInt16)2, Test2 & Test2550); AssertEquals ("TestA#3", (SqlInt16)0, SqlInt16.MaxValue & SqlInt16.MinValue); // | -operator AssertEquals ("TestB#1", (SqlInt16)6,Test2 | Test4); AssertEquals ("TestB#2", (SqlInt16)2550, Test2 | Test2550); AssertEquals ("TestB#3", (SqlInt16)(-1), SqlInt16.MinValue | SqlInt16.MaxValue); // ^ -operator AssertEquals("TestC#1", (SqlInt16)2546, (Test2550 ^ Test4)); AssertEquals("TestC#2", (SqlInt16)6, (Test2 ^ Test4)); } [Test] public void ThanOrEqualOperators() { SqlInt16 Test165 = new SqlInt16 (165); SqlInt16 Test100 = new SqlInt16 (100); SqlInt16 Test100II = new SqlInt16 (100); SqlInt16 Test255 = new SqlInt16 (2550); // == -operator Assert ("TestA#1", (Test100 == Test100II).Value); Assert ("TestA#2", !(Test165 == Test100).Value); Assert ("TestA#3", (Test165 == SqlInt16.Null).IsNull); // != -operator Assert ("TestB#1", !(Test100 != Test100II).Value); Assert ("TestB#2", (Test100 != Test255).Value); Assert ("TestB#3", (Test165 != Test255).Value); Assert ("TestB#4", (Test165 != SqlInt16.Null).IsNull); // > -operator Assert ("TestC#1", (Test165 > Test100).Value); Assert ("TestC#2", !(Test165 > Test255).Value); Assert ("TestC#3", !(Test100 > Test100II).Value); Assert ("TestC#4", (Test165 > SqlInt16.Null).IsNull); // >= -operator Assert ("TestD#1", !(Test165 >= Test255).Value); Assert ("TestD#2", (Test255 >= Test165).Value); Assert ("TestD#3", (Test100 >= Test100II).Value); Assert ("TestD#4", (Test165 >= SqlInt16.Null).IsNull); // < -operator Assert ("TestE#1", !(Test165 < Test100).Value); Assert ("TestE#2", (Test165 < Test255).Value); Assert ("TestE#3", !(Test100 < Test100II).Value); Assert ("TestE#4", (Test165 < SqlInt16.Null).IsNull); // <= -operator Assert ("TestF#1", (Test165 <= Test255).Value); Assert ("TestF#2", !(Test255 <= Test165).Value); Assert ("TestF#3", (Test100 <= Test100II).Value); Assert ("TestF#4", (Test165 <= SqlInt16.Null).IsNull); } [Test] public void OnesComplementOperator() { SqlInt16 Test12 = new SqlInt16 (12); SqlInt16 Test128 = new SqlInt16 (128); AssertEquals ("Test#1", (SqlInt16)(-13), ~Test12); AssertEquals ("Test#2", (SqlInt16)(-129), ~Test128); AssertEquals ("Test#3", SqlInt16.Null, ~SqlInt16.Null); } [Test] public void UnaryNegation() { SqlInt16 Test = new SqlInt16 (2000); SqlInt16 TestNeg = new SqlInt16 (-3000); SqlInt16 Result = -Test; AssertEquals ("Test#1", (short)(-2000), Result.Value); Result = -TestNeg; AssertEquals ("Test#2", (short)3000, Result.Value); } [Test] public void SqlBooleanToSqlInt16() { SqlBoolean TestBoolean = new SqlBoolean (true); SqlInt16 Result; Result = (SqlInt16)TestBoolean; AssertEquals ("Test#1", (short)1, Result.Value); Result = (SqlInt16)SqlBoolean.Null; Assert ("Test#2", Result.IsNull); } [Test] public void SqlDecimalToSqlInt16() { SqlDecimal TestDecimal64 = new SqlDecimal (64); SqlDecimal TestDecimal900 = new SqlDecimal (90000); AssertEquals ("Test#1", (short)64, ((SqlInt16)TestDecimal64).Value); AssertEquals ("Test#2", SqlInt16.Null, ((SqlInt16)SqlDecimal.Null)); try { SqlInt16 test = (SqlInt16)TestDecimal900; Fail ("Test#3"); } catch (Exception e) { AssertEquals("Test#4", typeof(OverflowException), e.GetType ()); } } [Test] public void SqlDoubleToSqlInt16() { SqlDouble TestDouble64 = new SqlDouble (64); SqlDouble TestDouble900 = new SqlDouble (90000); AssertEquals ("Test#1", (short)64, ((SqlInt16)TestDouble64).Value); AssertEquals ("Test#2", SqlInt16.Null, ((SqlInt16)SqlDouble.Null)); try { SqlInt16 test = (SqlInt16)TestDouble900; Fail ("Test#3"); } catch (Exception e) { AssertEquals("Test#4", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlIntToInt16() { SqlInt16 Test = new SqlInt16(12); Int16 Result = (Int16)Test; AssertEquals("Test#1", (short)12, Result); } [Test] public void SqlInt32ToSqlInt16() { SqlInt32 Test64 = new SqlInt32 (64); SqlInt32 Test900 = new SqlInt32 (90000); AssertEquals ("Test#1", (short)64, ((SqlInt16)Test64).Value); try { SqlInt16 test = (SqlInt16)Test900; Fail ("Test#2"); } catch (Exception e) { AssertEquals ("Test#3", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlInt64ToSqlInt16() { SqlInt64 Test64 = new SqlInt64 (64); SqlInt64 Test900 = new SqlInt64 (90000); AssertEquals ("Test#1", (short)64, ((SqlInt16)Test64).Value); try { SqlInt16 test = (SqlInt16)Test900; Fail ("Test#2"); } catch (Exception e) { AssertEquals("Test#3", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlMoneyToSqlInt16() { SqlMoney TestMoney64 = new SqlMoney(64); SqlMoney TestMoney900 = new SqlMoney(90000); AssertEquals ("Test#1", (short)64, ((SqlInt16)TestMoney64).Value); try { SqlInt16 test = (SqlInt16)TestMoney900; Fail ("Test#2"); } catch (Exception e) { AssertEquals("test#3", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlSingleToSqlInt16() { SqlSingle TestSingle64 = new SqlSingle(64); SqlSingle TestSingle900 = new SqlSingle(90000); AssertEquals("Test#1", (short)64, ((SqlInt16)TestSingle64).Value); try { SqlInt16 test = (SqlInt16)TestSingle900; Fail ("Test#2"); } catch (Exception e) { AssertEquals ("Test#3", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlStringToSqlInt16() { SqlString TestString = new SqlString("Test string"); SqlString TestString100 = new SqlString("100"); SqlString TestString1000 = new SqlString("100000"); AssertEquals ("Test#1", (short)100, ((SqlInt16)TestString100).Value); try { SqlInt16 test = (SqlInt16)TestString1000; Fail ("Test#2"); } catch(Exception e) { AssertEquals ("Test#3", typeof (OverflowException), e.GetType ()); } try { SqlInt16 test = (SqlInt16)TestString; Fail ("Test#3"); } catch(Exception e) { AssertEquals ("Test#4", typeof (FormatException), e.GetType ()); } } [Test] public void ByteToSqlInt16() { short TestShort = 14; AssertEquals ("Test#1", (short)14, ((SqlInt16)TestShort).Value); } } }
using System; using GitVersion; using GitVersion.Helpers; using GitVersionCore.Tests.Helpers; using NUnit.Framework; namespace GitVersionCore.Tests { [TestFixture] public class StringFormatWithExtensionTests { private IEnvironment environment; [SetUp] public void Setup() { environment = new TestEnvironment(); } [Test] public void FormatWithNoTokens() { var propertyObject = new { }; var target = "Some String without tokens"; var expected = target; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithSingleSimpleToken() { var propertyObject = new { SomeProperty = "SomeValue" }; var target = "{SomeProperty}"; var expected = "SomeValue"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleTokensAndVerbatimText() { var propertyObject = new { SomeProperty = "SomeValue", AnotherProperty = "Other Value" }; var target = "{SomeProperty} some text {AnotherProperty}"; var expected = "SomeValue some text Other Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarToken() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR}"; var expected = "Env Var Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarTokenWithFallback() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR ?? fallback}"; var expected = "Env Var Value"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithFallback() { environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR ?? fallback}"; var expected = "fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithoutFallback() { environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR}"; Assert.Throws<ArgumentException>(() => target.FormatWith(propertyObject, environment)); } [Test] public void FormatWithMultipleEnvVars() { environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_1", "Val-1"); environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_2", "Val-2"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR_1} and {env:GIT_VERSION_TEST_VAR_2}"; var expected = "Val-1 and Val-2"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleEnvChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: char var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ?? fallback}"; var expected = "{env:env:GIT_VERSION_TEST_VAR_1} and fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithMultipleFallbackChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: and ?? chars var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ??? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(target, actual); } [Test] public void FormatWithSingleFallbackChar() { environment.SetEnvironmentVariable("DUMMY_ENV_VAR", "Dummy-Val"); var propertyObject = new { }; //Test the sanity of the regex when there is a grammar mismatch var target = "{en:DUMMY_ENV_VAR} and {env:DUMMY_ENV_VAR??fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(target, actual); } [Test] public void FormatWIthNullPropagationWithMultipleSpaces() { var propertyObject = new { SomeProperty = "Some Value" }; var target = "{SomeProperty} and {env:DUMMY_ENV_VAR ?? fallback}"; var expected = "Some Value and fallback"; var actual = target.FormatWith(propertyObject, environment); Assert.AreEqual(expected, actual); } [Test] public void FormatEnvVar_WithFallback_QuotedAndEmpty() { environment.SetEnvironmentVariable("ENV_VAR", null); var propertyObject = new { }; var target = "{env:ENV_VAR ?? \"\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_String() { var propertyObject = new { Property = "Value" }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("Value")); } [Test] public void FormatProperty_Integer() { var propertyObject = new { Property = 42 }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("42")); } [Test] public void FormatProperty_NullObject() { var propertyObject = new { Property = (object)null }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_NullInteger() { var propertyObject = new { Property = (int?)null }; var target = "{Property}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } [Test] public void FormatProperty_String_WithFallback() { var propertyObject = new { Property = "Value" }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("Value")); } [Test] public void FormatProperty_Integer_WithFallback() { var propertyObject = new { Property = 42 }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("42")); } [Test] public void FormatProperty_NullObject_WithFallback() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullInteger_WithFallback() { var propertyObject = new { Property = (int?)null }; var target = "{Property ?? fallback}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullObject_WithFallback_Quoted() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"fallback\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("fallback")); } [Test] public void FormatProperty_NullObject_WithFallback_QuotedAndPadded() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \" fallback \"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo(" fallback ")); } [Test] public void FormatProperty_NullObject_WithFallback_QuotedAndEmpty() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"\"}"; var actual = target.FormatWith(propertyObject, environment); Assert.That(actual, Is.EqualTo("")); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal static class LayoutParser { internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool? throwConfigExceptions, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested) { //possible escape char `\` if (ch == '\\') { sr.Read(); var nextChar = sr.Peek(); //escape chars if (EndOfLayout(nextChar)) { //read next char and append sr.Read(); literalBuf.Append((char)nextChar); } else { //don't treat \ as escape char and just read it literalBuf.Append('\\'); } continue; } if (EndOfLayout(ch)) { //end of innerlayout. // `}` is when double nested inner layout. // `:` when single nested layout break; } } sr.Read(); //detect `${` (new layout-renderer) if (ch == '$' && sr.Peek() == '{') { //stash already found layout-renderer. AddLiteral(literalBuf, result); LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr, throwConfigExceptions); if (CanBeConvertedToLiteral(newLayoutRenderer)) { newLayoutRenderer = ConvertToLiteral(newLayoutRenderer); } // layout renderer result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } AddLiteral(literalBuf, result); int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } /// <summary> /// Add <see cref="LiteralLayoutRenderer"/> to <paramref name="result"/> /// </summary> /// <param name="literalBuf"></param> /// <param name="result"></param> private static void AddLiteral(StringBuilder literalBuf, List<LayoutRenderer> result) { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } } private static bool EndOfLayout(int ch) { return ch == '}' || ch == ':'; } private static string ParseLayoutRendererName(SimpleStringReader sr) { return sr.ReadUntilMatch(ch => EndOfLayout(ch)); } private static string ParseParameterName(SimpleStringReader sr) { int ch; int nestLevel = 0; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); nameBuf.Append('$'); if (sr.Peek() == '{') { nameBuf.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { sr.Read(); // issue#3193 if (nestLevel != 0) { nameBuf.Append((char)ch); } // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterValue(SimpleStringReader sr) { var simpleValue = sr.ReadUntilMatch(ch => EndOfLayout(ch) || ch == '\\'); if (sr.Peek() == '\\') { var nameBuf = new StringBuilder(); nameBuf.Append(simpleValue); ParseParameterUnicodeValue(sr, nameBuf); return nameBuf.ToString(); } return simpleValue; } private static void ParseParameterUnicodeValue(SimpleStringReader sr, StringBuilder nameBuf) { int ch; while ((ch = sr.Peek()) != -1) { if (EndOfLayout(ch)) { break; } // Code in this condition was replaced // to support escape codes e.g. '\r' '\n' '\u003a', // which can not be used directly as they are used as tokens by the parser // All escape codes listed in the following link were included // in addition to "\{", "\}", "\:" which are NLog specific: // https://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx if (ch == '\\') { // skip the backslash sr.Read(); var nextChar = (char)sr.Peek(); switch (nextChar) { case ':': case '{': case '}': case '\'': case '"': case '\\': sr.Read(); nameBuf.Append(nextChar); break; case '0': sr.Read(); nameBuf.Append('\0'); break; case 'a': sr.Read(); nameBuf.Append('\a'); break; case 'b': sr.Read(); nameBuf.Append('\b'); break; case 'f': sr.Read(); nameBuf.Append('\f'); break; case 'n': sr.Read(); nameBuf.Append('\n'); break; case 'r': sr.Read(); nameBuf.Append('\r'); break; case 't': sr.Read(); nameBuf.Append('\t'); break; case 'u': sr.Read(); var uChar = GetUnicode(sr, 4); // 4 digits nameBuf.Append(uChar); break; case 'U': sr.Read(); var UChar = GetUnicode(sr, 8); // 8 digits nameBuf.Append(UChar); break; case 'x': sr.Read(); var xChar = GetUnicode(sr, 4); // 1-4 digits nameBuf.Append(xChar); break; case 'v': sr.Read(); nameBuf.Append('\v'); break; } continue; } nameBuf.Append((char)ch); sr.Read(); } } private static char GetUnicode(SimpleStringReader sr, int maxDigits) { int code = 0; for (int cnt = 0; cnt < maxDigits; cnt++) { var digitCode = sr.Peek(); if (digitCode >= (int)'0' && digitCode <= (int)'9') digitCode = digitCode - (int)'0'; else if (digitCode >= (int)'a' && digitCode <= (int)'f') digitCode = digitCode - (int)'a' + 10; else if (digitCode >= (int)'A' && digitCode <= (int)'F') digitCode = digitCode - (int)'A' + 10; else break; sr.Read(); code = code * 16 + digitCode; } return (char)code; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions) { int ch = stringReader.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(stringReader); var layoutRenderer = GetLayoutRenderer(configurationItemFactory, name, throwConfigExceptions); Dictionary<Type, LayoutRenderer> wrappers = null; List<LayoutRenderer> orderedWrappers = null; ch = stringReader.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(stringReader).Trim(); if (stringReader.Peek() == '=') { stringReader.Read(); // skip the '=' PropertyInfo propertyInfo; LayoutRenderer parameterTarget = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo)) { if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out var wrapperType)) { wrappers = wrappers ?? new Dictionary<Type, LayoutRenderer>(); orderedWrappers = orderedWrappers ?? new List<LayoutRenderer>(); if (!wrappers.TryGetValue(wrapperType, out var wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo)) { propertyInfo = null; } else { parameterTarget = wrapperRenderer; } } } if (propertyInfo == null) { var value = ParseParameterValue(stringReader); if (!string.IsNullOrEmpty(parameterName) || !StringHelpers.IsNullOrWhiteSpace(value)) { // TODO NLog 5.0 Should throw exception when invalid configuration (Check throwConfigExceptions) InternalLogger.Warn("Skipping unrecognized property '{0}={1}` for ${{{2}}} ({3})", parameterName, value, name, layoutRenderer?.GetType()); } } else { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out var txt); var nestedLayout = new SimpleLayout(renderers, txt, configurationItemFactory); propertyInfo.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory); propertyInfo.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(stringReader); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName); } ch = stringReader.Read(); } if (orderedWrappers != null) { layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); } return layoutRenderer; } private static LayoutRenderer GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, string name, bool? throwConfigExceptions) { LayoutRenderer layoutRenderer; try { layoutRenderer = configurationItemFactory.LayoutRenderers.CreateInstance(name); } catch (Exception ex) { if (throwConfigExceptions ?? LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions) { throw; // TODO NLog 5.0 throw NLogConfigurationException. Maybe also include entire input layout-string (if not too long) } InternalLogger.Error(ex, "Error parsing layout {0} will be ignored.", name); // replace with empty values layoutRenderer = new LiteralLayoutRenderer(string.Empty); } return layoutRenderer; } private static void SetDefaultPropertyValue(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, string value) { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) if (PropertyHelper.TryGetPropertyInfo(layoutRenderer, string.Empty, out var propertyInfo)) { PropertyHelper.SetPropertyFromString(layoutRenderer, propertyInfo.Name, value, configurationItemFactory); } else { // TODO NLog 5.0 Should throw exception when invalid configuration (Check throwConfigExceptions) InternalLogger.Warn("{0} has no default property to assign value {1}", layoutRenderer.GetType(), value); } } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType(), newRenderer.GetType()); if (CanBeConvertedToLiteral(lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(true, lr)) { var renderType = renderable.GetType(); if (renderType == typeof(SimpleLayout)) { continue; } if (!renderType.IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(List<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { var lr1 = list[i] as LiteralLayoutRenderer; var lr2 = list[i + 1] as LiteralLayoutRenderer; if (lr1 != null && lr2 != null) { lr1.Text += lr2.Text; list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent())); } } }
// 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.Globalization; using System.Threading; using System.Collections; using System.Diagnostics; namespace System.DirectoryServices.Protocols { internal class LdapPartialResultsProcessor { private ArrayList _resultList = new ArrayList(); private ManualResetEvent _workThreadWaitHandle = null; private bool _workToDo = false; private int _currentIndex = 0; internal LdapPartialResultsProcessor(ManualResetEvent eventHandle) { _workThreadWaitHandle = eventHandle; } public void Add(LdapPartialAsyncResult asyncResult) { lock (this) { _resultList.Add(asyncResult); if (!_workToDo) { // Need to wake up the workthread if it is not running already. _workThreadWaitHandle.Set(); _workToDo = true; } } } public void Remove(LdapPartialAsyncResult asyncResult) { // Called by Abort operation. lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } // Remove this async operation from the list. _resultList.Remove(asyncResult); } } public void RetrievingSearchResults() { LdapPartialAsyncResult asyncResult = null; AsyncCallback tmpCallback = null; lock (this) { int count = _resultList.Count; if (count == 0) { // No asynchronous operation pending, begin to wait. _workThreadWaitHandle.Reset(); _workToDo = false; return; } // Might have work to do. int i = 0; while (true) { if (_currentIndex >= count) { // Some element is moved after last iteration. _currentIndex = 0; } asyncResult = (LdapPartialAsyncResult)_resultList[_currentIndex]; i++; _currentIndex++; // Have work to do. if (asyncResult._resultStatus != ResultsStatus.Done) { break; } if (i >= count) { // All the operations are done just waiting for the user to pick up the results. _workToDo = false; _workThreadWaitHandle.Reset(); return; } } // Try to get the results availabe for this asynchronous operation . GetResultsHelper(asyncResult); // If we are done with the asynchronous search, we need to fire callback and signal the waitable object. if (asyncResult._resultStatus == ResultsStatus.Done) { asyncResult._manualResetEvent.Set(); asyncResult._completed = true; if (asyncResult._callback != null) { tmpCallback = asyncResult._callback; } } else if (asyncResult._callback != null && asyncResult._partialCallback) { // The user specified a callback to be called even when partial results become available. if (asyncResult._response != null && (asyncResult._response.Entries.Count > 0 || asyncResult._response.References.Count > 0)) { tmpCallback = asyncResult._callback; } } } tmpCallback?.Invoke(asyncResult); } private void GetResultsHelper(LdapPartialAsyncResult asyncResult) { LdapConnection connection = asyncResult._con; ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED; if (asyncResult._resultStatus == ResultsStatus.CompleteResult) { resultType = ResultAll.LDAP_MSG_POLLINGALL; } try { SearchResponse response = (SearchResponse)connection.ConstructResponse(asyncResult._messageID, LdapOperation.LdapSearch, resultType, asyncResult._requestTimeout, false); // This should only happen in the polling thread case. if (response == null) { // Only when request time out has not yet expiered. if ((asyncResult._startTime.Ticks + asyncResult._requestTimeout.Ticks) > DateTime.Now.Ticks) { // This is expected, just the client does not have the result yet . return; } else { // time out, now we need to throw proper exception throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut)); } } if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // If search is done, set the flag. if (response.searchDone) { asyncResult._resultStatus = ResultsStatus.Done; } } catch (Exception exception) { if (exception is DirectoryOperationException directoryOperationException) { SearchResponse response = (SearchResponse)directoryOperationException.Response; if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // Set the response back to the exception so it holds all the results up to now. directoryOperationException.Response = asyncResult._response; } else if (exception is LdapException ldapException) { LdapError errorCode = (LdapError)ldapException.ErrorCode; if (asyncResult._response != null) { // add previous retrieved entries if available if (asyncResult._response.Entries != null) { for (int i = 0; i < asyncResult._response.Entries.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.Entries[i]); } } // add previous retrieved references if available if (asyncResult._response.References != null) { for (int i = 0; i < asyncResult._response.References.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.References[i]); } } } } // Exception occurs, this operation is done. asyncResult._exception = exception; asyncResult._resultStatus = ResultsStatus.Done; // Need to abandon this request. Wldap32.ldap_abandon(connection._ldapHandle, asyncResult._messageID); } } public void NeedCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (_resultList.Contains(asyncResult)) { // We don't need partial results anymore, polling for complete results. if (asyncResult._resultStatus == ResultsStatus.PartialResult) asyncResult._resultStatus = ResultsStatus.CompleteResult; } else { throw new ArgumentException(SR.InvalidAsyncResult); } } } public PartialResultsCollection GetPartialResults(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } if (asyncResult._exception != null) { // Remove this async operation // The async operation basically failed, we won't do it any more, so throw // exception to the user and remove it from the list. _resultList.Remove(asyncResult); throw asyncResult._exception; } var collection = new PartialResultsCollection(); if (asyncResult._response != null) { if (asyncResult._response.Entries != null) { for (int i = 0; i < asyncResult._response.Entries.Count; i++) { collection.Add(asyncResult._response.Entries[i]); } asyncResult._response.Entries.Clear(); } if (asyncResult._response.References != null) { for (int i = 0; i < asyncResult._response.References.Count; i++) { collection.Add(asyncResult._response.References[i]); } asyncResult._response.References.Clear(); } } return collection; } } public DirectoryResponse GetCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } Debug.Assert(asyncResult._resultStatus == ResultsStatus.Done); _resultList.Remove(asyncResult); if (asyncResult._exception != null) { throw asyncResult._exception; } else { return asyncResult._response; } } } private void AddResult(SearchResponse partialResults, SearchResponse newResult) { if (newResult == null) { return; } if (newResult.Entries != null) { for (int i = 0; i < newResult.Entries.Count; i++) { partialResults.Entries.Add(newResult.Entries[i]); } } if (newResult.References != null) { for (int i = 0; i < newResult.References.Count; i++) { partialResults.References.Add(newResult.References[i]); } } } } internal class PartialResultsRetriever { private ManualResetEvent _workThreadWaitHandle = null; private LdapPartialResultsProcessor _processor = null; internal PartialResultsRetriever(ManualResetEvent eventHandle, LdapPartialResultsProcessor processor) { _workThreadWaitHandle = eventHandle; _processor = processor; // Start the thread. var thread = new Thread(new ThreadStart(ThreadRoutine)) { IsBackground = true }; thread.Start(); } private void ThreadRoutine() { while (true) { // Make sure there is work to do. _workThreadWaitHandle.WaitOne(); // Do the real work. try { _processor.RetrievingSearchResults(); } catch (Exception e) { // We catch the exception here as we don't really want our worker thread to die because it // encounter certain exception when processing a single async operation. Debug.WriteLine(e.Message); } // Voluntarily gives up the CPU time. Thread.Sleep(250); } } } }
// // Details.cs // // Authors: // Gabriel Burt <[email protected]> // // Copyright (C) 2009 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.IO; using System.Net; using System.Collections.Generic; using System.Linq; using Mono.Unix; using Hyena.Json; namespace InternetArchive { public class Details { private string id, json; private JsonObject details; private JsonObject metadata, misc, item, review_info; private JsonArray reviews; public Details (string id) : this (id, null) {} public Details (string id, string json) { this.id = id; this.json = json; LoadDetails (); } #region Properties from the JSON object public string Description { get { return metadata.GetJoined ("description", System.Environment.NewLine); } } public string Creator { get { return metadata.GetJoined ("creator", ", "); } } public string LicenseUrl { get { return metadata.GetJoined (Field.LicenseUrl.Id, null) ?? metadata.GetJoined ("license", null); } } public string Language { get { return metadata.GetJoined (Field.Language.Id, ", "); } } public string Contributor { get { return metadata.GetJoined (Field.Contributor.Id, ", "); } } public string Publisher { get { return metadata.GetJoined ("publisher", ", "); } } public string Year { get { return metadata.GetJoined ("year", ", "); } } public string Subject { get { return metadata.GetJoined ("subject", ", "); } } public string Source { get { return metadata.GetJoined ("source", ", "); } } public string Taper { get { return metadata.GetJoined ("taper", ", "); } } public string Lineage { get { return metadata.GetJoined ("lineage", ", "); } } public string Transferer { get { return metadata.GetJoined ("transferer", ", "); } } public string Collections { get { return metadata.GetJoined ("collection", ", "); } } public DateTime DateAdded { get { return GetMetadataDate ("addeddate"); } } public string AddedBy { get { return metadata.GetJoined ("adder", ", "); } } public string Venue { get { return metadata.GetJoined ("venue", ", "); } } public string Coverage { get { return metadata.GetJoined ("coverage", ", "); } } public string ImageUrl { get { return misc.Get<string> ("image"); } } public long DownloadsAllTime { get { return item.Get<int> ("downloads"); } } public long DownloadsLastMonth { get { return item.Get<int> ("month"); } } public long DownloadsLastWeek { get { return item.Get<int> ("week"); } } public DateTime DateCreated { get { return GetMetadataDate ("date"); } } private DateTime GetMetadataDate (string key) { DateTime ret; if (DateTime.TryParse (metadata.GetJoined (key, null), out ret)) return ret; else return DateTime.MinValue; } public IEnumerable<DetailsFile> Files { get { string location_root = String.Format ("http://{0}{1}", details.Get<string> ("server"), details.Get<string> ("dir")); var files = details["files"] as JsonObject; foreach (string key in files.Keys) { var file = files[key] as JsonObject; yield return new DetailsFile (file, location_root, key); } } } public IEnumerable<DetailsReview> Reviews { get { if (reviews == null) { yield break; } // Return them in date-descending order for (int i = reviews.Count - 1; i >= 0; i--) { yield return new DetailsReview (reviews[i] as JsonObject); } } } public double AvgRating { get { return review_info.Get<double> ("avg_rating"); } } public int AvgRatingInt { get { return (int) Math.Round (AvgRating); } } public int NumReviews { get { return review_info.Get<int> ("num_reviews"); } } public string WebpageUrl { get { return String.Format ("http://www.archive.org/details/{0}", id); } } public string Json { get { return json; } } #endregion private void LoadDetails () { if (json != null) { // use the passed in json } else if (id == "banshee-internet-archive-offline-mode") { // Hack to load JSON data from local file instead of from archive.org json = System.IO.File.ReadAllText ("item2.json"); } else { // get it from archive.org json = FetchDetails (id); } if (json != null) { details = new Hyena.Json.Deserializer (json).Deserialize () as JsonObject; } if (details != null) { metadata = details.Get<JsonObject> ("metadata"); misc = details.Get<JsonObject> ("misc"); item = details.Get<JsonObject> ("item"); var r = details.Get<JsonObject> ("reviews"); if (r != null) { reviews = r.Get<JsonArray> ("reviews"); review_info = r.Get<JsonObject> ("info"); } } } private static string FetchDetails (string id) { HttpWebResponse response = null; string url = String.Format ("http://www.archive.org/details/{0}&output=json", id); try { Hyena.Log.Debug ("ArchiveSharp Getting Details", url); var request = (HttpWebRequest) WebRequest.Create (url); request.UserAgent = Search.UserAgent; request.Timeout = Search.TimeoutMs; request.KeepAlive = Search.KeepAlive; response = (HttpWebResponse) request.GetResponse (); if (response.StatusCode != HttpStatusCode.OK) { return null; } using (Stream stream = response.GetResponseStream ()) { using (StreamReader reader = new StreamReader (stream)) { return reader.ReadToEnd (); } } } finally { if (response != null) { if (response.StatusCode != HttpStatusCode.OK) { Hyena.Log.WarningFormat ("Got status {0} searching {1}", response.StatusCode, url); } response.Close (); response = null; } } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C09_CityColl (editable child list).<br/> /// This is a generated base class of <see cref="C09_CityColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="C08_Region"/> editable child object.<br/> /// The items of the collection are <see cref="C10_City"/> objects. /// </remarks> [Serializable] public partial class C09_CityColl : BusinessListBase<C09_CityColl, C10_City> { #region Collection Business Methods /// <summary> /// Removes a <see cref="C10_City"/> item from the collection. /// </summary> /// <param name="city_ID">The City_ID of the item to be removed.</param> public void Remove(int city_ID) { foreach (var c10_City in this) { if (c10_City.City_ID == city_ID) { Remove(c10_City); break; } } } /// <summary> /// Determines whether a <see cref="C10_City"/> item is in the collection. /// </summary> /// <param name="city_ID">The City_ID of the item to search for.</param> /// <returns><c>true</c> if the C10_City is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int city_ID) { foreach (var c10_City in this) { if (c10_City.City_ID == city_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="C10_City"/> item is in the collection's DeletedList. /// </summary> /// <param name="city_ID">The City_ID of the item to search for.</param> /// <returns><c>true</c> if the C10_City is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int city_ID) { foreach (var c10_City in DeletedList) { if (c10_City.City_ID == city_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="C10_City"/> item of the <see cref="C09_CityColl"/> collection, based on a given City_ID. /// </summary> /// <param name="city_ID">The City_ID.</param> /// <returns>A <see cref="C10_City"/> object.</returns> public C10_City FindC10_CityByCity_ID(int city_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].City_ID.Equals(city_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C09_CityColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="C09_CityColl"/> collection.</returns> internal static C09_CityColl NewC09_CityColl() { return DataPortal.CreateChild<C09_CityColl>(); } /// <summary> /// Factory method. Loads a <see cref="C09_CityColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Region_ID">The Parent_Region_ID parameter of the C09_CityColl to fetch.</param> /// <returns>A reference to the fetched <see cref="C09_CityColl"/> collection.</returns> internal static C09_CityColl GetC09_CityColl(int parent_Region_ID) { return DataPortal.FetchChild<C09_CityColl>(parent_Region_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C09_CityColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C09_CityColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="C09_CityColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Region_ID">The Parent Region ID.</param> protected void Child_Fetch(int parent_Region_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC09_CityColl", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Region_ID", parent_Region_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, parent_Region_ID); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="C09_CityColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(C10_City.GetC10_City(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; using Spines.Hana.Blame.Utility; namespace Spines.Hana.Blame.Services.ReplayManager { [DataContract] public class Replay { [DataMember(Name = "room")] public Room Room { get; private set; } [DataMember(Name = "lobby")] public string Lobby { get; private set; } [DataMember(Name = "rules")] public RuleSet Rules { get; private set; } [DataMember(Name = "owari")] public Owari Owari { get; } = new Owari(); [DataMember(Name = "games")] public IReadOnlyList<Game> Games { get; private set; } [DataMember(Name = "players")] public IReadOnlyList<Player> Players { get; private set; } public string RawData => _rawData ?? throw new InvalidOperationException(); public static Replay Parse(string xml) { try { return ParseInternal(xml); } catch { return null; } } public static Replay Null() { var result = new Replay(); var games = new List<Game>(); result._rawData = "<mjloggm ver=\"2.3\"></mjloggm>"; result.Lobby = "0"; result.Rules = RuleSet.TenhouAriAri; result.Room = Room.Ippan; result.Players = Enumerable.Range(0, 4).Select(i => new Player($"player{i}", 1, 1500, "C")).ToList(); for (var round = 0; round < 8; round++) { var game = new Game(); game.Wall.AddRange(Enumerable.Range(0, 136)); game.Dice.AddRange(Enumerable.Repeat(1, 2)); game.Oya = 0; game.Scores.AddRange(Enumerable.Repeat(25000, 4)); game.Round = round; game.Honba = 0; game.Riichi = 0; game.Repetition = 0; games.Add(game); for (var i = 0; i < 4; i++) { game.Actions.Add(Ids.Draw); game.Actions.Add(Ids.Discard); game.Discards.Add(135 - 4 * i); } game.Actions.Add(Ids.ExhaustiveDraw); var ryuukyoku = new Ryuukyoku(); ryuukyoku.ScoreChanges.AddRange(Enumerable.Repeat(0, 4)); ryuukyoku.Revealed.AddRange(Enumerable.Repeat(false, 4)); } result.Owari.Scores.AddRange(Enumerable.Repeat(25000, 4)); result.Owari.Points.AddRange(Enumerable.Repeat(0m, 4)); result.Games = games; return result; } private Replay() { } private static readonly Regex DiscardRegex = new Regex(@"([DEFG])(\d{1,3})"); private static readonly Regex DrawRegex = new Regex(@"([TUVW])(\d{1,3})"); private static readonly Dictionary<MeldType, int> MeldTypeIds = new Dictionary<MeldType, int> { {MeldType.Koutsu, Ids.Pon}, {MeldType.Shuntsu, Ids.Chii}, {MeldType.ClosedKan, Ids.ClosedKan}, {MeldType.CalledKan, Ids.CalledKan}, {MeldType.AddedKan, Ids.AddedKan} }; private static readonly Dictionary<string, int> RyuukyokuTypeIds = new Dictionary<string, int> { {RyuukyokuTypes.FourKan, Ids.FourKan}, {RyuukyokuTypes.FourRiichi, Ids.FourRiichi}, {RyuukyokuTypes.FourWind, Ids.FourWind}, {RyuukyokuTypes.NagashiMangan, Ids.NagashiMangan}, {RyuukyokuTypes.NineYaochuuHai, Ids.NineYaochuuHai}, {RyuukyokuTypes.ThreeRon, Ids.ThreeRon} }; private static Replay ParseInternal(string xml) { var result = new Replay(); result._rawData = xml; var xElement = XElement.Parse(xml); var games = new List<Game>(); var shuffle = xElement.Element("SHUFFLE"); var seed = shuffle?.Attribute("seed")?.Value; var generator = new WallGenerator(seed); var go = xElement.Element("GO"); result.Lobby = go?.Attribute("lobby")?.Value; var flags = (GameTypeFlag) int.Parse(go?.Attribute("type")?.Value); result.Rules = RuleSet.Parse(flags); if (result.Rules == null) { return null; } result.Room = Room.Parse(flags); if (result.Room == null) { return null; } var un = xElement.Element("UN"); var names = GetUserNames(un).ToList(); var ranks = un?.Attribute("dan")?.Value.Split(',').Select(ToInt).ToList(); var rates = un?.Attribute("rate")?.Value.Split(',').Select(ToDecimal).ToList(); var genders = un?.Attribute("sx")?.Value.Split(',').ToList(); var players = new List<Player>(); for (var i = 0; i < names.Count; ++i) { players.Add(new Player(names[i], ranks[i], rates[i], genders[i])); } result.Players = players; var upcomingRinshan = false; var insertDiscardBeforeDora = false; var game = new Game(); foreach (var e in xElement.Elements()) { var name = e.Name.LocalName; var drawMatch = DrawRegex.Match(name); if (drawMatch.Success) { if (upcomingRinshan) { upcomingRinshan = false; game.Actions.Add(Ids.Rinshan); } else { game.Actions.Add(Ids.Draw); } continue; } var discardMatch = DiscardRegex.Match(name); if (discardMatch.Success) { if (insertDiscardBeforeDora && game.Actions[game.Actions.Count - 1] == Ids.Dora) { game.Actions.Insert(game.Actions.Count - 1, Ids.Discard); } else { game.Actions.Add(Ids.Discard); } var tileId = ToInt(discardMatch.Groups[2].Value); game.Discards.Add(tileId); insertDiscardBeforeDora = false; continue; } switch (name) { case "SHUFFLE": case "TAIKYOKU": case "GO": break; case "BYE": game.Actions.Add(Ids.DisconnectBase + ToInt(e.Attribute("who")?.Value)); break; case "UN": foreach (var i in Enumerable.Range(0, 4)) { if (e.Attribute($"n{i}") == null) { continue; } game.Actions.Add(Ids.ReconnectBase + i); } break; case "DORA": game.Actions.Add(Ids.Dora); break; case "INIT": game = new Game(); game.Wall.AddRange(generator.GetWall(games.Count)); game.Dice.AddRange(generator.GetDice(games.Count)); game.Oya = ToInt(e.Attribute("oya")?.Value); game.Scores.AddRange(ToInts(e.Attribute("ten")?.Value)); // (round indicator), (honba), (riichi sticks), (dice0), (dice1), (dora indicator) var gameSeed = ToInts(e.Attribute("seed")?.Value).ToList(); game.Round = gameSeed[0]; game.Honba = gameSeed[1]; game.Riichi = gameSeed[2]; if (games.Count > 1) { var prev = games[games.Count - 1]; if (prev.Round == game.Round) { game.Repetition = prev.Repetition + 1; } } games.Add(game); upcomingRinshan = false; break; case "N": { var decoder = new MeldDecoder(e.Attribute("m")?.Value); game.Actions.Add(MeldTypeIds[decoder.MeldType]); var call = new Call(); call.Tiles.AddRange(decoder.Tiles); game.Calls.Add(call); upcomingRinshan = IsKan(decoder.MeldType); insertDiscardBeforeDora = decoder.MeldType == MeldType.AddedKan || decoder.MeldType == MeldType.CalledKan; break; } case "REACH": var step = e.Attribute("step")?.Value; game.Actions.Add(step == "1" ? Ids.Riichi : Ids.RiichiPayment); break; case "AGARI": { var who = ToInt(e.Attribute("who")?.Value); var fromWho = ToInt(e.Attribute("fromWho")?.Value); game.Actions.Add(who == fromWho ? Ids.Tsumo : Ids.Ron); // Alternating list of yaku ID and yaku value. var yakuAndHan = ToInts(e.Attribute("yaku")?.Value).ToList(); var yakuman = ToInts(e.Attribute("yakuman")?.Value); var agari = new Agari(); agari.Winner = who; agari.From = fromWho; agari.Fu = ToInts(e.Attribute("ten")?.Value).First(); agari.ScoreChanges.AddRange(ToInts(e.Attribute("sc")?.Value).Stride(2, 1)); for (var i = 0; i < yakuAndHan.Count; i += 2) { agari.Yaku.Add(new Yaku { Id = yakuAndHan[i], Han = yakuAndHan[i + 1] }); } agari.Yaku.AddRange(yakuman.Select(y => new Yaku {Id = y, Han = 0})); game.Agaris.Add(agari); AddOwari(result, e); break; } case "RYUUKYOKU": game.Actions.Add(GetRyuukyokuId(e)); var ryuukyoku = new Ryuukyoku(); ryuukyoku.ScoreChanges.AddRange(ToInts(e.Attribute("sc")?.Value).Stride(2, 1)); ryuukyoku.Revealed.AddRange(GetRevealedHands(e)); AddOwari(result, e); break; default: throw new NotImplementedException(); } } result.Games = games; return result; } private static void AddOwari(Replay replay, XElement element) { var attribute = element.Attribute("owari"); if (attribute == null) { return; } var values = attribute.Value.Split(','); replay.Owari.Scores.AddRange(values.Stride(2).Select(ToInt)); replay.Owari.Points.AddRange(values.Stride(2, 1).Select(ToDecimal)); } private static IEnumerable<bool> GetRevealedHands(XElement e) { return Enumerable.Range(0, 4).Select(i => e.Attribute($"hai{i}") != null); } private static int GetRyuukyokuId(XElement element) { var ryuukyouType = element.Attribute("type")?.Value; return ryuukyouType == null ? Ids.ExhaustiveDraw : RyuukyokuTypeIds[ryuukyouType]; } private static IEnumerable<string> GetUserNames(XElement element) { return Enumerable.Range(0, 4).Select(i => DecodeName(element.Attribute($"n{i}")?.Value)); } private static string DecodeName(string encodedName) { if (encodedName.Length == 0 || encodedName[0] != '%') { return encodedName; } var hexValues = encodedName.Split('%', StringSplitOptions.RemoveEmptyEntries); var bytes = hexValues.Select(v => Convert.ToByte(v, 16)).ToArray(); return new UTF8Encoding().GetString(bytes); } private static bool IsKan(MeldType meldType) { return meldType == MeldType.AddedKan || meldType == MeldType.CalledKan || meldType == MeldType.ClosedKan; } private static IEnumerable<int> ToInts(string value) { return value?.Split(',').Select(ToInt) ?? Enumerable.Empty<int>(); } private static int ToInt(string value) { return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static decimal ToDecimal(string value) { return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } private string _rawData; /// <summary> /// Ids for events during a match. 0-12 are used for discards, defining the index of the discard in a sorted hand. /// </summary> private struct Ids { public const int Draw = 0; public const int Discard = 1; public const int Ron = 2; public const int Tsumo = 3; public const int ExhaustiveDraw = 4; public const int NineYaochuuHai = 5; public const int FourRiichi = 6; public const int ThreeRon = 7; public const int FourKan = 8; public const int FourWind = 9; public const int NagashiMangan = 10; public const int Pon = 11; public const int Chii = 12; public const int ClosedKan = 13; public const int CalledKan = 14; public const int AddedKan = 15; public const int Dora = 16; public const int Rinshan = 17; public const int Riichi = 18; public const int RiichiPayment = 19; // If player n disconnects, the id is this + n. public const int DisconnectBase = 30; // If player n reconnects, the id is this + n. public const int ReconnectBase = 40; } private struct RyuukyokuTypes { public const string NineYaochuuHai = "yao9"; public const string FourRiichi = "reach4"; public const string ThreeRon = "ron3"; public const string FourKan = "kan4"; public const string FourWind = "kaze4"; public const string NagashiMangan = "nm"; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; using Microsoft.DocAsCode.Exceptions; using Microsoft.DotNet.ProjectModel.Workspaces; public sealed class ExtractMetadataWorker : IDisposable { private readonly Lazy<MSBuildWorkspace> _workspace = new Lazy<MSBuildWorkspace>(() => MSBuildWorkspace.Create()); private static readonly string[] SupportedSolutionExtensions = { ".sln" }; private static readonly string[] SupportedProjectName = { "project.json" }; private static readonly string[] SupportedProjectExtensions = { ".csproj", ".vbproj" }; private static readonly string[] SupportedSourceFileExtensions = { ".cs", ".vb" }; private static readonly string[] SupportedVBSourceFileExtensions = { ".vb" }; private static readonly string[] SupportedCSSourceFileExtensions = { ".cs" }; private static readonly string[] SupportedAssemblyExtensions = { ".dll", ".exe" }; private static readonly string SupportedCommentFileExtension = ".xml"; private static readonly List<string> SupportedExtensions = new List<string>(); private readonly ExtractMetadataInputModel _validInput; private readonly ExtractMetadataInputModel _rawInput; private readonly bool _rebuild; private readonly bool _shouldSkipMarkup; private readonly bool _preserveRawInlineComments; private readonly string _filterConfigFile; private readonly bool _useCompatibilityFileName; static ExtractMetadataWorker() { SupportedExtensions.AddRange(SupportedSolutionExtensions); SupportedExtensions.AddRange(SupportedProjectExtensions); SupportedExtensions.AddRange(SupportedSourceFileExtensions); SupportedExtensions.AddRange(SupportedAssemblyExtensions); } public ExtractMetadataWorker(ExtractMetadataInputModel input, bool rebuild, bool useCompatibilityFileName) { _rawInput = input; _validInput = ValidateInput(input); _rebuild = rebuild; _shouldSkipMarkup = input.ShouldSkipMarkup; _preserveRawInlineComments = input.PreserveRawInlineComments; _filterConfigFile = StringExtension.ToNormalizedFullPath(input.FilterConfigFile); _useCompatibilityFileName = useCompatibilityFileName; } public async Task ExtractMetadataAsync() { var validInput = _validInput; if (validInput == null) { return; } try { foreach (var pair in validInput.Items) { var inputs = pair.Value; var outputFolder = pair.Key; await SaveAllMembersFromCacheAsync(inputs, outputFolder, _rebuild); } } catch (Exception e) { throw new ExtractMetadataException($"Error extracting metadata for {_rawInput}: {e.Message}", e); } } #region Internal For UT internal static MetadataItem GenerateYamlMetadata(Compilation compilation, IAssemblySymbol assembly = null, bool preserveRawInlineComments = false, string filterConfigFile = null, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods = null) { if (compilation == null) { return null; } object visitorContext = new object(); SymbolVisitorAdapter visitor; if (compilation.Language == "Visual Basic") { visitor = new SymbolVisitorAdapter(new CSYamlModelGenerator() + new VBYamlModelGenerator(), SyntaxLanguage.VB, compilation, preserveRawInlineComments, filterConfigFile, extensionMethods); } else if (compilation.Language == "C#") { visitor = new SymbolVisitorAdapter(new CSYamlModelGenerator() + new VBYamlModelGenerator(), SyntaxLanguage.CSharp, compilation, preserveRawInlineComments, filterConfigFile, extensionMethods); } else { Debug.Assert(false, "Language not supported: " + compilation.Language); Logger.Log(LogLevel.Error, "Language not supported: " + compilation.Language); return null; } assembly = assembly ?? compilation.Assembly; MetadataItem item = assembly.Accept(visitor); return item; } internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromCompilation(IEnumerable<Compilation> compilations) { var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>(); foreach (var compilation in compilations) { if (compilation.Assembly.MightContainExtensionMethods) { var extensions = (from n in GetAllNamespaceMembers(compilation.Assembly).Distinct() from m in GetExtensionMethodPerNamespace(n) select m).ToList(); if (extensions.Count > 0) { methods[compilation] = extensions; } } } return methods; } internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromAssembly(Compilation compilation, IEnumerable<IAssemblySymbol> assemblies) { var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>(); foreach (var assembly in assemblies) { if (assembly.MightContainExtensionMethods) { var extensions = (from n in GetAllNamespaceMembers(assembly).Distinct() from m in GetExtensionMethodPerNamespace(n) select m).ToList(); if (extensions.Count > 0) { IEnumerable<IMethodSymbol> ext; if (methods.TryGetValue(compilation, out ext)) { methods[compilation] = ext.Union(extensions); } else { methods[compilation] = extensions; } } } } return methods; } #endregion #region Private #region Check Supportability private static bool IsSupported(string filePath) { return IsSupported(filePath, SupportedExtensions, SupportedProjectName); } private static bool IsSupportedSolution(string filePath) { return IsSupported(filePath, SupportedSolutionExtensions); } private static bool IsSupportedProject(string filePath) { return IsSupported(filePath, SupportedProjectExtensions, SupportedProjectName); } private static bool IsSupportedSourceFile(string filePath) { return IsSupported(filePath, SupportedSourceFileExtensions); } private static bool IsSupportedAssemblyFile(string filePath) { return IsSupported(filePath, SupportedAssemblyExtensions); } private static bool IsSupportedVBSourceFile(string filePath) { return IsSupported(filePath, SupportedVBSourceFileExtensions); } private static bool IsSupportedCSSourceFile(string filePath) { return IsSupported(filePath, SupportedCSSourceFileExtensions); } private static bool IsSupported(string filePath, IEnumerable<string> supportedExtension, params string[] supportedFileName) { var fileExtension = Path.GetExtension(filePath); var fileName = Path.GetFileName(filePath); return supportedExtension.Contains(fileExtension, StringComparer.OrdinalIgnoreCase) || supportedFileName.Contains(fileName, StringComparer.OrdinalIgnoreCase); } #endregion private static ExtractMetadataInputModel ValidateInput(ExtractMetadataInputModel input) { if (input == null) return null; if (input.Items == null || input.Items.Count == 0) { Logger.Log(LogLevel.Warning, "No source project or file to process, exiting..."); return null; } var items = new Dictionary<string, List<string>>(); // 1. Input file should exists foreach (var pair in input.Items) { if (string.IsNullOrWhiteSpace(pair.Key)) { var value = string.Join(", ", pair.Value); Logger.Log(LogLevel.Warning, $"Empty folder name is found: '{pair.Key}': '{value}'. It is not supported, skipping."); continue; } // HashSet to guarantee the input file path is unique HashSet<string> validFilePath = new HashSet<string>(); foreach (var inputFilePath in pair.Value) { if (!string.IsNullOrEmpty(inputFilePath)) { if (File.Exists(inputFilePath)) { if (IsSupported(inputFilePath)) { var path = StringExtension.ToNormalizedFullPath(inputFilePath); validFilePath.Add(path); } else { var value = string.Join(",", SupportedExtensions); Logger.Log(LogLevel.Warning, $"File {inputFilePath} is not supported, supported file extension are: {value}. The file will be ignored."); } } else { Logger.Log(LogLevel.Warning, $"File {inputFilePath} does not exist, will be ignored."); } } } if (validFilePath.Count > 0) items.Add(pair.Key, validFilePath.ToList()); } if (items.Count > 0) { var clone = input.Clone(); clone.Items = items; return clone; } else return null; } private async Task SaveAllMembersFromCacheAsync(IEnumerable<string> inputs, string outputFolder, bool forceRebuild) { var projectCache = new ConcurrentDictionary<string, Project>(); // Project<=>Documents var documentCache = new ProjectDocumentCache(); var projectDependencyGraph = new ConcurrentDictionary<string, List<string>>(); DateTime triggeredTime = DateTime.UtcNow; var solutions = inputs.Where(s => IsSupportedSolution(s)); var projects = inputs.Where(s => IsSupportedProject(s)); var sourceFiles = inputs.Where(s => IsSupportedSourceFile(s)); var assemblyFiles = inputs.Where(s => IsSupportedAssemblyFile(s)); // Exclude not supported files from inputs inputs = solutions.Concat(projects).Concat(sourceFiles).Concat(assemblyFiles); // Add filter config file into inputs and cache if (!string.IsNullOrEmpty(_filterConfigFile)) { inputs = inputs.Concat(new string[] { _filterConfigFile }); documentCache.AddDocument(_filterConfigFile, _filterConfigFile); } // No matter is incremental or not, we have to load solutions into memory await solutions.ForEachInParallelAsync(async path => { documentCache.AddDocument(path, path); var solution = await GetSolutionAsync(path); if (solution != null) { foreach (var project in solution.Projects) { var filePath = project.FilePath; // If the project is csproj/vbproj, add to project dictionary, otherwise, ignore if (IsSupportedProject(filePath)) { projectCache.GetOrAdd(StringExtension.ToNormalizedFullPath(project.FilePath), s => project); } else { var value = string.Join(",", SupportedExtensions); Logger.Log(LogLevel.Warning, $"Project {filePath} inside solution {path} is not supported, supported file extension are: {value}. The project will be ignored."); } } } }, 60); // Load additional projects out if it is not contained in expanded solution projects = projects.Except(projectCache.Keys).Distinct(); await projects.ForEachInParallelAsync(async path => { var project = await GetProjectAsync(path); if (project != null) { projectCache.GetOrAdd(path, s => project); } }, 60); foreach (var item in projectCache) { var path = item.Key; var project = item.Value; documentCache.AddDocument(path, path); documentCache.AddDocuments(path, project.Documents.Select(s => s.FilePath)); documentCache.AddDocuments(path, project.MetadataReferences .Where(s => s is PortableExecutableReference) .Select(s => ((PortableExecutableReference)s).FilePath)); FillProjectDependencyGraph(projectCache, projectDependencyGraph, project); } documentCache.AddDocuments(sourceFiles); // Incremental check for inputs as a whole: var applicationCache = ApplicationLevelCache.Get(inputs); if (!forceRebuild) { var buildInfo = applicationCache.GetValidConfig(inputs); if (buildInfo != null && buildInfo.ShouldSkipMarkup == _shouldSkipMarkup) { IncrementalCheck check = new IncrementalCheck(buildInfo); // 1. Check if sln files/ project files and its contained documents/ source files are modified var projectModified = check.AreFilesModified(documentCache.Documents); if (!projectModified) { // 2. Check if documents/ assembly references are changed in a project // e.g. <Compile Include="*.cs* /> and file added/deleted foreach (var project in projectCache.Values) { var key = StringExtension.ToNormalizedFullPath(project.FilePath); IEnumerable<string> currentContainedFiles = documentCache.GetDocuments(project.FilePath); var previousDocumentCache = new ProjectDocumentCache(buildInfo.ContainedFiles); IEnumerable<string> previousContainedFiles = previousDocumentCache.GetDocuments(project.FilePath); if (previousContainedFiles != null && currentContainedFiles != null) { projectModified = !previousContainedFiles.SequenceEqual(currentContainedFiles); } else { // When one of them is not null, project is modified if (!object.Equals(previousContainedFiles, currentContainedFiles)) { projectModified = true; } } if (projectModified) break; } } if (!projectModified) { // Nothing modified, use the result in cache try { CopyFromCachedResult(buildInfo, inputs, outputFolder); return; } catch (Exception e) { Logger.Log(LogLevel.Warning, $"Unable to copy results from cache: {e.Message}. Rebuild starts."); } } } } // Build all the projects to get the output and save to cache List<MetadataItem> projectMetadataList = new List<MetadataItem>(); ConcurrentDictionary<string, bool> projectRebuildInfo = new ConcurrentDictionary<string, bool>(); ConcurrentDictionary<string, Compilation> compilationCache = await GetProjectCompilationAsync(projectCache); var extensionMethods = GetAllExtensionMethodsFromCompilation(compilationCache.Values); foreach (var key in GetTopologicalSortedItems(projectDependencyGraph)) { var dependencyRebuilt = projectDependencyGraph[key].Any(r => projectRebuildInfo[r]); var projectMetadataResult = await GetProjectMetadataFromCacheAsync(projectCache[key], compilationCache[key], outputFolder, documentCache, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods, dependencyRebuilt); var projectMetadata = projectMetadataResult.Item1; if (projectMetadata != null) projectMetadataList.Add(projectMetadata); projectRebuildInfo[key] = projectMetadataResult.Item2; } var csFiles = sourceFiles.Where(s => IsSupportedCSSourceFile(s)); if (csFiles.Any()) { var csContent = string.Join(Environment.NewLine, csFiles.Select(s => File.ReadAllText(s))); var csCompilation = CompilationUtility.CreateCompilationFromCsharpCode(csContent); if (csCompilation != null) { var csMetadata = await GetFileMetadataFromCacheAsync(csFiles, csCompilation, outputFolder, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods); if (csMetadata != null) projectMetadataList.Add(csMetadata.Item1); } } var vbFiles = sourceFiles.Where(s => IsSupportedVBSourceFile(s)); if (vbFiles.Any()) { var vbContent = string.Join(Environment.NewLine, vbFiles.Select(s => File.ReadAllText(s))); var vbCompilation = CompilationUtility.CreateCompilationFromVBCode(vbContent); if (vbCompilation != null) { var vbMetadata = await GetFileMetadataFromCacheAsync(vbFiles, vbCompilation, outputFolder, forceRebuild, _preserveRawInlineComments, _shouldSkipMarkup, _filterConfigFile, extensionMethods); if (vbMetadata != null) projectMetadataList.Add(vbMetadata.Item1); } } if (assemblyFiles.Any()) { var assemblyCompilation = CompilationUtility.CreateCompilationFromAssembly(assemblyFiles); if (assemblyCompilation != null) { var referencedAssemblyList = CompilationUtility.GetAssemblyFromAssemblyComplation(assemblyCompilation); var assemblyExtension = GetAllExtensionMethodsFromAssembly(assemblyCompilation, referencedAssemblyList); var assemblyMetadataValues = from assembly in referencedAssemblyList let metadata = GetAssemblyMetadataFromCacheAsync(assemblyFiles, assemblyCompilation, assembly, outputFolder, forceRebuild, _filterConfigFile, assemblyExtension) select metadata.Result.Item1; var commentFiles = (from file in assemblyFiles select Path.ChangeExtension(file, SupportedCommentFileExtension) into xmlFile where File.Exists(xmlFile) select xmlFile).ToList(); MergeCommentsHelper.MergeComments(assemblyMetadataValues, commentFiles); if (assemblyMetadataValues.Any()) { projectMetadataList.AddRange(assemblyMetadataValues); } } } var allMemebers = MergeYamlProjectMetadata(projectMetadataList); var allReferences = MergeYamlProjectReferences(projectMetadataList); if (allMemebers == null || allMemebers.Count == 0) { var value = StringExtension.ToDelimitedString(projectMetadataList.Select(s => s.Name)); Logger.Log(LogLevel.Warning, $"No metadata is generated for {value}."); applicationCache.SaveToCache(inputs, null, triggeredTime, outputFolder, null, _shouldSkipMarkup); } else { // TODO: need an intermediate folder? when to clean it up? // Save output to output folder var outputFiles = ResolveAndExportYamlMetadata(allMemebers, allReferences, outputFolder, _validInput.IndexFileName, _validInput.TocFileName, _validInput.ApiFolderName, _preserveRawInlineComments, _shouldSkipMarkup, _rawInput.ExternalReferences, _useCompatibilityFileName); applicationCache.SaveToCache(inputs, documentCache.Cache, triggeredTime, outputFolder, outputFiles, _shouldSkipMarkup); } } private static void FillProjectDependencyGraph(ConcurrentDictionary<string, Project> projectCache, ConcurrentDictionary<string, List<string>> projectDependencyGraph, Project project) { projectDependencyGraph.GetOrAdd(StringExtension.ToNormalizedFullPath(project.FilePath), _ => GetTransitiveProjectReferences(projectCache, project).Distinct().ToList()); } private static IEnumerable<string> GetTransitiveProjectReferences(ConcurrentDictionary<string, Project> projectCache, Project project) { var solution = project.Solution; foreach (var pr in project.ProjectReferences) { var refProject = solution.GetProject(pr.ProjectId); var path = StringExtension.ToNormalizedFullPath(refProject.FilePath); if (projectCache.ContainsKey(path)) { yield return path; } else { foreach (var rpr in GetTransitiveProjectReferences(projectCache, refProject)) { yield return rpr; } } } } private static async Task<ConcurrentDictionary<string, Compilation>> GetProjectCompilationAsync(ConcurrentDictionary<string, Project> projectCache) { var compilations = new ConcurrentDictionary<string, Compilation>(); foreach (var project in projectCache) { try { var compilation = await project.Value.GetCompilationAsync(); compilations.TryAdd(project.Key, compilation); } catch (Exception e) { throw new ExtractMetadataException($"Error extracting metadata for project \"{project.Key}\": {e.Message}", e); } } return compilations; } private static IEnumerable<IMethodSymbol> GetExtensionMethodPerNamespace(INamespaceSymbol space) { var typesWithExtensionMethods = space.GetTypeMembers().Where(t => t.MightContainExtensionMethods); foreach (var type in typesWithExtensionMethods) { var members = type.GetMembers(); foreach (var member in members) { if (member.Kind == SymbolKind.Method) { var method = (IMethodSymbol)member; if (method.IsExtensionMethod) { yield return method; } } } } } private static IEnumerable<INamespaceSymbol> GetAllNamespaceMembers(IAssemblySymbol assembly) { var queue = new Queue<INamespaceSymbol>(); queue.Enqueue(assembly.GlobalNamespace); while (queue.Count > 0) { var space = queue.Dequeue(); yield return space; var childSpaces = space.GetNamespaceMembers(); foreach (var child in childSpaces) { queue.Enqueue(child); } } } private static void CopyFromCachedResult(BuildInfo buildInfo, IEnumerable<string> inputs, string outputFolder) { var outputFolderSource = buildInfo.OutputFolder; var relativeFiles = buildInfo.RelatvieOutputFiles; if (relativeFiles == null) { Logger.Log(LogLevel.Warning, $"No metadata is generated for '{StringExtension.ToDelimitedString(inputs)}'."); return; } Logger.Log(LogLevel.Info, $"'{StringExtension.ToDelimitedString(inputs)}' keep up-to-date since '{buildInfo.TriggeredUtcTime.ToString()}', cached result from '{buildInfo.OutputFolder}' is used."); PathUtility.CopyFilesToFolder(relativeFiles.Select(s => Path.Combine(outputFolderSource, s)), outputFolderSource, outputFolder, true, s => Logger.Log(LogLevel.Info, s), null); } private static Task<Tuple<MetadataItem, bool>> GetProjectMetadataFromCacheAsync(Project project, Compilation compilation, string outputFolder, ProjectDocumentCache documentCache, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods, bool isReferencedProjectRebuilt) { var projectFilePath = project.FilePath; var k = documentCache.GetDocuments(projectFilePath); return GetMetadataFromProjectLevelCacheAsync( project, new[] { projectFilePath, filterConfigFile }, s => Task.FromResult(forceRebuild || s.AreFilesModified(k.Concat(new string[] { filterConfigFile })) || isReferencedProjectRebuilt), s => Task.FromResult(compilation), s => Task.FromResult(compilation.Assembly), s => { return new Dictionary<string, List<string>> { { StringExtension.ToNormalizedFullPath(s.FilePath), k.ToList() } }; }, outputFolder, preserveRawInlineComments, shouldSkipMarkup, filterConfigFile, extensionMethods); } private static Task<Tuple<MetadataItem, bool>> GetAssemblyMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, IAssemblySymbol assembly, string outputFolder, bool forceRebuild, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods) { if (files == null || !files.Any()) return null; return GetMetadataFromProjectLevelCacheAsync( files, files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))), s => Task.FromResult(compilation), s => Task.FromResult(assembly), s => null, outputFolder, false, false, filterConfigFile, extensionMethods); } private static Task<Tuple<MetadataItem, bool>> GetFileMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, string outputFolder, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods) { if (files == null || !files.Any()) return null; return GetMetadataFromProjectLevelCacheAsync( files, files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))), s => Task.FromResult(compilation), s => Task.FromResult(compilation.Assembly), s => null, outputFolder, preserveRawInlineComments, shouldSkipMarkup, filterConfigFile, extensionMethods); } private static async Task<Tuple<MetadataItem, bool>> GetMetadataFromProjectLevelCacheAsync<T>( T input, IEnumerable<string> inputKey, Func<IncrementalCheck, Task<bool>> rebuildChecker, Func<T, Task<Compilation>> compilationProvider, Func<T, Task<IAssemblySymbol>> assemblyProvider, Func<T, IDictionary<string, List<string>>> containedFilesProvider, string outputFolder, bool preserveRawInlineComments, bool shouldSkipMarkup, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods) { DateTime triggeredTime = DateTime.UtcNow; var projectLevelCache = ProjectLevelCache.Get(inputKey); var projectConfig = projectLevelCache.GetValidConfig(inputKey); var rebuildProject = true; if (projectConfig != null) { var projectCheck = new IncrementalCheck(projectConfig); rebuildProject = await rebuildChecker(projectCheck); } MetadataItem projectMetadata; if (!rebuildProject) { // Load from cache var cacheFile = Path.Combine(projectConfig.OutputFolder, projectConfig.RelatvieOutputFiles.First()); Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' keep up-to-date since '{projectConfig.TriggeredUtcTime.ToString()}', cached intermediate result '{cacheFile}' is used."); if (TryParseYamlMetadataFile(cacheFile, out projectMetadata)) { return Tuple.Create(projectMetadata, rebuildProject); } else { Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' is invalid, rebuild needed."); } } var compilation = await compilationProvider(input); var assembly = await assemblyProvider(input); projectMetadata = GenerateYamlMetadata(compilation, assembly, preserveRawInlineComments, filterConfigFile, extensionMethods); var file = Path.GetRandomFileName(); var cacheOutputFolder = projectLevelCache.OutputFolder; var path = Path.Combine(cacheOutputFolder, file); YamlUtility.Serialize(path, projectMetadata); Logger.Log(LogLevel.Verbose, $"Successfully generated metadata {cacheOutputFolder} for {projectMetadata.Name}"); IDictionary<string, List<string>> containedFiles = null; if (containedFilesProvider != null) { containedFiles = containedFilesProvider(input); } // Save to cache projectLevelCache.SaveToCache(inputKey, containedFiles, triggeredTime, cacheOutputFolder, new List<string>() { file }, shouldSkipMarkup); return Tuple.Create(projectMetadata, rebuildProject); } private static IList<string> ResolveAndExportYamlMetadata( Dictionary<string, MetadataItem> allMembers, Dictionary<string, ReferenceItem> allReferences, string folder, string indexFileName, string tocFileName, string apiFolder, bool preserveRawInlineComments, bool shouldSkipMarkup, IEnumerable<string> externalReferencePackages, bool useCompatibilityFileName) { var outputFiles = new List<string>(); var model = YamlMetadataResolver.ResolveMetadata(allMembers, allReferences, apiFolder, preserveRawInlineComments, externalReferencePackages); // 1. generate toc.yml outputFiles.Add(tocFileName); model.TocYamlViewModel.Type = MemberType.Toc; // TOC do not change var tocViewModel = model.TocYamlViewModel.ToTocViewModel(); string tocFilePath = Path.Combine(folder, tocFileName); YamlUtility.Serialize(tocFilePath, tocViewModel, YamlMime.TableOfContent); ApiReferenceViewModel indexer = new ApiReferenceViewModel(); // 2. generate each item's yaml var members = model.Members; foreach (var memberModel in members) { var outputPath = memberModel.Name + Constants.YamlExtension; if (!useCompatibilityFileName) { outputPath = outputPath.Replace('`', '-'); } outputFiles.Add(Path.Combine(apiFolder, outputPath)); string itemFilePath = Path.Combine(folder, apiFolder, outputPath); Directory.CreateDirectory(Path.GetDirectoryName(itemFilePath)); var memberViewModel = memberModel.ToPageViewModel(); memberViewModel.ShouldSkipMarkup = shouldSkipMarkup; YamlUtility.Serialize(itemFilePath, memberViewModel, YamlMime.ManagedReference); Logger.Log(LogLevel.Verbose, $"Metadata file for {memberModel.Name} is saved to {itemFilePath}."); AddMemberToIndexer(memberModel, outputPath, indexer); } // 3. generate manifest file outputFiles.Add(indexFileName); string indexFilePath = Path.Combine(folder, indexFileName); JsonUtility.Serialize(indexFilePath, indexer); return outputFiles; } private static void AddMemberToIndexer(MetadataItem memberModel, string outputPath, ApiReferenceViewModel indexer) { if (memberModel.Type == MemberType.Namespace) { indexer.Add(memberModel.Name, outputPath); } else { TreeIterator.Preorder(memberModel, null, s => s.Items, (member, parent) => { string path; if (indexer.TryGetValue(member.Name, out path)) { Logger.LogWarning($"{member.Name} already exists in {path}, the duplicate one {outputPath} will be ignored."); } else { indexer.Add(member.Name, outputPath); } return true; }); } } private static Dictionary<string, MetadataItem> MergeYamlProjectMetadata(List<MetadataItem> projectMetadataList) { if (projectMetadataList == null || projectMetadataList.Count == 0) { return null; } Dictionary<string, MetadataItem> namespaceMapping = new Dictionary<string, MetadataItem>(); Dictionary<string, MetadataItem> allMembers = new Dictionary<string, MetadataItem>(); foreach (var project in projectMetadataList) { if (project.Items != null) { foreach (var ns in project.Items) { if (ns.Type == MemberType.Namespace) { MetadataItem nsOther; if (namespaceMapping.TryGetValue(ns.Name, out nsOther)) { if (ns.Items != null) { if (nsOther.Items == null) { nsOther.Items = new List<MetadataItem>(); } foreach (var i in ns.Items) { if (!nsOther.Items.Any(s => s.Name == i.Name)) { nsOther.Items.Add(i); } else { Logger.Log(LogLevel.Info, $"{i.Name} already exists in {nsOther.Name}, ignore current one"); } } } } else { namespaceMapping.Add(ns.Name, ns); } } if (!allMembers.ContainsKey(ns.Name)) { allMembers.Add(ns.Name, ns); } ns.Items?.ForEach(s => { MetadataItem existingMetadata; if (allMembers.TryGetValue(s.Name, out existingMetadata)) { Logger.Log(LogLevel.Warning, $"Duplicate member {s.Name} is found from {existingMetadata.Source.Path} and {s.Source.Path}, use the one in {existingMetadata.Source.Path} and ignore the one from {s.Source.Path}"); } else { allMembers.Add(s.Name, s); } s.Items?.ForEach(s1 => { MetadataItem existingMetadata1; if (allMembers.TryGetValue(s1.Name, out existingMetadata1)) { Logger.Log(LogLevel.Warning, $"Duplicate member {s1.Name} is found from {existingMetadata1.Source.Path} and {s1.Source.Path}, use the one in {existingMetadata1.Source.Path} and ignore the one from {s1.Source.Path}"); } else { allMembers.Add(s1.Name, s1); } }); }); } } } return allMembers; } private static bool TryParseYamlMetadataFile(string metadataFileName, out MetadataItem projectMetadata) { projectMetadata = null; try { using (StreamReader reader = new StreamReader(metadataFileName)) { projectMetadata = YamlUtility.Deserialize<MetadataItem>(reader); return true; } } catch (Exception e) { Logger.LogInfo($"Error parsing yaml metadata file: {e.Message}"); return false; } } private static Dictionary<string, ReferenceItem> MergeYamlProjectReferences(List<MetadataItem> projectMetadataList) { if (projectMetadataList == null || projectMetadataList.Count == 0) { return null; } var result = new Dictionary<string, ReferenceItem>(); foreach (var project in projectMetadataList) { if (project.References != null) { foreach (var pair in project.References) { if (!result.ContainsKey(pair.Key)) { result[pair.Key] = pair.Value; } else { result[pair.Key].Merge(pair.Value); } } } } return result; } private async Task<Solution> GetSolutionAsync(string path) { try { return await _workspace.Value.OpenSolutionAsync(path); } catch (Exception e) { Logger.Log(LogLevel.Warning, $"Error opening solution {path}: {e.Message}. Ignored."); return null; } } private async Task<Project> GetProjectAsync(string path) { try { string name = Path.GetFileName(path); #if NETCore if (name.Equals("project.json", StringComparison.OrdinalIgnoreCase)) { var workspace = new ProjectJsonWorkspace(path); return workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == Path.GetFullPath(path)); } #endif return await _workspace.Value.OpenProjectAsync(path); } catch (Exception e) { Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.Message}. Ignored."); return null; } } /// <summary> /// use DFS to get topological sorted items /// </summary> private static IEnumerable<string> GetTopologicalSortedItems(IDictionary<string, List<string>> graph) { var visited = new HashSet<string>(); var result = new List<string>(); foreach (var node in graph.Keys) { DepthFirstTraverse(graph, node, visited, result); } return result; } private static void DepthFirstTraverse(IDictionary<string, List<string>> graph, string start, HashSet<string> visited, List<string> result) { if (!visited.Add(start)) { return; } foreach (var presequisite in graph[start]) { DepthFirstTraverse(graph, presequisite, visited, result); } result.Add(start); } public void Dispose() { if (_workspace.IsValueCreated) { _workspace.Value.Dispose(); } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BlueFace.FlowChart; using BlueFace.FlowChart.FlowChartDiagrams; using BlueFace.Sys; using BlueFace.Sys.Net; using BlueFace.VoIP.Authentication; using BlueFace.VoIP.Net; using BlueFace.VoIP.Net.RTP; using BlueFace.VoIP.Net.SIP; using IronPython.Compiler; using IronPython.Hosting; using log4net; namespace BlueFace.Net.SignallingGUI { public delegate void SIPFlowLogDelegate(string message); public class SIPFlow : BaseFlow { private const string CRLF = "\r\n"; private ManualResetEvent m_flowItemProcessing = new ManualResetEvent(false); private MemoryStream m_sipFlowDebugStream; private StreamReader m_debugStreamReader; private long m_debugStreamPosition = 0; private SIPTransport m_sipTransport; public event SIPFlowLogDelegate LogEvent; // IronPython Globals private PythonHelper pythonHelper; public SIPFlow(SIPTransport sipTransport, List<ActionDiagram> actionDiagrams, List<DecisionDiagram> decisionDiagrams) : base(actionDiagrams, decisionDiagrams) { m_sipTransport = sipTransport; pythonHelper = new PythonHelper(m_pythonEngine, m_sipTransport); pythonHelper.LogEvent += new SIPFlowLogDelegate(pythonHelper_LogEvent); //m_sipTransport.SIPTransportResponseReceived += new SIPTransportResponseReceivedDelegate(pythonHelper.SIPTransportResponseReceived); //m_pythonEngine.Import("BlueFace.VoIP.Net.SIP.*"); m_pythonEngine.Execute("import clr"); //m_pythonEngine.Execute("clr.AddReference('BlueFace.VoIP.Net')"); //m_pythonEngine.Execute("from BlueFace.VoIP.Net.SIP import *"); //m_pythonEngine.Execute("clr.AddReference('siggui')"); //m_pythonEngine.Execute("from BlueFace.Net.SignallingGUI import *"); m_pythonEngine.Globals["pythonHelper"] = pythonHelper; //m_pythonEngine.Globals["sipRequest"] = sipRequest; //SIPTransaction transaction = new SIPTransaction(sipRequest); //SIPTransport.SendSIPReliable(transaction); m_sipFlowDebugStream = new MemoryStream(); m_debugStreamReader = new StreamReader(m_sipFlowDebugStream); m_pythonEngine.SetStandardOutput(m_sipFlowDebugStream); } private void pythonHelper_LogEvent(string message) { if (LogEvent != null) { LogEvent(message); } } public void StartFlow() { try { m_sipTransport.SIPTransportRequestReceived += new SIPTransportRequestReceivedDelegate(pythonHelper.SIPTransportRequestReceived); // First item has to be an Action one. string nextFlowItemId = ProcessFlowAction(StartFlowItem); while (nextFlowItemId != null) { m_flowItemProcessing.Reset(); //m_flowItemProcessing.WaitOne(1000, false); nextFlowItemId = ProcessFlowItem(nextFlowItemId); } } catch (Exception excp) { //throw new ApplicationException("Exception running flow. " + excp.Message); logger.Error("Exception StartFlow. " + excp.Message); FireFlowDebugMessage("Exception running call flow. " + excp.Message + CRLF); } finally { m_sipTransport.SIPTransportRequestReceived -= new SIPTransportRequestReceivedDelegate(pythonHelper.SIPTransportRequestReceived); m_flowItemProcessing.Reset(); FireFlowComplete(); } } private string ProcessFlowItem(string flowItemId) { if (m_actionFlowItems.ContainsKey(flowItemId)) { return ProcessFlowAction(m_actionFlowItems[flowItemId]); } else if (m_decisionFlowItems.ContainsKey(flowItemId)) { return ProcessFlowDecision(m_decisionFlowItems[flowItemId]); } else { throw new ApplicationException("Could not locate flow item for id " + flowItemId + "."); } } /// <summary> /// Processes the Action item and returns the connection id of the next item in the flow. /// </summary> private string ProcessFlowAction(ActionFlowItem actionItem) { try { FireFlowItemInProgess(actionItem); if (!String.IsNullOrEmpty(actionItem.Contents)) { //FireFlowDebugMessage("Action: " + actionItem.Contents + CRLF); // Executing flow diagram contents using Iron Python engine. m_pythonEngine.Execute(actionItem.Contents); // Read any output from the debug stream. m_sipFlowDebugStream.Position = m_debugStreamPosition; string debugOutput = m_debugStreamReader.ReadToEnd(); m_debugStreamPosition = m_sipFlowDebugStream.Position; if(debugOutput != null && debugOutput.Trim().Length > 0) { FireFlowDebugMessage(DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff") + CRLF + debugOutput); } } // Return the flowid of the item connected downstream of this action item. return actionItem.DownstreamFlowConnection.DestinationFlowItemId; } catch (Exception excp) { logger.Error("Exception SIPFlow ProcessFlowAction. " + excp.Message); throw excp; } } private string ProcessFlowDecision(DecisionFlowItem decisionItem) { try { FireFlowItemInProgess(decisionItem); // For a decision diagram evaluate each of the conditions in order left, bottom, right and take a branch as soon as a true condition is found. if (decisionItem.LeftConnection != null && decisionItem.LeftConnection.DestinationFlowItemId != null && !String.IsNullOrEmpty(decisionItem.LeftConnection.Condition)) { bool result = m_pythonEngine.EvaluateAs<bool>(decisionItem.LeftConnection.Condition); //FireFlowDebugMessage("Decision (left): " + decisionItem.LeftConnection.Condition + " = " + result + CRLF); if (result) { return decisionItem.LeftConnection.DestinationFlowItemId; } } if (decisionItem.BottomConnection != null && decisionItem.BottomConnection.DestinationFlowItemId != null && !String.IsNullOrEmpty(decisionItem.BottomConnection.Condition)) { bool result = m_pythonEngine.EvaluateAs<bool>(decisionItem.BottomConnection.Condition); //FireFlowDebugMessage("Decision (bottom): " + decisionItem.BottomConnection.Condition + " = " + result + CRLF); if (result) { return decisionItem.BottomConnection.DestinationFlowItemId; } } if (decisionItem.RightConnection != null && decisionItem.RightConnection.DestinationFlowItemId != null && !String.IsNullOrEmpty(decisionItem.RightConnection.Condition)) { bool result = m_pythonEngine.EvaluateAs<bool>(decisionItem.RightConnection.Condition); //FireFlowDebugMessage("Decision (right): " + decisionItem.RightConnection.Condition + "= " + result + CRLF); if (result) { return decisionItem.RightConnection.DestinationFlowItemId; } } throw new ApplicationException("A downstream flow connection could not be deterimed from decision flow item with id " + decisionItem.FlowItemId + "."); } catch (Exception excp) { logger.Error("Exception SIPFlow ProcessFlowDecision. " + excp.Message); throw excp; } } } public class PythonHelper { private const string CRLF = "\r\n"; private static ILog logger = LogManager.GetLogger("flow.py"); private SIPTransport m_sipTransport; private SIPResponse m_lastFinalResponse; private SIPResponse m_lastInfoResponse; private SIPRequest m_lastRequest; private ManualResetEvent m_waitForSIPFinalResponse = new ManualResetEvent(false); private ManualResetEvent m_waitForSIPInfoResponse = new ManualResetEvent(false); private ManualResetEvent m_waitForSIPRequest = new ManualResetEvent(false); public event SIPFlowLogDelegate LogEvent; public PythonHelper(PythonEngine pythonEngine, SIPTransport sipTransport) { m_sipTransport = sipTransport; logger.Debug("PythonHelper SIP Transport local socket is " + m_sipTransport.GetDefaultTransportContact(SIPProtocolsEnum.UDP) + "."); } public SIPRequest GetInviteRequest(string inviteURIStr, string fromURIStr, string body, int rtpPort) { SIPURI inviteURI = (inviteURIStr.StartsWith("sip:")) ? SIPURI.ParseSIPURI(inviteURIStr) : SIPURI.ParseSIPURI("sip:" + inviteURIStr); SIPFromHeader fromHeader = SIPFromHeader.ParseFromHeader(fromURIStr); // (fromURIStr.StartsWith("sip:")) ? SIPFromHeader.ParseFromHeader(fromURIStr) : SIPFromHeader.ParseFromHeader("sip:" + fromURIStr); SIPToHeader toHeader = new SIPToHeader(null, inviteURI, null); SIPRequest inviteRequest = new SIPRequest(SIPMethodsEnum.INVITE, inviteURI); IPEndPoint localSIPEndPoint = m_sipTransport.GetIPEndPointsList()[0]; SIPHeader inviteHeader = new SIPHeader(fromHeader, toHeader, 1, CallProperties.CreateNewCallId()); inviteHeader.From.FromTag = CallProperties.CreateNewTag(); inviteHeader.Contact = SIPContactHeader.ParseContactHeader("sip:" + localSIPEndPoint.ToString()); inviteHeader.CSeqMethod = SIPMethodsEnum.INVITE; //inviteHeader.UnknownHeaders.Add("BlueFace-Test: 12324"); inviteRequest.Header = inviteHeader; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint.Address.ToString(), localSIPEndPoint.Port, CallProperties.CreateBranchId()); inviteRequest.Header.Via.PushViaHeader(viaHeader); rtpPort = (rtpPort != 0) ? rtpPort : Crypto.GetRandomInt(10000, 20000); string sessionId = Crypto.GetRandomInt(1000, 5000).ToString(); if (body != null && body.Trim().Length > 0) { inviteRequest.Body = body; } else { inviteRequest.Body = "v=0" + CRLF + "o=- " + sessionId + " " + sessionId + " IN IP4 " + localSIPEndPoint.Address.ToString() + CRLF + "s=session" + CRLF + "c=IN IP4 " + localSIPEndPoint.Address.ToString() + CRLF + "t=0 0" + CRLF + "m=audio " + rtpPort + " RTP/AVP 0 101" + CRLF + "a=rtpmap:0 PCMU/8000" + CRLF + "a=rtpmap:101 telephone-event/8000" + CRLF + "a=fmtp:101 0-16" + CRLF + "a=sendrecv"; } inviteRequest.Header.ContentLength = inviteRequest.Body.Length; inviteRequest.Header.ContentType = "application/sdp"; return inviteRequest; } public SIPRequest GetAuthenticatedRequest(SIPRequest origRequest, SIPResponse authReqdResponse, string username, string password) { SIPRequest authRequest = origRequest; authRequest.Header.Via.TopViaHeader.Branch = CallProperties.CreateBranchId(); authRequest.Header.From.FromTag = CallProperties.CreateNewTag(); authRequest.Header.CSeq = origRequest.Header.CSeq + 1; AuthorizationRequest authorizationRequest = authReqdResponse.Header.AuthenticationHeader.AuthRequest; authorizationRequest.SetCredentials(username, password, origRequest.URI.ToString(), origRequest.Method.ToString()); authRequest.Header.AuthenticationHeader = new SIPAuthenticationHeader(authorizationRequest); authRequest.Header.AuthenticationHeader.AuthRequest.Response = authorizationRequest.Digest; return authRequest; } public SIPRequest GetCancelRequest(SIPRequest inviteRequest) { SIPRequest cancelRequest = new SIPRequest(SIPMethodsEnum.CANCEL, inviteRequest.URI); SIPHeader cancelHeader = new SIPHeader(inviteRequest.Header.From, inviteRequest.Header.To, inviteRequest.Header.CSeq, inviteRequest.Header.CallId); cancelHeader.Via = inviteRequest.Header.Via; cancelHeader.CSeqMethod = SIPMethodsEnum.CANCEL; cancelRequest.Header = cancelHeader; return cancelRequest; } public SIPRequest GetByeRequest(SIPResponse inviteResponse) { SIPRequest byeRequest = new SIPRequest(SIPMethodsEnum.BYE, inviteResponse.Header.Contact[0].ContactURI); SIPHeader byeHeader = new SIPHeader(inviteResponse.Header.From, inviteResponse.Header.To, inviteResponse.Header.CSeq + 1, inviteResponse.Header.CallId); byeHeader.CSeqMethod = SIPMethodsEnum.BYE; IPEndPoint localSIPEndPoint = m_sipTransport.GetIPEndPointsList()[0]; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint.Address.ToString(), localSIPEndPoint.Port, CallProperties.CreateBranchId()); byeHeader.Via.PushViaHeader(viaHeader); byeRequest.Header = byeHeader; return byeRequest; } public SIPRequest GetReferRequest(SIPRequest inviteRequest, SIPResponse inviteResponse, string referToURI) { SIPRequest referRequest = new SIPRequest(SIPMethodsEnum.REFER, inviteRequest.URI); SIPHeader referHeader = new SIPHeader(inviteResponse.Header.From, inviteResponse.Header.To, inviteRequest.Header.CSeq + 1, inviteRequest.Header.CallId); referHeader.Contact = inviteRequest.Header.Contact; referHeader.CSeqMethod = SIPMethodsEnum.REFER; referHeader.ReferTo = referToURI; SIPFromHeader referredBy = new SIPFromHeader(inviteRequest.Header.From.FromName, inviteRequest.Header.From.FromURI, null); referHeader.ReferredBy = referredBy.ToString(); referHeader.AuthenticationHeader = inviteRequest.Header.AuthenticationHeader; IPEndPoint localSIPEndPoint = m_sipTransport.GetIPEndPointsList()[0]; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint.Address.ToString(), localSIPEndPoint.Port, CallProperties.CreateBranchId()); referHeader.Via.PushViaHeader(viaHeader); referRequest.Header = referHeader; return referRequest; } public SIPRequest GetRegisterRequest(string server, string toURIStr, string contactStr) { try { IPEndPoint localSIPEndPoint = m_sipTransport.GetDefaultTransportContact(SIPProtocolsEnum.UDP); SIPRequest registerRequest = new SIPRequest(SIPMethodsEnum.REGISTER, "sip:" + server); SIPHeader registerHeader = new SIPHeader(SIPFromHeader.ParseFromHeader(toURIStr), SIPToHeader.ParseToHeader(toURIStr), 1, CallProperties.CreateNewCallId()); registerHeader.From.FromTag = CallProperties.CreateNewTag(); registerHeader.Contact = SIPContactHeader.ParseContactHeader(contactStr); SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint.Address.ToString(), localSIPEndPoint.Port, CallProperties.CreateBranchId()); registerHeader.Via.PushViaHeader(viaHeader); registerHeader.CSeqMethod = SIPMethodsEnum.REGISTER; registerHeader.Expires = SIPConstants.DEFAULT_REGISTEREXPIRY_SECONDS; registerRequest.Header = registerHeader; return registerRequest; } catch (Exception excp) { logger.Error("Exception GetRegisterRequest. " + excp.Message); throw new ApplicationException("GetRegisterRequest " + excp.GetType().ToString() + ". " + excp.Message); } } public SIPRequest GetSIPRequest(SIPMethodsEnum sipMethod, string requestURIStr, string fromURIStr) { return GetSIPRequest(sipMethod, requestURIStr, fromURIStr, 1, CallProperties.CreateNewCallId(), null, null); } public SIPRequest GetSIPRequest(SIPMethodsEnum sipMethod, string requestURIStr, string fromURIStr, int cseq, string callId) { return GetSIPRequest(sipMethod, requestURIStr, fromURIStr, cseq, callId, null, null); } public SIPRequest GetSIPRequest(SIPMethodsEnum sipMethod, string requestURIStr, string fromURIStr, int cseq, string callId, string contentType, string body) { SIPURI requestURI = (requestURIStr.StartsWith("sip:")) ? SIPURI.ParseSIPURI(requestURIStr) : SIPURI.ParseSIPURI("sip:" + requestURIStr); SIPURI fromURI = (fromURIStr.StartsWith("sip:")) ? SIPURI.ParseSIPURI(fromURIStr) : SIPURI.ParseSIPURI("sip:" + fromURIStr); SIPFromHeader fromHeader = new SIPFromHeader(null, fromURI, CallProperties.CreateNewTag()); SIPToHeader toHeader = new SIPToHeader(null, requestURI, null); SIPRequest sipRequest = new SIPRequest(sipMethod, requestURI); IPEndPoint localSIPEndPoint = m_sipTransport.GetIPEndPointsList()[0]; SIPHeader sipHeader = new SIPHeader(fromHeader, toHeader, cseq, callId); sipHeader.Contact = SIPContactHeader.ParseContactHeader("sip:" + localSIPEndPoint.ToString()); sipHeader.CSeqMethod = sipMethod; sipRequest.Header = sipHeader; SIPViaHeader viaHeader = new SIPViaHeader(localSIPEndPoint.Address.ToString(), localSIPEndPoint.Port, CallProperties.CreateBranchId()); sipRequest.Header.Via.PushViaHeader(viaHeader); if (body != null && body.Trim().Length > 0) { sipRequest.Body = body; //sipRequest.Body = "Signal=5\r\nDuration=250"; //sipRequest.Body = "<rtcp>blah blah blah</rtcp>"; sipRequest.Header.ContentLength = sipRequest.Body.Length; sipRequest.Header.ContentType = contentType; } return sipRequest; } public SIPRequest ParseSIPRequest(string sipRequestStr) { // Strings from Rich text boxes use a \n end of line character. sipRequestStr = Regex.Replace(sipRequestStr, "\n", "\r\n"); sipRequestStr = Regex.Replace(sipRequestStr, "\r\r", "\r"); SIPMessage sipMessage = SIPMessage.ParseSIPMessage(sipRequestStr, null, null); return SIPRequest.ParseSIPRequest(sipMessage); } public void SendSIPRequest(SIPRequest sipRequest) { SendSIPRequest(sipRequest, sipRequest.URI.GetURIEndPoint().ToString()); } public void SendSIPRequest(SIPRequest sipRequest, string dstSocket) { //ResetSIPResponse(); if (sipRequest.Method == SIPMethodsEnum.INVITE) { //m_inviteRequest = sipRequest; UACInviteTransaction inviteTransaction = m_sipTransport.CreateUACTransaction(sipRequest, IPSocket.GetIPEndPoint(dstSocket), m_sipTransport.GetTransportContact(null), SIPProtocolsEnum.UDP); inviteTransaction.UACInviteTransactionInformationResponseReceived += new SIPTransactionResponseReceivedDelegate(TransactionInformationResponseReceived); inviteTransaction.UACInviteTransactionFinalResponseReceived += new SIPTransactionResponseReceivedDelegate(TransactionFinalResponseReceived); m_sipTransport.SendSIPReliable(inviteTransaction); } else { SIPNonInviteTransaction sipTransaction = m_sipTransport.CreateNonInviteTransaction(sipRequest, IPSocket.GetIPEndPoint(dstSocket), m_sipTransport.GetTransportContact(null), SIPProtocolsEnum.UDP); sipTransaction.NonInviteTransactionFinalResponseReceived += new SIPTransactionResponseReceivedDelegate(TransactionFinalResponseReceived); m_sipTransport.SendSIPReliable(sipTransaction); } } private void TransactionInformationResponseReceived(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse) { m_lastInfoResponse = sipResponse; m_waitForSIPInfoResponse.Set(); } private void TransactionFinalResponseReceived(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, SIPTransaction sipTransaction, SIPResponse sipResponse) { m_lastFinalResponse = sipResponse; m_waitForSIPFinalResponse.Set(); } public void SIPTransportRequestReceived(SIPProtocolsEnum protocol, IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, SIPRequest sipRequest) { if (sipRequest.Method == SIPMethodsEnum.BYE) { // Send an Ok response. SIPResponse okResponse = GetResponse(sipRequest.Header, SIPResponseStatusCodesEnum.Ok); m_sipTransport.SendResponseFrom(localEndPoint, remoteEndPoint, protocol, okResponse); } else if (sipRequest.Method == SIPMethodsEnum.NOTIFY) { // Send an not supported response. //SIPResponse notSupportedResponse = GetResponse(sipRequest.Header, SIPResponseStatusCodesEnum.MethodNotAllowed); //SIPTransport.SendResponseFrom(localEndPoint, remoteEndPoint, notSupportedResponse); // Send an Ok response. SIPResponse okResponse = GetResponse(sipRequest.Header, SIPResponseStatusCodesEnum.Ok); okResponse.Header.Contact = null; m_sipTransport.SendResponseFrom(localEndPoint, remoteEndPoint, protocol, okResponse); } else { m_lastRequest = sipRequest; m_waitForSIPRequest.Set(); } } public SIPResponse WaitForInfoResponse(int waitSeconds, SIPRequest sipRequest) { DateTime startWaitTime = DateTime.Now; m_waitForSIPInfoResponse.Reset(); m_lastInfoResponse = null; while (m_lastInfoResponse == null && DateTime.Now.Subtract(startWaitTime).TotalSeconds < waitSeconds) { m_waitForSIPInfoResponse.WaitOne(Convert.ToInt32((waitSeconds - DateTime.Now.Subtract(startWaitTime).TotalSeconds) * 1000), false); if (m_lastInfoResponse != null && m_lastInfoResponse.Header.CallId == sipRequest.Header.CallId) { break; } else { m_lastInfoResponse = null; } } return m_lastInfoResponse; } public SIPResponse WaitForFinalResponse(int waitSeconds, SIPRequest sipRequest) { DateTime startWaitTime = DateTime.Now; m_waitForSIPFinalResponse.Reset(); m_lastFinalResponse = null; while (m_lastFinalResponse == null && DateTime.Now.Subtract(startWaitTime).TotalSeconds < waitSeconds) { m_waitForSIPFinalResponse.WaitOne(Convert.ToInt32((waitSeconds - DateTime.Now.Subtract(startWaitTime).TotalSeconds) * 1000), false); if (m_lastFinalResponse != null && m_lastFinalResponse.Header.CallId == sipRequest.Header.CallId) { break; } else { m_lastFinalResponse = null; } } return m_lastFinalResponse; } public SIPRequest WaitForRequest(int waitSeconds) { m_waitForSIPRequest.Reset(); m_waitForSIPRequest.WaitOne(waitSeconds * 1000, false); return m_lastRequest; } private SIPResponse GetResponse(SIPHeader requestHeader, SIPResponseStatusCodesEnum responseCode) { try { SIPResponse response = new SIPResponse(responseCode); response.Header = new SIPHeader(requestHeader.Contact, requestHeader.From, requestHeader.To, requestHeader.CSeq, requestHeader.CallId); response.Header.CSeqMethod = requestHeader.CSeqMethod; response.Header.Via = requestHeader.Via; response.Header.MaxForwards = Int32.MinValue; return response; } catch (Exception excp) { logger.Error("Exception GetResponse. " + excp.Message); throw excp; } } public void SendRTPPacket(string sourceSocket, string destinationSocket) { try { //logger.Debug("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + "."); FireLogEvent("Attempting to send RTP packet from " + sourceSocket + " to " + destinationSocket + "."); IPEndPoint sourceEP = IPSocket.GetIPEndPoint(sourceSocket); IPEndPoint destEP = IPSocket.GetIPEndPoint(destinationSocket); RTPPacket rtpPacket = new RTPPacket(80); rtpPacket.Header.SequenceNumber = (UInt16)6500; rtpPacket.Header.Timestamp = 100000; UDPPacket udpPacket = new UDPPacket(sourceEP.Port, destEP.Port, rtpPacket.GetBytes()); IPv4Header ipHeader = new IPv4Header(ProtocolType.Udp, Crypto.GetRandomInt(6), sourceEP.Address, destEP.Address); IPv4Packet ipPacket = new IPv4Packet(ipHeader, udpPacket.GetBytes()); byte[] data = ipPacket.GetBytes(); Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); rawSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); rawSocket.SendTo(data, destEP); } catch (Exception excp) { logger.Error("Exception SendRTPPacket. " + excp.Message); } } public void FireLogEvent(string message) { if (LogEvent != null) { LogEvent(message); } } } }
//----------------------------------------------------------------------- // <copyright file="Network.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> // Parts of this task are based on code from (http://sedodream.codeplex.com). It is used here with permission. //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Computer { using System; using System.Globalization; using System.Net; using System.Net.NetworkInformation; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>GetDnsHostName</i> (<b>Required: HostName</b> <b>Output:</b> DnsHostName)</para> /// <para><i>GetInternalIP</i> (<b>Output:</b> Ip)</para> /// <para><i>GetRemoteIP</i> (<b>Required: </b>HostName <b>Output:</b> Ip)</para> /// <para><i>Ping</i> (<b>Required: </b> HostName <b>Optional: </b>Timeout, PingCount <b>Output:</b> Exists)</para> /// <para><b>Remote Execution Support:</b> NA</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)"/> /// <Target Name="Default"> /// <!-- Get the Machine IP Addresses --> /// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetInternalIP"> /// <Output TaskParameter="IP" ItemName="TheIP"/> /// </MSBuild.ExtensionPack.Computer.Network> /// <Message Text="The IP: %(TheIP.Identity)"/> /// <!-- Get Remote IP Addresses --> /// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetRemoteIP" HostName="www.freetodev.com"> /// <Output TaskParameter="IP" ItemName="TheRemoteIP"/> /// </MSBuild.ExtensionPack.Computer.Network> /// <Message Text="The Remote IP: %(TheRemoteIP.Identity)"/> /// <!-- Ping a host --> /// <MSBuild.ExtensionPack.Computer.Network TaskAction="Ping" HostName="www.freetodev.com"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.Network> /// <Message Text="Exists: $(DoesExist)"/> /// <!-- Gets the fully-qualified domain name for a hostname. --> /// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetDnsHostName" HostName="192.168.0.15"> /// <Output TaskParameter="DnsHostName" PropertyName="HostEntryName" /> /// </MSBuild.ExtensionPack.Computer.Network> /// <Message Text="Host Entry name: $(HostEntryName)" /> /// </Target> /// </Project> /// ]]></code> /// </example> [HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/2719abfe-553d-226c-d75f-2964c24f1965.htm")] public class Network : BaseTask { private const string GetDnsHostNameTaskAction = "GetDnsHostName"; private const string GetInternalIPTaskAction = "GetInternalIP"; private const string GetRemoteIPTaskAction = "GetRemoteIP"; private const string PingTaskAction = "Ping"; private int pingCount = 5; private int timeout = 3000; [DropdownValue(GetInternalIPTaskAction)] [DropdownValue(GetRemoteIPTaskAction)] [DropdownValue(PingTaskAction)] public override string TaskAction { get { return base.TaskAction; } set { base.TaskAction = value; } } /// <summary> /// Sets the HostName / IP address /// </summary> [TaskAction(GetDnsHostNameTaskAction, true)] [TaskAction(PingTaskAction, true)] public string HostName { get; set; } /// <summary> /// Gets whether the Host Exists /// </summary> [Output] [TaskAction(PingTaskAction, false)] public bool Exists { get; private set; } /// <summary> /// Sets the number of pings to attempt. Default is 5. /// </summary> [TaskAction(PingTaskAction, false)] public int PingCount { get { return this.pingCount; } set { this.pingCount = value; } } /// <summary> /// Sets the timeout in ms for a Ping. Default is 3000 /// </summary> [TaskAction(PingTaskAction, false)] public int Timeout { get { return this.timeout; } set { this.timeout = value; } } /// <summary> /// Gets the IP's /// </summary> [Output] public ITaskItem[] IP { get; set; } /// <summary> /// Gets the DnsHostName /// </summary> [Output] public string DnsHostName { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } switch (this.TaskAction) { case PingTaskAction: this.Ping(); break; case GetInternalIPTaskAction: this.GetInternalIP(); break; case GetRemoteIPTaskAction: this.GetRemoteIP(); break; case GetDnsHostNameTaskAction: this.GetDnsHostName(); break; default: Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private void GetDnsHostName() { if (string.IsNullOrEmpty(this.HostName)) { Log.LogError("HostName is required"); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting host entry name for: {0}", this.HostName)); var hostEntry = Dns.GetHostEntry(this.HostName); this.DnsHostName = hostEntry.HostName; } private void GetRemoteIP() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Get Remote IP for: {0}", this.HostName)); IPAddress[] addresslist = Dns.GetHostAddresses(this.HostName); this.IP = new ITaskItem[addresslist.Length]; for (int i = 0; i < addresslist.Length; i++) { ITaskItem newItem = new TaskItem(addresslist[i].ToString()); this.IP[i] = newItem; } } private void GetInternalIP() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Get Internal IP for: {0}", Environment.MachineName)); string hostName = Dns.GetHostName(); if (string.IsNullOrEmpty(hostName)) { this.LogTaskWarning("Trying to determine IP addresses but Dns.GetHostName() returned an empty value"); return; } IPHostEntry hostEntry = Dns.GetHostEntry(hostName); if (hostEntry.AddressList == null || hostEntry.AddressList.Length <= 0) { this.LogTaskWarning("Trying to determine internal IP addresses but address list is empty"); return; } this.IP = new ITaskItem[hostEntry.AddressList.Length]; for (int i = 0; i < hostEntry.AddressList.Length; i++) { ITaskItem newItem = new TaskItem(hostEntry.AddressList[i].ToString()); this.IP[i] = newItem; } } private void Ping() { const int BufferSize = 32; const int TimeToLive = 128; byte[] buffer = new byte[BufferSize]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = unchecked((byte)i); } using (System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping()) { PingOptions options = new PingOptions(TimeToLive, false); for (int i = 0; i < this.PingCount; i++) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Pinging {0}", this.HostName)); PingReply response = pinger.Send(this.HostName, this.Timeout, buffer, options); if (response != null && response.Status == IPStatus.Success) { this.Exists = true; return; } if (response != null) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response Status {0}", response.Status)); } System.Threading.Thread.Sleep(1000); } this.Exists = false; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Microsoft.Azure.Management.Automation.Specification.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for node reports. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> internal partial class DscNodeReportsOperations : IServiceOperations<AutomationManagementClient>, IDscNodeReportsOperations { /// <summary> /// Initializes a new instance of the DscNodeReportsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DscNodeReportsOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the Dsc node report data by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeId'> /// Required. The Dsc node id. /// </param> /// <param name='reportId'> /// Required. The report id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get dsc node report operation. /// </returns> public async Task<DscNodeReportGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("nodeId", nodeId); tracingParameters.Add("reportId", reportId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; url = url + Uri.EscapeDataString(nodeId.ToString()); url = url + "/reports/"; url = url + Uri.EscapeDataString(reportId.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DscNodeReportGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeReportGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNodeReport nodeReportInstance = new DscNodeReport(); result.NodeReport = nodeReportInstance; JToken endTimeValue = responseDoc["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); nodeReportInstance.EndTime = endTimeInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); nodeReportInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); nodeReportInstance.StartTime = startTimeInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); nodeReportInstance.Type = typeInstance; } JToken reportIdValue = responseDoc["reportId"]; if (reportIdValue != null && reportIdValue.Type != JTokenType.Null) { Guid reportIdInstance = Guid.Parse(((string)reportIdValue)); nodeReportInstance.ReportId = reportIdInstance; } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); nodeReportInstance.Status = statusInstance; } JToken refreshModeValue = responseDoc["refreshMode"]; if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null) { string refreshModeInstance = ((string)refreshModeValue); nodeReportInstance.RefreshMode = refreshModeInstance; } JToken rebootRequestedValue = responseDoc["rebootRequested"]; if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null) { string rebootRequestedInstance = ((string)rebootRequestedValue); nodeReportInstance.RebootRequested = rebootRequestedInstance; } JToken reportFormatVersionValue = responseDoc["reportFormatVersion"]; if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null) { string reportFormatVersionInstance = ((string)reportFormatVersionValue); nodeReportInstance.ReportFormatVersion = reportFormatVersionInstance; } JToken configurationVersionValue = responseDoc["configurationVersion"]; if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null) { string configurationVersionInstance = ((string)configurationVersionValue); nodeReportInstance.ConfigurationVersion = configurationVersionInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeReportInstance.Id = idInstance; } JToken errorsArray = responseDoc["errors"]; if (errorsArray != null && errorsArray.Type != JTokenType.Null) { foreach (JToken errorsValue in ((JArray)errorsArray)) { DscReportError dscReportErrorInstance = new DscReportError(); nodeReportInstance.Errors.Add(dscReportErrorInstance); JToken errorSourceValue = errorsValue["errorSource"]; if (errorSourceValue != null && errorSourceValue.Type != JTokenType.Null) { string errorSourceInstance = ((string)errorSourceValue); dscReportErrorInstance.ErrorSource = errorSourceInstance; } JToken resourceIdValue = errorsValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); dscReportErrorInstance.ResourceId = resourceIdInstance; } JToken errorCodeValue = errorsValue["errorCode"]; if (errorCodeValue != null && errorCodeValue.Type != JTokenType.Null) { string errorCodeInstance = ((string)errorCodeValue); dscReportErrorInstance.ErrorCode = errorCodeInstance; } JToken errorMessageValue = errorsValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); dscReportErrorInstance.ErrorMessage = errorMessageInstance; } JToken localeValue = errorsValue["locale"]; if (localeValue != null && localeValue.Type != JTokenType.Null) { string localeInstance = ((string)localeValue); dscReportErrorInstance.Locale = localeInstance; } JToken errorDetailsValue = errorsValue["errorDetails"]; if (errorDetailsValue != null && errorDetailsValue.Type != JTokenType.Null) { string errorDetailsInstance = ((string)errorDetailsValue); dscReportErrorInstance.ErrorDetails = errorDetailsInstance; } } } JToken resourcesArray = responseDoc["resources"]; if (resourcesArray != null && resourcesArray.Type != JTokenType.Null) { foreach (JToken resourcesValue in ((JArray)resourcesArray)) { DscReportResource dscReportResourceInstance = new DscReportResource(); nodeReportInstance.Resources.Add(dscReportResourceInstance); JToken resourceIdValue2 = resourcesValue["resourceId"]; if (resourceIdValue2 != null && resourceIdValue2.Type != JTokenType.Null) { string resourceIdInstance2 = ((string)resourceIdValue2); dscReportResourceInstance.ReportResourceId = resourceIdInstance2; } JToken sourceInfoValue = resourcesValue["sourceInfo"]; if (sourceInfoValue != null && sourceInfoValue.Type != JTokenType.Null) { string sourceInfoInstance = ((string)sourceInfoValue); dscReportResourceInstance.SourceInfo = sourceInfoInstance; } JToken dependsOnArray = resourcesValue["dependsOn"]; if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null) { foreach (JToken dependsOnValue in ((JArray)dependsOnArray)) { DscReportResourceNavigation dscReportResourceNavigationInstance = new DscReportResourceNavigation(); dscReportResourceInstance.DependsOn.Add(dscReportResourceNavigationInstance); JToken resourceIdValue3 = dependsOnValue["resourceId"]; if (resourceIdValue3 != null && resourceIdValue3.Type != JTokenType.Null) { string resourceIdInstance3 = ((string)resourceIdValue3); dscReportResourceNavigationInstance.ReportResourceId = resourceIdInstance3; } } } JToken moduleNameValue = resourcesValue["moduleName"]; if (moduleNameValue != null && moduleNameValue.Type != JTokenType.Null) { string moduleNameInstance = ((string)moduleNameValue); dscReportResourceInstance.ModuleName = moduleNameInstance; } JToken moduleVersionValue = resourcesValue["moduleVersion"]; if (moduleVersionValue != null && moduleVersionValue.Type != JTokenType.Null) { string moduleVersionInstance = ((string)moduleVersionValue); dscReportResourceInstance.ModuleVersion = moduleVersionInstance; } JToken resourceNameValue = resourcesValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); dscReportResourceInstance.ResourceName = resourceNameInstance; } JToken errorValue = resourcesValue["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { string errorInstance = ((string)errorValue); dscReportResourceInstance.Error = errorInstance; } JToken statusValue2 = resourcesValue["status"]; if (statusValue2 != null && statusValue2.Type != JTokenType.Null) { string statusInstance2 = ((string)statusValue2); dscReportResourceInstance.Status = statusInstance2; } JToken durationInSecondsValue = resourcesValue["durationInSeconds"]; if (durationInSecondsValue != null && durationInSecondsValue.Type != JTokenType.Null) { double durationInSecondsInstance = ((double)durationInSecondsValue); dscReportResourceInstance.DurationInSeconds = durationInSecondsInstance; } JToken startDateValue = resourcesValue["startDate"]; if (startDateValue != null && startDateValue.Type != JTokenType.Null) { DateTimeOffset startDateInstance = ((DateTimeOffset)startDateValue); dscReportResourceInstance.StartDate = startDateInstance; } } } JToken metaConfigurationValue = responseDoc["metaConfiguration"]; if (metaConfigurationValue != null && metaConfigurationValue.Type != JTokenType.Null) { DscMetaConfiguration metaConfigurationInstance = new DscMetaConfiguration(); nodeReportInstance.MetaConfiguration = metaConfigurationInstance; JToken configurationModeFrequencyMinsValue = metaConfigurationValue["configurationModeFrequencyMins"]; if (configurationModeFrequencyMinsValue != null && configurationModeFrequencyMinsValue.Type != JTokenType.Null) { int configurationModeFrequencyMinsInstance = ((int)configurationModeFrequencyMinsValue); metaConfigurationInstance.ConfigurationModeFrequencyMins = configurationModeFrequencyMinsInstance; } JToken rebootNodeIfNeededValue = metaConfigurationValue["rebootNodeIfNeeded"]; if (rebootNodeIfNeededValue != null && rebootNodeIfNeededValue.Type != JTokenType.Null) { bool rebootNodeIfNeededInstance = ((bool)rebootNodeIfNeededValue); metaConfigurationInstance.RebootNodeIfNeeded = rebootNodeIfNeededInstance; } JToken configurationModeValue = metaConfigurationValue["configurationMode"]; if (configurationModeValue != null && configurationModeValue.Type != JTokenType.Null) { string configurationModeInstance = ((string)configurationModeValue); metaConfigurationInstance.ConfigurationMode = configurationModeInstance; } JToken actionAfterRebootValue = metaConfigurationValue["actionAfterReboot"]; if (actionAfterRebootValue != null && actionAfterRebootValue.Type != JTokenType.Null) { string actionAfterRebootInstance = ((string)actionAfterRebootValue); metaConfigurationInstance.ActionAfterReboot = actionAfterRebootInstance; } JToken certificateIdValue = metaConfigurationValue["certificateId"]; if (certificateIdValue != null && certificateIdValue.Type != JTokenType.Null) { string certificateIdInstance = ((string)certificateIdValue); metaConfigurationInstance.CertificateId = certificateIdInstance; } JToken refreshFrequencyMinsValue = metaConfigurationValue["refreshFrequencyMins"]; if (refreshFrequencyMinsValue != null && refreshFrequencyMinsValue.Type != JTokenType.Null) { int refreshFrequencyMinsInstance = ((int)refreshFrequencyMinsValue); metaConfigurationInstance.RefreshFrequencyMins = refreshFrequencyMinsInstance; } JToken allowModuleOverwriteValue = metaConfigurationValue["allowModuleOverwrite"]; if (allowModuleOverwriteValue != null && allowModuleOverwriteValue.Type != JTokenType.Null) { bool allowModuleOverwriteInstance = ((bool)allowModuleOverwriteValue); metaConfigurationInstance.AllowModuleOverwrite = allowModuleOverwriteInstance; } } JToken hostNameValue = responseDoc["hostName"]; if (hostNameValue != null && hostNameValue.Type != JTokenType.Null) { string hostNameInstance = ((string)hostNameValue); nodeReportInstance.HostName = hostNameInstance; } JToken iPV4AddressesArray = responseDoc["iPV4Addresses"]; if (iPV4AddressesArray != null && iPV4AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV4AddressesValue in ((JArray)iPV4AddressesArray)) { nodeReportInstance.IPV4Addresses.Add(((string)iPV4AddressesValue)); } } JToken iPV6AddressesArray = responseDoc["iPV6Addresses"]; if (iPV6AddressesArray != null && iPV6AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV6AddressesValue in ((JArray)iPV6AddressesArray)) { nodeReportInstance.IPV6Addresses.Add(((string)iPV6AddressesValue)); } } JToken numberOfResourcesValue = responseDoc["numberOfResources"]; if (numberOfResourcesValue != null && numberOfResourcesValue.Type != JTokenType.Null) { int numberOfResourcesInstance = ((int)numberOfResourcesValue); nodeReportInstance.NumberOfResources = numberOfResourcesInstance; } JToken rawErrorsValue = responseDoc["rawErrors"]; if (rawErrorsValue != null && rawErrorsValue.Type != JTokenType.Null) { string rawErrorsInstance = ((string)rawErrorsValue); nodeReportInstance.RawErrors = rawErrorsInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the Dsc node reports by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeId'> /// Required. The Dsc node id. /// </param> /// <param name='reportId'> /// Required. The report id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get node report content operation. /// </returns> public async Task<DscNodeReportGetContentResponse> GetContentAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("nodeId", nodeId); tracingParameters.Add("reportId", reportId); TracingAdapter.Enter(invocationId, this, "GetContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; url = url + Uri.EscapeDataString(nodeId.ToString()); url = url + "/reports/"; url = url + Uri.EscapeDataString(reportId.ToString()); url = url + "/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DscNodeReportGetContentResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeReportGetContentResponse(); result.Content = responseContent; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the Dsc node report list by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> public async Task<DscNodeReportListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodes/"; if (parameters != null && parameters.NodeId != null) { url = url + Uri.EscapeDataString(parameters.NodeId.ToString()); } url = url + "/reports"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.StartTime != null) { odataFilter.Add("startTime ge " + Uri.EscapeDataString(parameters.StartTime)); } if (parameters != null && parameters.EndTime != null) { odataFilter.Add("endTime le " + Uri.EscapeDataString(parameters.EndTime)); } if (parameters != null && parameters.Type != null) { odataFilter.Add("type eq '" + Uri.EscapeDataString(parameters.Type) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(" and ", odataFilter)); } queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DscNodeReportListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeReportListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeReport dscNodeReportInstance = new DscNodeReport(); result.NodeReports.Add(dscNodeReportInstance); JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); dscNodeReportInstance.EndTime = endTimeInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); dscNodeReportInstance.StartTime = startTimeInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeReportInstance.Type = typeInstance; } JToken reportIdValue = valueValue["reportId"]; if (reportIdValue != null && reportIdValue.Type != JTokenType.Null) { Guid reportIdInstance = Guid.Parse(((string)reportIdValue)); dscNodeReportInstance.ReportId = reportIdInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dscNodeReportInstance.Status = statusInstance; } JToken refreshModeValue = valueValue["refreshMode"]; if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null) { string refreshModeInstance = ((string)refreshModeValue); dscNodeReportInstance.RefreshMode = refreshModeInstance; } JToken rebootRequestedValue = valueValue["rebootRequested"]; if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null) { string rebootRequestedInstance = ((string)rebootRequestedValue); dscNodeReportInstance.RebootRequested = rebootRequestedInstance; } JToken reportFormatVersionValue = valueValue["reportFormatVersion"]; if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null) { string reportFormatVersionInstance = ((string)reportFormatVersionValue); dscNodeReportInstance.ReportFormatVersion = reportFormatVersionInstance; } JToken configurationVersionValue = valueValue["configurationVersion"]; if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null) { string configurationVersionInstance = ((string)configurationVersionValue); dscNodeReportInstance.ConfigurationVersion = configurationVersionInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeReportInstance.Id = idInstance; } JToken errorsArray = valueValue["errors"]; if (errorsArray != null && errorsArray.Type != JTokenType.Null) { foreach (JToken errorsValue in ((JArray)errorsArray)) { DscReportError dscReportErrorInstance = new DscReportError(); dscNodeReportInstance.Errors.Add(dscReportErrorInstance); JToken errorSourceValue = errorsValue["errorSource"]; if (errorSourceValue != null && errorSourceValue.Type != JTokenType.Null) { string errorSourceInstance = ((string)errorSourceValue); dscReportErrorInstance.ErrorSource = errorSourceInstance; } JToken resourceIdValue = errorsValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); dscReportErrorInstance.ResourceId = resourceIdInstance; } JToken errorCodeValue = errorsValue["errorCode"]; if (errorCodeValue != null && errorCodeValue.Type != JTokenType.Null) { string errorCodeInstance = ((string)errorCodeValue); dscReportErrorInstance.ErrorCode = errorCodeInstance; } JToken errorMessageValue = errorsValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); dscReportErrorInstance.ErrorMessage = errorMessageInstance; } JToken localeValue = errorsValue["locale"]; if (localeValue != null && localeValue.Type != JTokenType.Null) { string localeInstance = ((string)localeValue); dscReportErrorInstance.Locale = localeInstance; } JToken errorDetailsValue = errorsValue["errorDetails"]; if (errorDetailsValue != null && errorDetailsValue.Type != JTokenType.Null) { string errorDetailsInstance = ((string)errorDetailsValue); dscReportErrorInstance.ErrorDetails = errorDetailsInstance; } } } JToken resourcesArray = valueValue["resources"]; if (resourcesArray != null && resourcesArray.Type != JTokenType.Null) { foreach (JToken resourcesValue in ((JArray)resourcesArray)) { DscReportResource dscReportResourceInstance = new DscReportResource(); dscNodeReportInstance.Resources.Add(dscReportResourceInstance); JToken resourceIdValue2 = resourcesValue["resourceId"]; if (resourceIdValue2 != null && resourceIdValue2.Type != JTokenType.Null) { string resourceIdInstance2 = ((string)resourceIdValue2); dscReportResourceInstance.ReportResourceId = resourceIdInstance2; } JToken sourceInfoValue = resourcesValue["sourceInfo"]; if (sourceInfoValue != null && sourceInfoValue.Type != JTokenType.Null) { string sourceInfoInstance = ((string)sourceInfoValue); dscReportResourceInstance.SourceInfo = sourceInfoInstance; } JToken dependsOnArray = resourcesValue["dependsOn"]; if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null) { foreach (JToken dependsOnValue in ((JArray)dependsOnArray)) { DscReportResourceNavigation dscReportResourceNavigationInstance = new DscReportResourceNavigation(); dscReportResourceInstance.DependsOn.Add(dscReportResourceNavigationInstance); JToken resourceIdValue3 = dependsOnValue["resourceId"]; if (resourceIdValue3 != null && resourceIdValue3.Type != JTokenType.Null) { string resourceIdInstance3 = ((string)resourceIdValue3); dscReportResourceNavigationInstance.ReportResourceId = resourceIdInstance3; } } } JToken moduleNameValue = resourcesValue["moduleName"]; if (moduleNameValue != null && moduleNameValue.Type != JTokenType.Null) { string moduleNameInstance = ((string)moduleNameValue); dscReportResourceInstance.ModuleName = moduleNameInstance; } JToken moduleVersionValue = resourcesValue["moduleVersion"]; if (moduleVersionValue != null && moduleVersionValue.Type != JTokenType.Null) { string moduleVersionInstance = ((string)moduleVersionValue); dscReportResourceInstance.ModuleVersion = moduleVersionInstance; } JToken resourceNameValue = resourcesValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); dscReportResourceInstance.ResourceName = resourceNameInstance; } JToken errorValue = resourcesValue["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { string errorInstance = ((string)errorValue); dscReportResourceInstance.Error = errorInstance; } JToken statusValue2 = resourcesValue["status"]; if (statusValue2 != null && statusValue2.Type != JTokenType.Null) { string statusInstance2 = ((string)statusValue2); dscReportResourceInstance.Status = statusInstance2; } JToken durationInSecondsValue = resourcesValue["durationInSeconds"]; if (durationInSecondsValue != null && durationInSecondsValue.Type != JTokenType.Null) { double durationInSecondsInstance = ((double)durationInSecondsValue); dscReportResourceInstance.DurationInSeconds = durationInSecondsInstance; } JToken startDateValue = resourcesValue["startDate"]; if (startDateValue != null && startDateValue.Type != JTokenType.Null) { DateTimeOffset startDateInstance = ((DateTimeOffset)startDateValue); dscReportResourceInstance.StartDate = startDateInstance; } } } JToken metaConfigurationValue = valueValue["metaConfiguration"]; if (metaConfigurationValue != null && metaConfigurationValue.Type != JTokenType.Null) { DscMetaConfiguration metaConfigurationInstance = new DscMetaConfiguration(); dscNodeReportInstance.MetaConfiguration = metaConfigurationInstance; JToken configurationModeFrequencyMinsValue = metaConfigurationValue["configurationModeFrequencyMins"]; if (configurationModeFrequencyMinsValue != null && configurationModeFrequencyMinsValue.Type != JTokenType.Null) { int configurationModeFrequencyMinsInstance = ((int)configurationModeFrequencyMinsValue); metaConfigurationInstance.ConfigurationModeFrequencyMins = configurationModeFrequencyMinsInstance; } JToken rebootNodeIfNeededValue = metaConfigurationValue["rebootNodeIfNeeded"]; if (rebootNodeIfNeededValue != null && rebootNodeIfNeededValue.Type != JTokenType.Null) { bool rebootNodeIfNeededInstance = ((bool)rebootNodeIfNeededValue); metaConfigurationInstance.RebootNodeIfNeeded = rebootNodeIfNeededInstance; } JToken configurationModeValue = metaConfigurationValue["configurationMode"]; if (configurationModeValue != null && configurationModeValue.Type != JTokenType.Null) { string configurationModeInstance = ((string)configurationModeValue); metaConfigurationInstance.ConfigurationMode = configurationModeInstance; } JToken actionAfterRebootValue = metaConfigurationValue["actionAfterReboot"]; if (actionAfterRebootValue != null && actionAfterRebootValue.Type != JTokenType.Null) { string actionAfterRebootInstance = ((string)actionAfterRebootValue); metaConfigurationInstance.ActionAfterReboot = actionAfterRebootInstance; } JToken certificateIdValue = metaConfigurationValue["certificateId"]; if (certificateIdValue != null && certificateIdValue.Type != JTokenType.Null) { string certificateIdInstance = ((string)certificateIdValue); metaConfigurationInstance.CertificateId = certificateIdInstance; } JToken refreshFrequencyMinsValue = metaConfigurationValue["refreshFrequencyMins"]; if (refreshFrequencyMinsValue != null && refreshFrequencyMinsValue.Type != JTokenType.Null) { int refreshFrequencyMinsInstance = ((int)refreshFrequencyMinsValue); metaConfigurationInstance.RefreshFrequencyMins = refreshFrequencyMinsInstance; } JToken allowModuleOverwriteValue = metaConfigurationValue["allowModuleOverwrite"]; if (allowModuleOverwriteValue != null && allowModuleOverwriteValue.Type != JTokenType.Null) { bool allowModuleOverwriteInstance = ((bool)allowModuleOverwriteValue); metaConfigurationInstance.AllowModuleOverwrite = allowModuleOverwriteInstance; } } JToken hostNameValue = valueValue["hostName"]; if (hostNameValue != null && hostNameValue.Type != JTokenType.Null) { string hostNameInstance = ((string)hostNameValue); dscNodeReportInstance.HostName = hostNameInstance; } JToken iPV4AddressesArray = valueValue["iPV4Addresses"]; if (iPV4AddressesArray != null && iPV4AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV4AddressesValue in ((JArray)iPV4AddressesArray)) { dscNodeReportInstance.IPV4Addresses.Add(((string)iPV4AddressesValue)); } } JToken iPV6AddressesArray = valueValue["iPV6Addresses"]; if (iPV6AddressesArray != null && iPV6AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV6AddressesValue in ((JArray)iPV6AddressesArray)) { dscNodeReportInstance.IPV6Addresses.Add(((string)iPV6AddressesValue)); } } JToken numberOfResourcesValue = valueValue["numberOfResources"]; if (numberOfResourcesValue != null && numberOfResourcesValue.Type != JTokenType.Null) { int numberOfResourcesInstance = ((int)numberOfResourcesValue); dscNodeReportInstance.NumberOfResources = numberOfResourcesInstance; } JToken rawErrorsValue = valueValue["rawErrors"]; if (rawErrorsValue != null && rawErrorsValue.Type != JTokenType.Null) { string rawErrorsInstance = ((string)rawErrorsValue); dscNodeReportInstance.RawErrors = rawErrorsInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the Dsc node report list by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> public async Task<DscNodeReportListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DscNodeReportListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeReportListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeReport dscNodeReportInstance = new DscNodeReport(); result.NodeReports.Add(dscNodeReportInstance); JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); dscNodeReportInstance.EndTime = endTimeInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); dscNodeReportInstance.StartTime = startTimeInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeReportInstance.Type = typeInstance; } JToken reportIdValue = valueValue["reportId"]; if (reportIdValue != null && reportIdValue.Type != JTokenType.Null) { Guid reportIdInstance = Guid.Parse(((string)reportIdValue)); dscNodeReportInstance.ReportId = reportIdInstance; } JToken statusValue = valueValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); dscNodeReportInstance.Status = statusInstance; } JToken refreshModeValue = valueValue["refreshMode"]; if (refreshModeValue != null && refreshModeValue.Type != JTokenType.Null) { string refreshModeInstance = ((string)refreshModeValue); dscNodeReportInstance.RefreshMode = refreshModeInstance; } JToken rebootRequestedValue = valueValue["rebootRequested"]; if (rebootRequestedValue != null && rebootRequestedValue.Type != JTokenType.Null) { string rebootRequestedInstance = ((string)rebootRequestedValue); dscNodeReportInstance.RebootRequested = rebootRequestedInstance; } JToken reportFormatVersionValue = valueValue["reportFormatVersion"]; if (reportFormatVersionValue != null && reportFormatVersionValue.Type != JTokenType.Null) { string reportFormatVersionInstance = ((string)reportFormatVersionValue); dscNodeReportInstance.ReportFormatVersion = reportFormatVersionInstance; } JToken configurationVersionValue = valueValue["configurationVersion"]; if (configurationVersionValue != null && configurationVersionValue.Type != JTokenType.Null) { string configurationVersionInstance = ((string)configurationVersionValue); dscNodeReportInstance.ConfigurationVersion = configurationVersionInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeReportInstance.Id = idInstance; } JToken errorsArray = valueValue["errors"]; if (errorsArray != null && errorsArray.Type != JTokenType.Null) { foreach (JToken errorsValue in ((JArray)errorsArray)) { DscReportError dscReportErrorInstance = new DscReportError(); dscNodeReportInstance.Errors.Add(dscReportErrorInstance); JToken errorSourceValue = errorsValue["errorSource"]; if (errorSourceValue != null && errorSourceValue.Type != JTokenType.Null) { string errorSourceInstance = ((string)errorSourceValue); dscReportErrorInstance.ErrorSource = errorSourceInstance; } JToken resourceIdValue = errorsValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); dscReportErrorInstance.ResourceId = resourceIdInstance; } JToken errorCodeValue = errorsValue["errorCode"]; if (errorCodeValue != null && errorCodeValue.Type != JTokenType.Null) { string errorCodeInstance = ((string)errorCodeValue); dscReportErrorInstance.ErrorCode = errorCodeInstance; } JToken errorMessageValue = errorsValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); dscReportErrorInstance.ErrorMessage = errorMessageInstance; } JToken localeValue = errorsValue["locale"]; if (localeValue != null && localeValue.Type != JTokenType.Null) { string localeInstance = ((string)localeValue); dscReportErrorInstance.Locale = localeInstance; } JToken errorDetailsValue = errorsValue["errorDetails"]; if (errorDetailsValue != null && errorDetailsValue.Type != JTokenType.Null) { string errorDetailsInstance = ((string)errorDetailsValue); dscReportErrorInstance.ErrorDetails = errorDetailsInstance; } } } JToken resourcesArray = valueValue["resources"]; if (resourcesArray != null && resourcesArray.Type != JTokenType.Null) { foreach (JToken resourcesValue in ((JArray)resourcesArray)) { DscReportResource dscReportResourceInstance = new DscReportResource(); dscNodeReportInstance.Resources.Add(dscReportResourceInstance); JToken resourceIdValue2 = resourcesValue["resourceId"]; if (resourceIdValue2 != null && resourceIdValue2.Type != JTokenType.Null) { string resourceIdInstance2 = ((string)resourceIdValue2); dscReportResourceInstance.ReportResourceId = resourceIdInstance2; } JToken sourceInfoValue = resourcesValue["sourceInfo"]; if (sourceInfoValue != null && sourceInfoValue.Type != JTokenType.Null) { string sourceInfoInstance = ((string)sourceInfoValue); dscReportResourceInstance.SourceInfo = sourceInfoInstance; } JToken dependsOnArray = resourcesValue["dependsOn"]; if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null) { foreach (JToken dependsOnValue in ((JArray)dependsOnArray)) { DscReportResourceNavigation dscReportResourceNavigationInstance = new DscReportResourceNavigation(); dscReportResourceInstance.DependsOn.Add(dscReportResourceNavigationInstance); JToken resourceIdValue3 = dependsOnValue["resourceId"]; if (resourceIdValue3 != null && resourceIdValue3.Type != JTokenType.Null) { string resourceIdInstance3 = ((string)resourceIdValue3); dscReportResourceNavigationInstance.ReportResourceId = resourceIdInstance3; } } } JToken moduleNameValue = resourcesValue["moduleName"]; if (moduleNameValue != null && moduleNameValue.Type != JTokenType.Null) { string moduleNameInstance = ((string)moduleNameValue); dscReportResourceInstance.ModuleName = moduleNameInstance; } JToken moduleVersionValue = resourcesValue["moduleVersion"]; if (moduleVersionValue != null && moduleVersionValue.Type != JTokenType.Null) { string moduleVersionInstance = ((string)moduleVersionValue); dscReportResourceInstance.ModuleVersion = moduleVersionInstance; } JToken resourceNameValue = resourcesValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); dscReportResourceInstance.ResourceName = resourceNameInstance; } JToken errorValue = resourcesValue["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { string errorInstance = ((string)errorValue); dscReportResourceInstance.Error = errorInstance; } JToken statusValue2 = resourcesValue["status"]; if (statusValue2 != null && statusValue2.Type != JTokenType.Null) { string statusInstance2 = ((string)statusValue2); dscReportResourceInstance.Status = statusInstance2; } JToken durationInSecondsValue = resourcesValue["durationInSeconds"]; if (durationInSecondsValue != null && durationInSecondsValue.Type != JTokenType.Null) { double durationInSecondsInstance = ((double)durationInSecondsValue); dscReportResourceInstance.DurationInSeconds = durationInSecondsInstance; } JToken startDateValue = resourcesValue["startDate"]; if (startDateValue != null && startDateValue.Type != JTokenType.Null) { DateTimeOffset startDateInstance = ((DateTimeOffset)startDateValue); dscReportResourceInstance.StartDate = startDateInstance; } } } JToken metaConfigurationValue = valueValue["metaConfiguration"]; if (metaConfigurationValue != null && metaConfigurationValue.Type != JTokenType.Null) { DscMetaConfiguration metaConfigurationInstance = new DscMetaConfiguration(); dscNodeReportInstance.MetaConfiguration = metaConfigurationInstance; JToken configurationModeFrequencyMinsValue = metaConfigurationValue["configurationModeFrequencyMins"]; if (configurationModeFrequencyMinsValue != null && configurationModeFrequencyMinsValue.Type != JTokenType.Null) { int configurationModeFrequencyMinsInstance = ((int)configurationModeFrequencyMinsValue); metaConfigurationInstance.ConfigurationModeFrequencyMins = configurationModeFrequencyMinsInstance; } JToken rebootNodeIfNeededValue = metaConfigurationValue["rebootNodeIfNeeded"]; if (rebootNodeIfNeededValue != null && rebootNodeIfNeededValue.Type != JTokenType.Null) { bool rebootNodeIfNeededInstance = ((bool)rebootNodeIfNeededValue); metaConfigurationInstance.RebootNodeIfNeeded = rebootNodeIfNeededInstance; } JToken configurationModeValue = metaConfigurationValue["configurationMode"]; if (configurationModeValue != null && configurationModeValue.Type != JTokenType.Null) { string configurationModeInstance = ((string)configurationModeValue); metaConfigurationInstance.ConfigurationMode = configurationModeInstance; } JToken actionAfterRebootValue = metaConfigurationValue["actionAfterReboot"]; if (actionAfterRebootValue != null && actionAfterRebootValue.Type != JTokenType.Null) { string actionAfterRebootInstance = ((string)actionAfterRebootValue); metaConfigurationInstance.ActionAfterReboot = actionAfterRebootInstance; } JToken certificateIdValue = metaConfigurationValue["certificateId"]; if (certificateIdValue != null && certificateIdValue.Type != JTokenType.Null) { string certificateIdInstance = ((string)certificateIdValue); metaConfigurationInstance.CertificateId = certificateIdInstance; } JToken refreshFrequencyMinsValue = metaConfigurationValue["refreshFrequencyMins"]; if (refreshFrequencyMinsValue != null && refreshFrequencyMinsValue.Type != JTokenType.Null) { int refreshFrequencyMinsInstance = ((int)refreshFrequencyMinsValue); metaConfigurationInstance.RefreshFrequencyMins = refreshFrequencyMinsInstance; } JToken allowModuleOverwriteValue = metaConfigurationValue["allowModuleOverwrite"]; if (allowModuleOverwriteValue != null && allowModuleOverwriteValue.Type != JTokenType.Null) { bool allowModuleOverwriteInstance = ((bool)allowModuleOverwriteValue); metaConfigurationInstance.AllowModuleOverwrite = allowModuleOverwriteInstance; } } JToken hostNameValue = valueValue["hostName"]; if (hostNameValue != null && hostNameValue.Type != JTokenType.Null) { string hostNameInstance = ((string)hostNameValue); dscNodeReportInstance.HostName = hostNameInstance; } JToken iPV4AddressesArray = valueValue["iPV4Addresses"]; if (iPV4AddressesArray != null && iPV4AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV4AddressesValue in ((JArray)iPV4AddressesArray)) { dscNodeReportInstance.IPV4Addresses.Add(((string)iPV4AddressesValue)); } } JToken iPV6AddressesArray = valueValue["iPV6Addresses"]; if (iPV6AddressesArray != null && iPV6AddressesArray.Type != JTokenType.Null) { foreach (JToken iPV6AddressesValue in ((JArray)iPV6AddressesArray)) { dscNodeReportInstance.IPV6Addresses.Add(((string)iPV6AddressesValue)); } } JToken numberOfResourcesValue = valueValue["numberOfResources"]; if (numberOfResourcesValue != null && numberOfResourcesValue.Type != JTokenType.Null) { int numberOfResourcesInstance = ((int)numberOfResourcesValue); dscNodeReportInstance.NumberOfResources = numberOfResourcesInstance; } JToken rawErrorsValue = valueValue["rawErrors"]; if (rawErrorsValue != null && rawErrorsValue.Type != JTokenType.Null) { string rawErrorsInstance = ((string)rawErrorsValue); dscNodeReportInstance.RawErrors = rawErrorsInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Author: Robert Scheller, Melissa Lucash using Landis.Utilities; using System; using System.Threading; using Landis.Core; using Landis.SpatialModeling; namespace Landis.Extension.Succession.NECN { // Chihiro; add grass layer to track dead wood in grass species public enum LayerName { Leaf, FineRoot, Wood, CoarseRoot, Metabolic, Structural, SOM1, SOM2, SOM3, Other }; public enum LayerType {Surface, Soil, Other} /// <summary> /// A Century soil model carbon and nitrogen pool. /// </summary> public class Layer { private LayerName name; private LayerType type; private double carbon; private double nitrogen; private double decayValue; private double fractionLignin; private double netMineralization; private double grossMineralization; //--------------------------------------------------------------------- public Layer(LayerName name, LayerType type) { this.name = name; this.type = type; this.carbon = 0.0; this.nitrogen = 0.0; // Initial decay value of Wood is set to mean decay rate of all tree species. // // // if this.name is LayerName.Wood: // double decayvalue = 0.0 // double N_of_species = len(sppnames) // // Compute mean wood decay rate // for sppname in tree-sppnames: // decayrate += decayrate(sppname) // this.decayVlaue = decayvalue / N_of_species // // elif this.name is LayerName.Grass: // double decayvalue = 0.0 // double N_of_species = len(sppnames) // // Compute mean wood decay rate // for sppname in grass-sppnames: // decayrate += decayrate(sppname) // this.decayVlaue = decayvalue / N_of_species // // else: // this.decayValue = 0.0 // if (this.name == LayerName.Wood) { // Compute mean decay value double decayvalue = 0.0; double n_of_tree_species = 0.0; foreach (ISpecies species in PlugIn.ModelCore.Species) { if (!SpeciesData.Grass[species]) decayvalue += FunctionalType.Table[SpeciesData.FuncType[species]].WoodDecayRate; n_of_tree_species += 1; } this.decayValue = decayvalue / n_of_tree_species; } else { this.decayValue = 0.0; } //this.decayValue = 0.0; this.fractionLignin = 0.0; this.netMineralization = 0.0; this.grossMineralization = 0.0; } //--------------------------------------------------------------------- /// <summary> /// Layer Name /// </summary> public LayerName Name { get { return name; } set { name = value; } } //--------------------------------------------------------------------- /// <summary> /// Provides an index to LitterTypeTable /// </summary> public LayerType Type { get { return type; } set { type = value; } } //--------------------------------------------------------------------- /// <summary> /// Carbon /// </summary> public double Carbon { get { return carbon; } set { carbon = Math.Max(0.0, value); } } //--------------------------------------------------------------------- /// <summary> /// Nitrogen /// </summary> public double Nitrogen { get { return nitrogen; } set { nitrogen = Math.Max(0.0, value); } } //--------------------------------------------------------------------- /// <summary> /// Pool decay rate. /// </summary> public double DecayValue { get { return decayValue; } set { decayValue = value; } } //--------------------------------------------------------------------- /// <summary> /// Pool Carbon:Nitrogen Ratio /// </summary> public double FractionLignin { get { return fractionLignin; } set { fractionLignin = value; } } //--------------------------------------------------------------------- /// <summary> /// Net Mineralization /// </summary> public double NetMineralization { get { return netMineralization; } set { netMineralization = value; } } //--------------------------------------------------------------------- /// <summary> /// Gross Mineralization /// </summary> public double GrossMineralization { get { return grossMineralization; } set { grossMineralization = value; } } // -------------------------------------------------- public Layer Clone() { Layer newLayer = new Layer(this.Name, this.Type); newLayer.carbon = this.carbon; newLayer.nitrogen = this.nitrogen ; newLayer.decayValue = this.decayValue ; newLayer.fractionLignin = this.fractionLignin ; newLayer.netMineralization = this.netMineralization ; newLayer.grossMineralization = this.grossMineralization ; return newLayer; } // -------------------------------------------------- public void DecomposeStructural(ActiveSite site) { if (this.Carbon > 0.0000001) { double anerb = SiteVars.AnaerobicEffect[site]; if (this.Type == LayerType.Surface) anerb = 1.0; // No anaerobic effect on surface material //Compute total C flow out of structural in layer double totalCFlow = //System.Math.Min(this.Carbon, OtherData.MaxStructuralC) this.Carbon * SiteVars.DecayFactor[site] //* OtherData.LitterParameters[(int)this.Type].DecayRateStrucC // v6: Replace the fixed value (0.39) with the user input value for surficial C decay * PlugIn.Parameters.DecayRateSurf * anerb * System.Math.Exp(-1.0 * OtherData.LigninDecayEffect * this.FractionLignin) * OtherData.MonthAdjust; //Decompose structural into som1 and som2 with CO2 loss. if (totalCFlow > this.Carbon) { string mesg = string.Format("Error: Decompose Structural totalCFlow > this.Carbon: totalCFlow={0}, DecayFactor={1}, Anerb={2}", totalCFlow, SiteVars.DecayFactor[site], anerb); throw new ApplicationException(mesg); } this.DecomposeLignin(totalCFlow, site); } } // -------------------------------------------------- // Only wood contains lignin public void DecomposeLignin(double totalCFlow, ActiveSite site) { double carbonToSOM1; //Net C flow to SOM1 double carbonToSOM2; //Net C flow to SOM2 double litterC = this.Carbon; double ratioCN = litterC / this.Nitrogen; //See if Layer can decompose to SOM1. //If it can decompose to SOM1, it will also go to SOM2. //If it can't decompose to SOM1, it can't decompose at all. //If Wood Object can decompose if (this.DecomposePossible(ratioCN, SiteVars.MineralN[site])) { // Decompose Wood Object to SOM2 // ----------------------- // Gross C flow to som2 carbonToSOM2 = totalCFlow * this.FractionLignin; //MicrobialRespiration associated with decomposition to som2 double SOM2co2loss = carbonToSOM2 * OtherData.LigninRespirationRate; if (this.Type == LayerType.Surface) this.Respiration(SOM2co2loss, site, true); else this.Respiration(SOM2co2loss, site, false); //Net C flow to SOM2 double netCFlow = carbonToSOM2 - SOM2co2loss; // Partition and schedule C flows this.TransferCarbon(SiteVars.SOM2[site], netCFlow); this.TransferNitrogen(SiteVars.SOM2[site], netCFlow, litterC, ratioCN, site); // ---------------------------------------------- // Decompose Wood Object to SOM1 // Gross C flow to som1 carbonToSOM1 = totalCFlow - netCFlow; double SOM1co2loss; //MicrobialRespiration associated with decomposition to som1 if (this.Type == LayerType.Surface) { SOM1co2loss = carbonToSOM1 * OtherData.StructuralToCO2Surface; this.Respiration(SOM1co2loss, site, true); } else { SOM1co2loss = carbonToSOM1 * OtherData.StructuralToCO2Soil; this.Respiration(SOM1co2loss, site, false); } //Net C flow to SOM1 carbonToSOM1 -= SOM1co2loss; if(this.Type == LayerType.Surface) { if (carbonToSOM1 > this.Carbon) { string mesg = string.Format("Error: Carbon transfer SOM1surface->SOM1 exceeds C flow. Source={0}, C-transfer={1}, C={2}", this.Name, carbonToSOM1, this.Carbon); throw new ApplicationException(mesg); } this.TransferCarbon(SiteVars.SOM1surface[site], carbonToSOM1); this.TransferNitrogen(SiteVars.SOM1surface[site], carbonToSOM1, litterC, ratioCN, site); } else { if (carbonToSOM1 > this.Carbon) { string mesg = string.Format("Error: Carbon transfer SOM1soil->SOM1 exceeds C flow. Source={0}, C-transfer={1}, C={2}", this.Name, carbonToSOM1, this.Carbon); throw new ApplicationException(mesg); } this.TransferCarbon(SiteVars.SOM1soil[site], carbonToSOM1); this.TransferNitrogen(SiteVars.SOM1soil[site], carbonToSOM1, litterC, ratioCN, site); } } //PlugIn.ModelCore.UI.WriteLine("Decompose2. MineralN={0:0.00}.", SiteVars.MineralN[site]); return; } //--------------------------------------------------------------------- public void DecomposeMetabolic(ActiveSite site) { double litterC = this.Carbon; double anerb = SiteVars.AnaerobicEffect[site]; if (litterC > 0.0000001) { // Determine C/N ratios for flows to SOM1 double ratioCNtoSOM1 = 0.0; double co2loss = 0.0; // Compute ratios for surface metabolic residue if (this.Type == LayerType.Surface) ratioCNtoSOM1 = Layer.AbovegroundDecompositionRatio(this.Nitrogen, litterC); //Compute ratios for soil metabolic residue else ratioCNtoSOM1 = Layer.BelowgroundDecompositionRatio(site, OtherData.MinCNenterSOM1, OtherData.MaxCNenterSOM1, OtherData.MinContentN_SOM1); //Compute total C flow out of metabolic layer double totalCFlow = litterC * SiteVars.DecayFactor[site] * OtherData.LitterParameters[(int) this.Type].DecayRateMetabolicC * OtherData.MonthAdjust; //PlugIn.ModelCore.UI.WriteLine("DecomposeMeta1. MineralN={0:0.00}.", SiteVars.MineralN[site]); //Added impact of soil anerobic conditions if (this.Type == LayerType.Soil) totalCFlow *= anerb; //Make sure metabolic C does not go negative. if (totalCFlow > litterC) totalCFlow = litterC; //If decomposition can occur, if(this.DecomposePossible(ratioCNtoSOM1, SiteVars.MineralN[site])) { //CO2 loss if (this.Type == LayerType.Surface) { co2loss = totalCFlow * OtherData.MetabolicToCO2Surface; //this.Respiration(co2loss, site, true); } else { co2loss = totalCFlow * OtherData.MetabolicToCO2Soil; //this.Respiration(co2loss, site, false); } this.Respiration(co2loss, site, false); //SURFACE DECAY ALSO COUNTED AS SOIL RESPIRATION (Shih-Chieh Chang) //PlugIn.ModelCore.UI.WriteLine("BeforeResp. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine("AfterResp. MineralN={0:0.00}.", SiteVars.MineralN[site]); //Decompose metabolic into som1 double netCFlow = totalCFlow - co2loss; if (netCFlow > litterC) PlugIn.ModelCore.UI.WriteLine(" ERROR: Decompose Metabolic: netCFlow={0:0.000} > layer.Carbon={0:0.000}.", netCFlow, this.Carbon); // -- CARBON AND NITROGEN --------------------------- // Partition and schedule C flows // Compute and schedule N flows and update mineralization accumulators. if((int) this.Type == (int) LayerType.Surface) { this.TransferCarbon(SiteVars.SOM1surface[site], netCFlow); this.TransferNitrogen(SiteVars.SOM1surface[site], netCFlow, litterC, ratioCNtoSOM1, site); //PlugIn.ModelCore.UI.WriteLine("DecomposeMetabolic. MineralN={0:0.00}.", SiteVars.MineralN[site]); } else { this.TransferCarbon(SiteVars.SOM1soil[site], netCFlow); this.TransferNitrogen(SiteVars.SOM1soil[site], netCFlow, litterC, ratioCNtoSOM1, site); } } } //} } //--------------------------------------------------------------------- public void TransferCarbon(Layer destination, double netCFlow) { if (netCFlow < 0) { //PlugIn.ModelCore.UI.WriteLine("NEGATIVE C FLOW! Source: {0},{1}; Destination: {2},{3}.", this.Name, this.Type, destination.Name, destination.Type); } if (netCFlow > this.Carbon) netCFlow = this.Carbon; //round these to avoid unexpected behavior this.Carbon = this.Carbon - netCFlow; // Math.Round((this.Carbon - netCFlow),2); destination.Carbon = destination.Carbon + netCFlow; // Math.Round((destination.Carbon + netCFlow),2); } public void TransferNitrogen(Layer destination, double CFlow, double totalC, double ratioCNtoDestination, ActiveSite site) { // this is the source. double mineralNFlow = 0.0; //...N flow is proportional to C flow. double NFlow = this.Nitrogen * CFlow / totalC; //...This was added to avoid a 0/0 error on the pc. if (CFlow <= 0.0 || NFlow <= 0.0) { return; } if ((NFlow - this.Nitrogen) > 0.01) { //PlugIn.ModelCore.UI.WriteLine(" Transfer N: N flow > source N."); //PlugIn.ModelCore.UI.WriteLine(" NFlow={0:0.000}, SourceN={1:0.000}", NFlow, this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" dest.Name ={0}, dest.Type ={1}", destination.Name, destination.Type); //PlugIn.ModelCore.UI.WriteLine(" ratio CN to dest={0}", ratioCNtoDestination); } //...If C/N of Box A > C/N of new material entering Box B if ((CFlow / NFlow) > ratioCNtoDestination) { //...IMMOBILIZATION occurs. //...Compute the amount of N immobilized. // since ratioCNtoDestination = netCFlow / (Nflow + immobileN), // where immobileN is the extra N needed from the mineral pool double immobileN = (CFlow / ratioCNtoDestination) - NFlow; //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); // PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" NFlow={0:0.000}, SourceN={1:0.000},CNdestination={2:0}", NFlow, this.Nitrogen,ratioCNtoDestination); //PlugIn.ModelCore.UI.WriteLine("CalculatingImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); //...Schedule flow from Box A to Box B (outofa) //flow(anps,bnps,time,outofa); this.Nitrogen -= NFlow; destination.Nitrogen += NFlow; //PlugIn.ModelCore.UI.WriteLine("NFlow. MineralN={0:0.00}, ImmobileN={1:0.000}.", SiteVars.MineralN[site],immobileN); // Schedule flow from mineral pool to Box B (immobileN) // flow(labile,bnps,time,immflo); //Don't allow mineral N to go to zero or negative.- ML if (immobileN > SiteVars.MineralN[site]) immobileN = SiteVars.MineralN[site] - 0.01; //leave some small amount of mineral N SiteVars.MineralN[site] -= immobileN; //PlugIn.ModelCore.UI.WriteLine("AfterImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); destination.Nitrogen += immobileN; //PlugIn.ModelCore.UI.WriteLine("AdjustImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine(" TransferN immobileN={0:0.000}, C={1:0.000}, N={2:0.000}, ratioCN={3:0.000}.", immobileN, CFlow, NFlow, ratioCNtoDestination); //PlugIn.ModelCore.UI.WriteLine(" source={0}-{1}, destination={2}-{3}.", this.Name, this.Type, destination.Name, destination.Type); //...Return mineralization value. mineralNFlow = -1 * immobileN; //PlugIn.ModelCore.UI.WriteLine("MineralNflow. MineralN={0:0.00}.", SiteVars.MineralN[site]); } else //...MINERALIZATION occurs //...Schedule flow from Box A to Box B { //PlugIn.ModelCore.UI.WriteLine(" Transfer Nitrogen Min."); double mineralizedN = (CFlow / ratioCNtoDestination); this.Nitrogen -= mineralizedN; destination.Nitrogen += mineralizedN; //...Schedule flow from Box A to mineral pool mineralNFlow = NFlow - mineralizedN; if ((mineralNFlow - this.Nitrogen) > 0.01) { //PlugIn.ModelCore.UI.WriteLine(" Transfer N mineralization: mineralN > source N."); //PlugIn.ModelCore.UI.WriteLine(" MineralNFlow={0:0.000}, SourceN={1:0.000}", mineralNFlow, this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); // PlugIn.ModelCore.UI.WriteLine(" dest.Name ={0}, dest.Type ={1}", destination.Name, destination.Type); //PlugIn.ModelCore.UI.WriteLine(" ratio CN to dest={0}", ratioCNtoDestination); } this.Nitrogen -= mineralNFlow; SiteVars.MineralN[site] += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine("IfMinOccurs. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine(" TransferN NFlow={0:0.000}, mineralizedN = {1:0.000}, N mineralalization = {1:0.000}", NFlow, mineralizedN, mineralNFlow); //PlugIn.ModelCore.UI.WriteLine(" Source: this.Name={0}, this.Type={1}", this.Name, this.Type); } if (mineralNFlow > 0) SiteVars.GrossMineralization[site] += mineralNFlow; //...Net mineralization this.NetMineralization += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" this.Nitrogen={0:0.000}.", this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine("AfterMinOccurs. MineralN={0:0.00}.", SiteVars.MineralN[site]); return; } public void Respiration(double co2loss, ActiveSite site, bool surface) { // Compute flows associated with microbial respiration. // Input: // co2loss = CO2 loss associated with decomposition // Box A. For components with only 1 layer, tcstva will be dimensioned (1). // Transput: //c carbonSourceSink = C source/sink //c grossMineralization = gross mineralization //c netMineralization = net mineralization for layer N //c...Mineralization associated with respiration is proportional to the N fraction. double mineralNFlow = co2loss * this.Nitrogen / this.Carbon; if(mineralNFlow > this.Nitrogen) { //if((mineralNFlow - this.Nitrogen) > 0.01) //{ // PlugIn.ModelCore.UI.WriteLine("RESPIRATION for layer {0} {1}: Mineral N flow exceeds layer Nitrogen.", this.Name, this.Type); // PlugIn.ModelCore.UI.WriteLine(" MineralNFlow={0:0.000}, this.Nitrogen ={0:0.000}", mineralNFlow, this.Nitrogen); // PlugIn.ModelCore.UI.WriteLine(" CO2 loss={0:0.000}, this.Carbon={0:0.000}", co2loss, this.Carbon); // PlugIn.ModelCore.UI.WriteLine(" Site R/C: {0}/{1}.", site.Location.Row, site.Location.Column); //} mineralNFlow = this.Nitrogen; co2loss = this.Carbon; } this.TransferCarbon(SiteVars.SourceSink[site], co2loss); //Add lost CO2 to monthly heterotrophic respiration SiteVars.MonthlyHeteroResp[site][Main.Month] += co2loss; if(!surface) SiteVars.MonthlySoilResp[site][Main.Month] += co2loss; this.Nitrogen -= mineralNFlow; SiteVars.MineralN[site] += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" Source: this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" Respiration.mineralN= {0:0.000}, co2loss={1:00}", mineralNFlow, co2loss); //c...Update gross mineralization // this.GrossMineralization += mineralNFlow; if (mineralNFlow > 0) SiteVars.GrossMineralization[site] += mineralNFlow; //c...Update net mineralization this.NetMineralization += mineralNFlow; return; } public bool DecomposePossible(double ratioCNnew, double mineralN) { //c...Determine if decomposition can occur. bool canDecompose = true; //c...If there is no available mineral N if (mineralN < 0.0000001) { // Compare the C/N of new material to the C/N of the layer if C/N of // the layer > C/N of new material if (this.Carbon / this.Nitrogen > ratioCNnew) { // Immobilization is necessary and the stuff in Box A can't // decompose to Box B. canDecompose = false; } } // If there is some available mineral N, decomposition can // proceed even if mineral N is driven negative in // the next time step. return canDecompose; } public void AdjustLignin(double inputC, double inputFracLignin) { //c...Adjust the fraction of lignin in structural C when new material //c... is added. //c oldc = grams C in structural before new material is added //c frnew = fraction of lignin in new structural material //c addc = grams structural C being added //c fractl comes in as fraction of lignin in structural before new //c material is added; goes out as fraction of lignin in //c structural with old and new combined. //c...oldlig = grams of lignin in existing residue double oldlig = this.FractionLignin * this.Carbon;//totalC; //c...newlig = grams of lignin in new residue double newlig = inputFracLignin * inputC; //c...Compute lignin fraction in combined residue double newFraction = (oldlig + newlig) / (this.Carbon + inputC); this.FractionLignin = newFraction; return; } public void AdjustDecayRate(double inputC, double inputDecayRate) { //c...oldlig = grams of lignin in existing residue double oldDecayRate = this.DecayValue * this.Carbon; //c...newlig = grams of lignin in new residue double newDecayRate = inputDecayRate * inputC; //c...Compute decay rate in combined residue this.DecayValue = (oldDecayRate + newDecayRate) / (inputC + this.Carbon); return; } public static double BelowgroundDecompositionRatio(ActiveSite site, double minCNenter, double maxCNenter, double minContentN) { //BelowGround Decomposition RATio computation. double bgdrat = 0.0; //Determine ratio of C/N of new material entering 'Box B'. //Ratio depends on available N double mineralN = SiteVars.MineralN[site]; if (mineralN <= 0.0) bgdrat = maxCNenter; // Set ratio to maximum allowed (HIGHEST carbon, LOWEST nitrogen) else if (mineralN > minContentN) bgdrat = minCNenter; //Set ratio to minimum allowed else bgdrat = (1.0 - (mineralN / minContentN)) * (maxCNenter - minCNenter) + minCNenter; return bgdrat; } public static double AbovegroundDecompositionRatio(double abovegroundN, double abovegroundC) { double Ncontent, agdrat; double biomassConversion = 2.0; // CNmicrobialB = slope of the regression line for C/N of som1 double CNmicrobial_b = (OtherData.MinCNSurfMicrobes - OtherData.MaxCNSurfMicrobes) / OtherData.MinNContentCNSurfMicrobes; // The ratios for metabolic and som1 may vary and must be recomputed each time step if ((abovegroundC * biomassConversion) <= 0.00000000001) Ncontent = 0.0; else Ncontent = abovegroundN / (abovegroundC * biomassConversion); //tca is multiplied by biomassConversion to give biomass if (Ncontent > OtherData.MinNContentCNSurfMicrobes) agdrat = OtherData.MinCNSurfMicrobes; else agdrat = OtherData.MaxCNSurfMicrobes + Ncontent * CNmicrobial_b; return agdrat; } //--------------------------------------------------------------------- /// <summary> /// Reduces the pool's biomass by a specified percentage. /// </summary> public void ReduceMass(double percentageLost) { if (percentageLost < 0.0 || percentageLost > 1.0) throw new ArgumentException("Percentage must be between 0% and 100%"); this.Carbon = this.Carbon * (1.0 - percentageLost); this.Nitrogen = this.Nitrogen * (1.0 - percentageLost); return; } } }
// 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.IO; using Xunit; namespace System.CodeDom.Compiler.Tests { public class CodeCompilerTests { public static IEnumerable<object[]> CodeCompileUnit_TestData() { yield return new object[] { null }; yield return new object[] { new CodeCompileUnit() }; var unit = new CodeCompileUnit(); unit.ReferencedAssemblies.Add("assembly1"); unit.ReferencedAssemblies.Add("assembly2"); yield return new object[] { unit }; var referencedUnit = new CodeCompileUnit(); referencedUnit.ReferencedAssemblies.Add("referenced"); referencedUnit.ReferencedAssemblies.Add("assembly1"); yield return new object[] { referencedUnit }; } [Theory] [MemberData(nameof(CodeCompileUnit_TestData))] public void CompileAssemblyFromDom_ValidCodeCompileUnit_ReturnsExpected(CodeCompileUnit compilationUnit) { ICodeCompiler compiler = new StubCompiler(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("referenced"); Assert.Null(compiler.CompileAssemblyFromDom(options, compilationUnit)); } [Theory] [MemberData(nameof(CodeCompileUnit_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromDom_ValidCodeCompileUnit_ThrowsPlatformNotSupportedException(CodeCompileUnit compilationUnit) { ICodeCompiler compiler = new Compiler(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("referenced"); Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromDom(options, compilationUnit)); } [Fact] public void CompileAssemblyFromDom_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromDom(null, new CodeCompileUnit())); } [Theory] [MemberData(nameof(CodeCompileUnit_TestData))] public void FromDom_ValidCodeCompileUnit_ReturnsExpected(CodeCompileUnit compilationUnit) { var compiler = new StubCompiler(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("referenced"); Assert.Null(compiler.FromDomEntryPoint(options, compilationUnit)); } [Theory] [MemberData(nameof(CodeCompileUnit_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromDom_ValidCodeCompileUnit_ThrowsPlatformNotSupportedException(CodeCompileUnit compilationUnit) { var compiler = new Compiler(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("referenced"); Assert.Throws<PlatformNotSupportedException>(() => compiler.FromDomEntryPoint(options, compilationUnit)); } [Fact] public void FromDom_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromDomEntryPoint(null, new CodeCompileUnit())); } public static IEnumerable<object[]> CodeCompileUnits_TestData() { yield return new object[] { new CodeCompileUnit[0] }; yield return new object[] { new CodeCompileUnit[] { null } }; var unit = new CodeCompileUnit(); unit.ReferencedAssemblies.Add("assembly1"); unit.ReferencedAssemblies.Add("assembly2"); yield return new object[] { new CodeCompileUnit[] { new CodeCompileUnit(), unit } }; } [Theory] [MemberData(nameof(CodeCompileUnits_TestData))] public void CompileAssemblyFromDomBatch_ValidCodeCompileUnits_ReturnsExpected(CodeCompileUnit[] compilationUnits) { ICodeCompiler compiler = new StubCompiler(); Assert.Null(compiler.CompileAssemblyFromDomBatch(new CompilerParameters(), compilationUnits)); } [Theory] [MemberData(nameof(CodeCompileUnits_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromDomBatch_ValidCodeCompileUnits_ThrowsPlatformNotSupportedException(CodeCompileUnit[] compilationUnits) { ICodeCompiler compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromDomBatch(new CompilerParameters(), compilationUnits)); } [Fact] public void CompileAssemblyFromDomBatch_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromDomBatch(null, new CodeCompileUnit[0])); } [Fact] public void CompileAssemblyFromDomBatch_NullCompileUnits_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("ea", () => compiler.CompileAssemblyFromDomBatch(new CompilerParameters(), null)); } [Theory] [MemberData(nameof(CodeCompileUnits_TestData))] public void FromDomBatch_ValidCodeCompileUnits_ReturnsExpected(CodeCompileUnit[] compilationUnits) { var compiler = new StubCompiler(); Assert.Null(compiler.FromDomBatchEntryPoint(new CompilerParameters(), compilationUnits)); } [Theory] [MemberData(nameof(CodeCompileUnits_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromDomBatch_ValidCodeCompileUnits_ThrowsPlatformNotSupportedException(CodeCompileUnit[] compilationUnits) { var compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.FromDomBatchEntryPoint(new CompilerParameters(), compilationUnits)); } [Fact] public void FromDomBatch_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromDomBatchEntryPoint(null, new CodeCompileUnit[0])); } [Fact] public void FromDomBatch_NullCompileUnits_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("ea", () => compiler.FromDomBatchEntryPoint(new CompilerParameters(), null)); } [Fact] public void CompileAssemblyFromFile_FileExists_ReturnsExpected() { ICodeCompiler compiler = new StubCompiler(); using (var file = new TempFile(Path.GetTempFileName(), 0)) { Assert.Null(compiler.CompileAssemblyFromFile(new CompilerParameters(), file.Path)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromFile_FileExists_ThrowsPlatformNotSupportedException() { ICodeCompiler compiler = new Compiler(); using (var file = new TempFile(Path.GetTempFileName(), 0)) { Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromFile(new CompilerParameters(), file.Path)); } } [Fact] public void CompileAssemblyFromFile_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromFile(null, "fileName")); } [Fact] public void CompileAssemblyFromFile_NullFileName_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("fileName", () => compiler.CompileAssemblyFromFile(new CompilerParameters(), null)); } [Fact] public void CompileAssemblyFromFile_EmptyFileName_ThrowsArgumentException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentException>("path", null, () => compiler.CompileAssemblyFromFile(new CompilerParameters(), "")); } [Fact] public void CompileAssemblyFromFile_NoSuchFile_ThrowsFileNotFoundException() { ICodeCompiler compiler = new Compiler(); Assert.Throws<FileNotFoundException>(() => compiler.CompileAssemblyFromFile(new CompilerParameters(), "noSuchFile")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromFile_FileExists_ThrowsPlatformNotSupportedException() { var compiler = new Compiler(); using (var file = new TempFile(Path.GetTempFileName(), 0)) { Assert.Throws<PlatformNotSupportedException>(() => compiler.FromFileEntryPoint(new CompilerParameters(), file.Path)); } } [Fact] public void FromFile_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromFileEntryPoint(null, "fileName")); } [Fact] public void FromFile_NullFileName_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("fileName", () => compiler.FromFileEntryPoint(new CompilerParameters(), null)); } [Fact] public void FromFile_EmptyFileName_ThrowsArgumentException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentException>("path", null, () => compiler.FromFileEntryPoint(new CompilerParameters(), "")); } [Fact] public void FromFile_NoSuchFile_ThrowsFileNotFoundException() { var compiler = new Compiler(); Assert.Throws<FileNotFoundException>(() => compiler.FromFileEntryPoint(new CompilerParameters(), "noSuchFile")); } [Fact] public void CompileAssemblyFromFileBatch_ValidFileNames_ReturnsExpected() { using (var file = new TempFile(Path.GetTempFileName(), 0)) { ICodeCompiler compiler = new StubCompiler(); Assert.Null(compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), new string[] { file.Path })); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromFileBatch_ValidFileNames_ThrowsPlatformNotSupportedException() { using (var file = new TempFile(Path.GetTempFileName(), 0)) { ICodeCompiler compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), new string[] { file.Path })); } } [Fact] public void CompileAssemblyFromFileBatch_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromFileBatch(null, new string[0])); } [Fact] public void CompileAssemblyFromFileBatch_NullFileNames_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("fileNames", () => compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), null)); } [Fact] public void CompileAssemblyFromFileBatch_NullFileNameInFileNames_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("path", () => compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), new string[] { null })); } [Fact] public void CompileAssemblyFromFileBatch_EmptyFileNameInFileNames_ThrowsArgumentException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentException>("path", null, () => compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), new string[] { "" })); } [Fact] public void CompileAssemblyFromFileBatch_NoSuchFileInFileNames_ThrowsFileNotFoundException() { ICodeCompiler compiler = new Compiler(); Assert.Throws<FileNotFoundException>(() => compiler.CompileAssemblyFromFileBatch(new CompilerParameters(), new string[] { "noSuchFile" })); } public static IEnumerable<object[]> FromFileBatch_TestData() { yield return new object[] { new string[0] }; yield return new object[] { new string[] { null } }; yield return new object[] { new string[] { "" } }; yield return new object[] { new string[] { "noSuchFile" } }; } [Theory] [MemberData(nameof(FromFileBatch_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromFileBatch_ValidFileNames_ThrowsPlatformNotSupportedException(string[] fileNames) { var compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.FromFileBatchEntryPoint(new CompilerParameters(), fileNames)); } [Fact] public void FromFileBatch_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromFileBatchEntryPoint(null, new string[0])); } [Fact] public void FromFileBatch_NullFileNames_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("fileNames", () => compiler.FromFileBatchEntryPoint(new CompilerParameters(), null)); } public static IEnumerable<object[]> Source_TestData() { yield return new object[] { null }; yield return new object[] { "" }; yield return new object[] { "source" }; } [Theory] [MemberData(nameof(Source_TestData))] public void CompileAssemblyFromSource_ValidSource_ReturnsExpected(string source) { ICodeCompiler compiler = new StubCompiler(); Assert.Null(compiler.CompileAssemblyFromSource(new CompilerParameters(), source)); } [Theory] [MemberData(nameof(Source_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromSource_ValidSource_ThrowsPlatformNotSupportedException(string source) { ICodeCompiler compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromSource(new CompilerParameters(), source)); } [Fact] public void CompileAssemblyFromSource_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromSource(null, "source")); } [Theory] [MemberData(nameof(Source_TestData))] public void FromSource_ValidSource_ReturnsExpected(string source) { var compiler = new StubCompiler(); Assert.Null(compiler.FromSourceEntryPoint(new CompilerParameters(), source)); } [Theory] [MemberData(nameof(Source_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromSource_ValidSource_ThrowsPlatformNotSupportedException(string source) { var compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.FromSourceEntryPoint(new CompilerParameters(), source)); } [Fact] public void FromSource_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromSourceEntryPoint(null, "source")); } public static IEnumerable<object[]> Sources_TestData() { yield return new object[] { new string[0] }; yield return new object[] { new string[] { null } }; yield return new object[] { new string[] { "" } }; yield return new object[] { new string[] { "source1", "source2" } }; } [Theory] [MemberData(nameof(Sources_TestData))] public void CompileAssemblyFromSourceBatch_ValidSources_ReturnsExpected(string[] sources) { ICodeCompiler compiler = new StubCompiler(); Assert.Null(compiler.CompileAssemblyFromSourceBatch(new CompilerParameters(), sources)); } [Theory] [MemberData(nameof(Sources_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void CompileAssemblyFromSourceBatch_ValidSources_ThrowsPlatformNotSupportedException(string[] sources) { ICodeCompiler compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.CompileAssemblyFromSourceBatch(new CompilerParameters(), sources)); } [Fact] public void CompileAssemblyFromSourceBatch_NullOptions_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.CompileAssemblyFromSourceBatch(null, new string[] { "source" })); } [Fact] public void CompileAssemblyFromSourceBatch_NullSources_ThrowsArgumentNullException() { ICodeCompiler compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("sources", () => compiler.CompileAssemblyFromSourceBatch(new CompilerParameters(), null)); } [Theory] [MemberData(nameof(Sources_TestData))] public void FromSourceBatch_ValidSources_ReturnsExpected(string[] sources) { var compiler = new StubCompiler(); Assert.Null(compiler.FromSourceBatchEntryPoint(new CompilerParameters(), sources)); } [Theory] [MemberData(nameof(Sources_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void FromSourceBatch_ValidSources_ThrowsPlatformNotSupportedException(string[] sources) { var compiler = new Compiler(); Assert.Throws<PlatformNotSupportedException>(() => compiler.FromSourceBatchEntryPoint(new CompilerParameters(), sources)); } [Fact] public void FromSourceBatch_NullOptions_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("options", () => compiler.FromSourceBatchEntryPoint(null, new string[] { "source" })); } [Fact] public void FromSourceBatch_NullSources_ThrowsArgumentNullException() { var compiler = new Compiler(); AssertExtensions.Throws<ArgumentNullException>("sources", () => compiler.FromSourceBatchEntryPoint(new CompilerParameters(), null)); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("cmdArgs")] public void GetResponseFileCmdArgs_ValidCmdArgs_ReturnsExpected(string cmdArgs) { var compiler = new Compiler(); string args = compiler.GetResponseFileCmdArgsEntryPoint(new CompilerParameters(), cmdArgs); Assert.StartsWith("@\"", args); Assert.EndsWith("\"", args); } [Fact] public void GetResponseFileCmdArgs_NullOptions_ThrowsNullReferenceException() { var compiler = new Compiler(); Assert.Throws<NullReferenceException>(() => compiler.GetResponseFileCmdArgsEntryPoint(null, "cmdArgs")); } public static IEnumerable<object[]> JoinStringArray_TestData() { yield return new object[] { null, ", ", "" }; yield return new object[] { new string[0], ", ", "" }; yield return new object[] { new string[] { "a" }, ", ", "\"a\"" }; yield return new object[] { new string[] { "a", "b" }, ", ", "\"a\", \"b\"" }; yield return new object[] { new string[] { "a", "b" }, null, "\"a\"\"b\"" }; yield return new object[] { new string[] { "a", "b" }, "", "\"a\"\"b\"" }; } [Theory] [MemberData(nameof(JoinStringArray_TestData))] public void JoinStringArray_Invoke_ReturnsExpected(string[] sa, string separator, string expected) { var compiler = new Compiler(); Assert.Equal(expected, compiler.JoinStringArrayEntryPoint(sa, separator)); } public class Compiler : CodeCompiler { public CompilerResults FromDomEntryPoint(CompilerParameters options, CodeCompileUnit e) => FromDom(options, e); public CompilerResults FromDomBatchEntryPoint(CompilerParameters options, CodeCompileUnit[] ea) => FromDomBatch(options, ea); public CompilerResults FromFileEntryPoint(CompilerParameters options, string fileName) => FromFile(options, fileName); public CompilerResults FromFileBatchEntryPoint(CompilerParameters options, string[] fileNames) => FromFileBatch(options, fileNames); public CompilerResults FromSourceEntryPoint(CompilerParameters options, string source) => FromSource(options, source); public CompilerResults FromSourceBatchEntryPoint(CompilerParameters options, string[] sources) => FromSourceBatch(options, sources); public string GetResponseFileCmdArgsEntryPoint(CompilerParameters options, string cmdArgs) => GetResponseFileCmdArgs(options, cmdArgs); public string JoinStringArrayEntryPoint(string[] sa, string separator) => JoinStringArray(sa, separator); protected override string CompilerName => throw new NotImplementedException(); protected override string FileExtension => ".cs"; protected override string NullToken => throw new NotImplementedException(); protected override string CmdArgsFromParameters(CompilerParameters options) { throw new NotImplementedException(); } protected override string CreateEscapedIdentifier(string value) { throw new NotImplementedException(); } protected override string CreateValidIdentifier(string value) { throw new NotImplementedException(); } protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e) { } protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e) { } protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e) { } protected override void GenerateAssignStatement(CodeAssignStatement e) { } protected override void GenerateAttachEventStatement(CodeAttachEventStatement e) { } protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes) { } protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes) { } protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e) { } protected override void GenerateCastExpression(CodeCastExpression e) { } protected override void GenerateComment(CodeComment e) { } protected override void GenerateConditionStatement(CodeConditionStatement e) { } protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c) { } protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e) { } protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e) { } protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c) { } protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) { } protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { } protected override void GenerateExpressionStatement(CodeExpressionStatement e) { } protected override void GenerateField(CodeMemberField e) { } protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) { } protected override void GenerateGotoStatement(CodeGotoStatement e) { } protected override void GenerateIndexerExpression(CodeIndexerExpression e) { } protected override void GenerateIterationStatement(CodeIterationStatement e) { } protected override void GenerateLabeledStatement(CodeLabeledStatement e) { } protected override void GenerateLinePragmaEnd(CodeLinePragma e) { } protected override void GenerateLinePragmaStart(CodeLinePragma e) { } protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c) { } protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e) { } protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) { } protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e) { } protected override void GenerateNamespaceEnd(CodeNamespace e) { } protected override void GenerateNamespaceImport(CodeNamespaceImport e) { } protected override void GenerateNamespaceStart(CodeNamespace e) { } protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e) { } protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c) { } protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e) { } protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) { } protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e) { } protected override void GenerateSnippetExpression(CodeSnippetExpression e) { } protected override void GenerateSnippetMember(CodeSnippetTypeMember e) { } protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e) { } protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e) { } protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) { } protected override void GenerateTypeConstructor(CodeTypeConstructor e) { } protected override void GenerateTypeEnd(CodeTypeDeclaration e) { } protected override void GenerateTypeStart(CodeTypeDeclaration e) { } protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e) { } protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e) { } protected override string GetTypeOutput(CodeTypeReference value) { throw new NotImplementedException(); } protected override bool IsValidIdentifier(string value) { throw new NotImplementedException(); } protected override void OutputType(CodeTypeReference typeRef) { throw new NotImplementedException(); } protected override void ProcessCompilerOutputLine(CompilerResults results, string line) { throw new NotImplementedException(); } protected override string QuoteSnippetString(string value) { throw new NotImplementedException(); } protected override bool Supports(GeneratorSupport support) { throw new NotImplementedException(); } } public class StubCompiler : Compiler { protected override CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { return null; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using StructureMap.Building; using StructureMap.Diagnostics; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.TypeRules; namespace StructureMap { public class BuildSession : IBuildSession, IContext { public static readonly string DEFAULT = "Default"; private readonly IPipelineGraph _pipelineGraph; private readonly ISessionCache _sessionCache; private readonly Stack<Instance> _instances = new Stack<Instance>(); public BuildSession(IPipelineGraph pipelineGraph, string requestedName = null, ExplicitArguments args = null) { _pipelineGraph = pipelineGraph; _sessionCache = new SessionCache(this, args); RequestedName = requestedName ?? DEFAULT; } protected IPipelineGraph pipelineGraph { get { return _pipelineGraph; } } public string RequestedName { get; set; } public void BuildUp(object target) { if (target == null) throw new ArgumentNullException("target"); var pluggedType = target.GetType(); var plan = _pipelineGraph.Policies.ToBuildUpPlan(pluggedType, () => { return _pipelineGraph.Instances.GetDefault(pluggedType) as IConfiguredInstance ?? new ConfiguredInstance(pluggedType); }); plan.BuildUp(this, this, target); } public T GetInstance<T>() { return (T) GetInstance(typeof (T)); } public object GetInstance(Type pluginType) { return _sessionCache.GetDefault(pluginType, _pipelineGraph); } public T GetInstance<T>(string name) { return (T) CreateInstance(typeof (T), name); } public object GetInstance(Type pluginType, string name) { return CreateInstance(pluginType, name); } public T TryGetInstance<T>() where T : class { return (T) TryGetInstance(typeof (T)); } public T TryGetInstance<T>(string name) where T : class { return (T) TryGetInstance(typeof (T), name); } public object TryGetInstance(Type pluginType) { return _sessionCache.TryGetDefault(pluginType, _pipelineGraph); } public object TryGetInstance(Type pluginType, string name) { return _pipelineGraph.Instances.HasInstance(pluginType, name) ? ((IContext) this).GetInstance(pluginType, name) : null; } public IEnumerable<T> All<T>() where T : class { return _sessionCache.All<T>(); } public object ResolveFromLifecycle(Type pluginType, Instance instance) { var cache = _pipelineGraph.DetermineLifecycle(pluginType, instance).FindCache(_pipelineGraph); return cache.Get(pluginType, instance, this); } public object BuildNewInSession(Type pluginType, Instance instance) { if (pluginType == null) throw new ArgumentNullException("pluginType"); if (instance == null) throw new ArgumentNullException("instance"); var plan = instance.ResolveBuildPlan(pluginType, _pipelineGraph.Policies); return plan.Build(this, this); } public object BuildNewInOriginalContext(Type pluginType, Instance instance) { var session = new BuildSession(pipelineGraph.Root(), requestedName: instance.Name); return session.BuildNewInSession(pluginType, instance); } public IEnumerable<T> GetAllInstances<T>() { return _pipelineGraph.Instances.GetAllInstances(typeof (T)) .Select(x => (T) FindObject(typeof (T), x)) .ToArray(); } public IEnumerable<object> GetAllInstances(Type pluginType) { var allInstances = _pipelineGraph.Instances.GetAllInstances(pluginType); return allInstances.Select(x => FindObject(pluginType, x)).ToArray(); } public static BuildSession ForPluginGraph(PluginGraph graph, ExplicitArguments args = null) { var pipeline = PipelineGraph.BuildRoot(graph); return new BuildSession(pipeline, args: args); } public static BuildSession Empty(ExplicitArguments args = null) { return ForPluginGraph(new PluginGraph(), args); } public virtual object CreateInstance(Type pluginType, string name) { var instance = _pipelineGraph.Instances.FindInstance(pluginType, name); if (instance == null) { var ex = new StructureMapConfigurationException("Could not find an Instance named '{0}' for PluginType {1}", name, pluginType.GetFullName()); ex.Context = new WhatDoIHaveWriter(_pipelineGraph).GetText(new ModelQuery {PluginType = pluginType}, "The current configuration for type {0} is:".ToFormat(pluginType.GetFullName())); throw ex; } return FindObject(pluginType, instance); } public void Push(Instance instance) { if (_instances.Contains(instance)) { throw new StructureMapBuildException("Bi-directional dependency relationship detected!" + Environment.NewLine + "Check the StructureMap stacktrace below:"); } _instances.Push(instance); } public void Pop() { if (_instances.Any()) { _instances.Pop(); } } public Type ParentType { get { if (_instances.Count > 1) { return _instances.ToArray().Skip(1).First().ReturnedType; } return null; } } // This is where all Creation happens public virtual object FindObject(Type pluginType, Instance instance) { var lifecycle = _pipelineGraph.DetermineLifecycle(pluginType, instance); return _sessionCache.GetObject(pluginType, instance, lifecycle); } public Policies Policies { get { return _pipelineGraph.Policies; } } } }
// Copyright 2020 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 // // 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 Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using YetiVSI.DebugEngine.Exit; using YetiCommon; namespace YetiVSI.DebugEngine { // The event interface GUIDs can be extracted from // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VSSDK\VisualStudioIntegration\Common\IDL\msdbg.idl class LoadCompleteEvent : DebugEvent, IDebugLoadCompleteEvent2 { public LoadCompleteEvent() : base((uint)(enum_EVENTATTRIBUTES.EVENT_STOPPING | enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS), new Guid("B1844850-1349-45D4-9F12-495212F5EB0B")) { } } class EntryPointEvent : DebugEvent, IDebugEntryPointEvent2 { public EntryPointEvent() : base((uint)(enum_EVENTATTRIBUTES.EVENT_STOPPING | enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS), new Guid("E8414A3E-1642-48EC-829E-5F4040E16DA9")) { } } public class EngineCreateEvent : DebugEvent, IDebugEngineCreateEvent2 { readonly IDebugEngine2 _engine; public EngineCreateEvent(IDebugEngine2 engine) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("FE5B734C-759D-4E59-AB04-F103343BDD06")) { _engine = engine; } public int GetEngine(out IDebugEngine2 pEngine) { pEngine = _engine; return VSConstants.S_OK; } } public class ProgramCreateEvent : DebugEvent, IDebugProgramCreateEvent2 { public ProgramCreateEvent() : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("96CD11EE-ECD4-4E89-957E-B5D496FC4139")) { } } public class ProgramDestroyEvent : DebugEvent, IDebugProgramDestroyEvent2 { readonly uint _exitCode = 0; public ProgramDestroyEvent(ExitInfo exitInfo) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("E147E9E3-6440-4073-A7B7-A65592C714B5")) { ExitInfo = exitInfo; } public int GetExitCode(out uint exitCode) { exitCode = _exitCode; return VSConstants.S_OK; } public ExitInfo ExitInfo { get; } } public class ThreadCreateEvent : DebugEvent, IDebugThreadCreateEvent2 { public ThreadCreateEvent() : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA")) { } } public class ThreadDestroyEvent : DebugEvent, IDebugThreadDestroyEvent2 { readonly uint _exitCode; public ThreadDestroyEvent(uint exitCode) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("2C3B7532-A36F-4A6E-9072-49BE649B8541")) { _exitCode = exitCode; } public int GetExitCode(out uint exitCode) { exitCode = _exitCode; return VSConstants.S_OK; } } public class BreakEvent : DebugEvent, IDebugBreakEvent2 { public BreakEvent() : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNC_STOP, new Guid("C7405D1D-E24B-44E0-B707-D8A5A4E1641B")) { } } public class StepCompleteEvent : DebugEvent, IDebugStepCompleteEvent2 { public StepCompleteEvent() : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNC_STOP, new Guid("0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D")) { } } public class BreakpointEvent : DebugEvent, IDebugBreakpointEvent2 { readonly IEnumDebugBoundBreakpoints2 _breakpointEnum; public BreakpointEvent(IEnumDebugBoundBreakpoints2 breakpointEnum) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNC_STOP, new Guid("501C1E21-C557-48B8-BA30-A1EAB0BC4A74")) { _breakpointEnum = breakpointEnum; } public int EnumBreakpoints(out IEnumDebugBoundBreakpoints2 breakpointEnum) { breakpointEnum = _breakpointEnum; return VSConstants.S_OK; } } public class BreakpointErrorEvent : DebugEvent, IDebugBreakpointErrorEvent2 { readonly DebugBreakpointError _breakpointError; public BreakpointErrorEvent(DebugBreakpointError breakpointError) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("ABB0CA42-F82B-4622-84E4-6903AE90F210")) { _breakpointError = breakpointError; } public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 breakpointError) { breakpointError = _breakpointError; return VSConstants.S_OK; } } public class BreakpointBoundEvent : DebugEvent, IDebugBreakpointBoundEvent2 { readonly IDebugPendingBreakpoint2 _pendingBreakpoint; readonly IEnumerable<IDebugBoundBreakpoint2> _newlyBoundBreakpoints; readonly BoundBreakpointEnumFactory _breakpointBoundEnumFactory; public BreakpointBoundEvent(IDebugPendingBreakpoint2 pendingBreakpoint) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("1dddb704-cf99-4b8a-b746-dabb01dd13a0")) { _pendingBreakpoint = pendingBreakpoint; _newlyBoundBreakpoints = null; _breakpointBoundEnumFactory = null; } public BreakpointBoundEvent( IDebugPendingBreakpoint2 pendingBreakpoint, IEnumerable<IDebugBoundBreakpoint2> newlyBoundBreakpoints, BoundBreakpointEnumFactory breakpointBoundEnumFactory) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, new Guid("1dddb704-cf99-4b8a-b746-dabb01dd13a0")) { _pendingBreakpoint = pendingBreakpoint; _newlyBoundBreakpoints = newlyBoundBreakpoints; _breakpointBoundEnumFactory = breakpointBoundEnumFactory; } public int EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 boundBreakpointsEnum) { if (_newlyBoundBreakpoints != null && _breakpointBoundEnumFactory != null) { boundBreakpointsEnum = _breakpointBoundEnumFactory.Create(_newlyBoundBreakpoints); } else { _pendingBreakpoint.EnumBoundBreakpoints(out boundBreakpointsEnum); } return VSConstants.S_OK; } public int GetPendingBreakpoint(out IDebugPendingBreakpoint2 pendingBreakpoint) { pendingBreakpoint = _pendingBreakpoint; return VSConstants.S_OK; } } public class DebugExpressionEvaluationCompleteEvent : DebugEvent, IDebugExpressionEvaluationCompleteEvent2 { readonly IDebugExpression2 _expr; readonly IDebugProperty2 _result; public DebugExpressionEvaluationCompleteEvent(IDebugExpression2 expr, IDebugProperty2 result) : base((uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS, new Guid("C0E13A85-238A-4800-8315-D947C960A843")) { _expr = expr; _result = result; } public int GetExpression(out IDebugExpression2 expr) { expr = _expr; return VSConstants.S_OK; } public int GetResult(out IDebugProperty2 result) { result = _result; return VSConstants.S_OK; } } public class ExceptionEvent : DebugEvent, IDebugExceptionEvent2 { readonly string _exceptionName; readonly string _detail; readonly uint _code; readonly enum_EXCEPTION_STATE _state; public ExceptionEvent(string exceptionName, uint code, enum_EXCEPTION_STATE state, string description) : base((uint)enum_EVENTATTRIBUTES.EVENT_SYNC_STOP, YetiConstants.ExceptionEventGuid) { _exceptionName = exceptionName; _code = code; _state = state; _detail = description; } public int CanPassToDebuggee() => VSConstants.S_FALSE; public int GetException(EXCEPTION_INFO[] pExceptionInfo) { if (pExceptionInfo.Length == 0) { return VSConstants.E_INVALIDARG; } pExceptionInfo[0] = new EXCEPTION_INFO { bstrExceptionName = _exceptionName, dwCode = _code, dwState = _state, guidType = Iid }; return VSConstants.S_OK; } public int GetExceptionDescription(out string description) { description = ""; if (!string.IsNullOrEmpty(_exceptionName)) { description = _exceptionName + ": "; } description += _detail; return VSConstants.S_OK; } public int PassToDebuggee(int fPass) => VSConstants.E_FAIL; } public class DebugModuleLoadEvent : DebugEvent, IDebugModuleLoadEvent2 { readonly IDebugModule2 _module; readonly bool _loaded; // true if a module was loaded, false if a module was unloaded public DebugModuleLoadEvent(IDebugModule2 module, bool loaded) : base((uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS, new Guid("989DB083-0D7C-40D1-A9D9-921BF611A4B2")) { _module = module; _loaded = loaded; } public int GetModule(out IDebugModule2 pModule, ref string pbstrDebugMessage, ref int pbLoad) { pModule = _module; pbLoad = _loaded ? 1 : 0; return VSConstants.S_OK; } } public class DebugSymbolSearchEvent : DebugEvent, IDebugSymbolSearchEvent2 { readonly IDebugModule3 _module; readonly string _moduleName; readonly string _errorMessage; readonly bool _loaded; public DebugSymbolSearchEvent(IDebugModule3 module, string moduleName, string errorMessage, bool loaded) : base((uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS, new Guid("2A064CA8-D657-4CC8-B11B-F545BFC3FDD3")) { _module = module; _moduleName = moduleName; _errorMessage = errorMessage; _loaded = loaded; } // Haven't seen this method being actually invoked, VS asks IDebugModule3 directly. public int GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags) { pModule = _module; // From documentation: Returns a string containing any error messages from the // module. If there is no error, then this string will just contain the module's // name but it is never empty. // https://docs.microsoft.com/en-us/visualstudio/extensibility/debugger/reference/idebugsymbolsearchevent2-getsymbolsearchinfo?view=vs-2019 pbstrDebugMessage = _errorMessage ?? _moduleName; if (pdwModuleInfoFlags.Length > 0) { pdwModuleInfoFlags[0] = _loaded ? enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED : 0; } return VSConstants.S_OK; } } public class DebugEvent : IDebugEvent2 { readonly uint _attributes; public Guid Iid { get; private set; } protected DebugEvent(uint attributes, Guid iid) { _attributes = attributes; Iid = iid; } int IDebugEvent2.GetAttributes(out uint attributes) { attributes = _attributes; return VSConstants.S_OK; } } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DriveProxy.Utils; using Google.Apis.Download; namespace DriveProxy.API { partial class DriveService { public class DownloadStream : Stream { protected string _DownloadFilePath = ""; protected long _FileSize = 0; protected DateTime _LastWriteTime = default(DateTime); protected Parameters _Parameters = null; public override StreamType Type { get { return StreamType.Download; } } public DateTime ModifiedDate { get { if (_FileInfo != null) { return _FileInfo.ModifiedDate; } return default(DateTime); } } public int ChunkSize { get { if (_Parameters == null || !_Parameters.ChunkSize.HasValue) { return 0; } return _Parameters.ChunkSize.Value; } } public bool CheckIfAlreadyDownloaded { get { if (_Parameters == null || !_Parameters.CheckIfAlreadyDownloaded.HasValue) { return true; } return _Parameters.CheckIfAlreadyDownloaded.Value; } } public long FileSize { get { return _FileSize; } } public DateTime LastWriteTime { get { return _LastWriteTime; } } public void Init(FileInfo fileInfo, Parameters parameters = null) { try { if (Status == StatusType.Queued) { throw new Exception("Stream has already been queued."); } if (Status != StatusType.NotStarted) { throw new Exception("Stream has already been started."); } if (fileInfo == null) { throw new Exception("File is null."); } if (fileInfo.IsFolder) { throw new Exception("Cannot download folder."); } _FileId = fileInfo.Id; _FileInfo = fileInfo; _Parameters = parameters ?? new Parameters(); base.Init(); } catch (Exception exception) { Log.Error(exception); } } protected override void Start() { try { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); _FileInfo = _DriveService.GetFile(FileId); if (_FileInfo == null) { throw new Exception("File '" + FileId + "' no longer exists."); } if (String.IsNullOrEmpty(_FileInfo.FilePath)) { throw new Exception("FileInfo.FilePath is blank."); } } catch (Exception exception) { Log.Error(exception); } try { if (_FileInfo.IsGoogleDoc) { try { API.DriveService.WriteGoogleDoc(_FileInfo); DriveService_ProgressChanged(DownloadStatus.Completed, 0, null); return; } catch (Exception exception) { Log.Error(exception); } } else if (String.IsNullOrEmpty(_FileInfo.DownloadUrl)) { try { DriveService_ProgressChanged(DownloadStatus.Completed, 0, null); return; } catch (Exception exception) { Log.Error(exception); } } else if (_FileInfo.FileSize == 0) { try { API.DriveService.CreateFile(FileInfo); DriveService_ProgressChanged(DownloadStatus.Completed, 0, null); return; } catch (Exception exception) { Log.Error(exception); } } else { FileInfoStatus fileInfoStatus = API.DriveService.GetFileInfoStatus(_FileInfo); if (fileInfoStatus == FileInfoStatus.ModifiedOnDisk || fileInfoStatus == FileInfoStatus.OnDisk) { if (CheckIfAlreadyDownloaded) { try { DriveService_ProgressChanged(DownloadStatus.Completed, 0, null); return; } catch (Exception exception) { Log.Error(exception); } } } } } catch (Exception exception) { Log.Error(exception); } try { API.DriveService.DeleteFile(_FileInfo.FilePath); _DownloadFilePath = _FileInfo.FilePath + ".download"; Lock(_DownloadFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } catch (Exception exception) { Log.Error(exception); } try { _FileSize = API.DriveService.GetLong(_FileInfo.FileSize); _LastWriteTime = API.DriveService.GetFileLastWriteTime(_DownloadFilePath); } catch (Exception exception) { Log.Error(exception); } try { using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { var request = new MediaDownloader(connection.Service); request.ProgressChanged += DriveService_ProgressChanged; if (ChunkSize <= 0) { request.ChunkSize = API.DriveService.Settings.DownloadFileChunkSize; } else if (ChunkSize > MediaDownloader.MaximumChunkSize) { request.ChunkSize = MediaDownloader.MaximumChunkSize; } else { request.ChunkSize = ChunkSize; } _CancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.Tasks.Task<IDownloadProgress> task = request.DownloadAsync(_FileInfo.DownloadUrl, _FileStream, _CancellationTokenSource.Token); } } catch (Exception exception) { Log.Error(exception); } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(DownloadStatus.Failed, 0, exception); } catch { Debugger.Break(); } Log.Error(exception); } } protected override void Dispose() { try { CloseFileStream(); if (!String.IsNullOrEmpty(_DownloadFilePath)) { API.DriveService.DeleteFile(_DownloadFilePath); _DownloadFilePath = ""; } base.Dispose(); } catch (Exception exception) { Log.Error(exception, false); } } protected void DriveService_ProgressChanged(DownloadStatus status, long bytesDownloaded, Exception exception) { try { DriveService_ProgressChanged(new DownloadProgress(status, bytesDownloaded, exception)); } catch (Exception exception2) { Log.Error(exception2); } } protected void DriveService_ProgressChanged(IDownloadProgress downloadProgress) { try { var status = StatusType.NotStarted; long bytesProcessed = downloadProgress.BytesDownloaded; long totalBytes = FileSize; Exception processException = downloadProgress.Exception; if (downloadProgress.Status == DownloadStatus.Completed) { status = StatusType.Completed; } else if (downloadProgress.Status == DownloadStatus.Downloading) { status = StatusType.Processing; } else if (downloadProgress.Status == DownloadStatus.Failed) { status = StatusType.Failed; } else { status = StatusType.Starting; } UpdateProgress(status, bytesProcessed, totalBytes, processException); if (_Status == StatusType.Failed && String.IsNullOrEmpty(_ExceptionMessage)) { Debugger.Break(); } if (Processed) { try { if (Completed) { if (!String.IsNullOrEmpty(_DownloadFilePath)) { if (!String.Equals(_DownloadFilePath, _FileInfo.FilePath, StringComparison.CurrentCultureIgnoreCase)) { API.DriveService.MoveFile(_DownloadFilePath, _FileInfo.FilePath); _DownloadFilePath = ""; } } } else { if (!String.IsNullOrEmpty(_DownloadFilePath)) { API.DriveService.DeleteFile(_DownloadFilePath); _DownloadFilePath = ""; } _DriveService.CleanupFile(_FileInfo, true); } } catch (Exception exception) { Log.Error(exception, false); if (!Failed) { _ExceptionMessage = exception.Message; _Status = StatusType.Failed; } } try { if (Completed) { _LastWriteTime = API.DriveService.GetFileLastWriteTime(FilePath); if (!API.DriveService.IsDateTimeEqual(_LastWriteTime, _FileInfo.ModifiedDate)) { _LastWriteTime = API.DriveService.SetFileLastWriteTime(FilePath, _FileInfo.ModifiedDate); } } } catch (Exception exception) { Log.Error(exception, false); if (!Failed) { _ExceptionMessage = exception.Message; _Status = StatusType.Failed; } } } if (_Status == StatusType.Failed && String.IsNullOrEmpty(_ExceptionMessage)) { Debugger.Break(); } InvokeOnProgressEvent(); } catch (Exception exception) { Log.Error(exception, false); } } private class DownloadProgress : IDownloadProgress { private readonly long _bytesDownloaded; private readonly Exception _exception; private readonly DownloadStatus _status = DownloadStatus.NotStarted; public DownloadProgress(DownloadStatus status, long bytesDownloaded, Exception exception) { _status = status; _bytesDownloaded = bytesDownloaded; _exception = exception; } public long BytesDownloaded { get { return _bytesDownloaded; } } public Exception Exception { get { return _exception; } } public DownloadStatus Status { get { return _status; } } } public class Parameters { public bool? CheckIfAlreadyDownloaded; public int? ChunkSize; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; namespace System.ServiceModel { [KnownType(typeof(FaultException.FaultCodeData))] [KnownType(typeof(FaultException.FaultCodeData[]))] [KnownType(typeof(FaultException.FaultReasonData))] [KnownType(typeof(FaultException.FaultReasonData[]))] public class FaultException : CommunicationException { internal const string Namespace = "http://schemas.xmlsoap.org/Microsoft/WindowsCommunicationFoundation/2005/08/Faults/"; private string _action; private FaultCode _code; private FaultReason _reason; private MessageFault _fault; public FaultException() : base(SR.SFxFaultReason) { _code = FaultException.DefaultCode; _reason = FaultException.DefaultReason; } public FaultException(string reason) : base(reason) { _code = FaultException.DefaultCode; _reason = FaultException.CreateReason(reason); } public FaultException(FaultReason reason) : base(FaultException.GetSafeReasonText(reason)) { _code = FaultException.DefaultCode; _reason = FaultException.EnsureReason(reason); } public FaultException(string reason, FaultCode code) : base(reason) { _code = FaultException.EnsureCode(code); _reason = FaultException.CreateReason(reason); } public FaultException(FaultReason reason, FaultCode code) : base(FaultException.GetSafeReasonText(reason)) { _code = FaultException.EnsureCode(code); _reason = FaultException.EnsureReason(reason); } public FaultException(string reason, FaultCode code, string action) : base(reason) { _code = FaultException.EnsureCode(code); _reason = FaultException.CreateReason(reason); _action = action; } internal FaultException(string reason, FaultCode code, string action, Exception innerException) : base(reason, innerException) { _code = FaultException.EnsureCode(code); _reason = FaultException.CreateReason(reason); _action = action; } public FaultException(FaultReason reason, FaultCode code, string action) : base(FaultException.GetSafeReasonText(reason)) { _code = FaultException.EnsureCode(code); _reason = FaultException.EnsureReason(reason); _action = action; } internal FaultException(FaultReason reason, FaultCode code, string action, Exception innerException) : base(FaultException.GetSafeReasonText(reason), innerException) { _code = FaultException.EnsureCode(code); _reason = FaultException.EnsureReason(reason); _action = action; } public FaultException(MessageFault fault) : base(FaultException.GetSafeReasonText(GetReason(fault))) { if (fault == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault"); _code = FaultException.EnsureCode(fault.Code); _reason = FaultException.EnsureReason(fault.Reason); _fault = fault; } public FaultException(MessageFault fault, string action) : base(FaultException.GetSafeReasonText(GetReason(fault))) { if (fault == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault"); _code = fault.Code; _reason = fault.Reason; _fault = fault; _action = action; } public string Action { get { return _action; } } public FaultCode Code { get { return _code; } } private static FaultReason DefaultReason { get { return new FaultReason(SR.SFxFaultReason); } } private static FaultCode DefaultCode { get { return new FaultCode("Sender"); } } public override string Message { get { return FaultException.GetSafeReasonText(this.Reason); } } public FaultReason Reason { get { return _reason; } } internal MessageFault Fault { get { return _fault; } } private static FaultCode CreateCode(string code) { return (code != null) ? new FaultCode(code) : DefaultCode; } public static FaultException CreateFault(MessageFault messageFault, params Type[] faultDetailTypes) { return CreateFault(messageFault, null, faultDetailTypes); } public static FaultException CreateFault(MessageFault messageFault, string action, params Type[] faultDetailTypes) { if (messageFault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageFault"); } if (faultDetailTypes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultDetailTypes"); } DataContractSerializerFaultFormatter faultFormatter = new DataContractSerializerFaultFormatter(faultDetailTypes); return faultFormatter.Deserialize(messageFault, action); } public virtual MessageFault CreateMessageFault() { if (_fault != null) { return _fault; } else { return MessageFault.CreateFault(_code, _reason); } } private static FaultReason CreateReason(string reason) { return (reason != null) ? new FaultReason(reason) : DefaultReason; } private static FaultReason GetReason(MessageFault fault) { if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault"); } return fault.Reason; } internal static string GetSafeReasonText(MessageFault messageFault) { if (messageFault == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageFault"); return GetSafeReasonText(messageFault.Reason); } internal static string GetSafeReasonText(FaultReason reason) { if (reason == null) return SR.SFxUnknownFaultNullReason0; try { return reason.GetMatchingTranslation(System.Globalization.CultureInfo.CurrentCulture).Text; } catch (ArgumentException) { if (reason.Translations.Count == 0) { return SR.SFxUnknownFaultZeroReasons0; } else { return SR.Format(SR.SFxUnknownFaultNoMatchingTranslation1, reason.Translations[0].Text); } } } private static FaultCode EnsureCode(FaultCode code) { return (code != null) ? code : DefaultCode; } private static FaultReason EnsureReason(FaultReason reason) { return (reason != null) ? reason : DefaultReason; } internal class FaultCodeData { private string _name; private string _ns; internal static FaultCode Construct(FaultCodeData[] nodes) { FaultCode code = null; for (int i = nodes.Length - 1; i >= 0; i--) { code = new FaultCode(nodes[i]._name, nodes[i]._ns, code); } return code; } internal static FaultCodeData[] GetObjectData(FaultCode code) { FaultCodeData[] array = new FaultCodeData[FaultCodeData.GetDepth(code)]; for (int i = 0; i < array.Length; i++) { array[i] = new FaultCodeData(); array[i]._name = code.Name; array[i]._ns = code.Namespace; code = code.SubCode; } if (code != null) { Fx.Assert("FaultException.FaultCodeData.GetObjectData: (code != null)"); } return array; } private static int GetDepth(FaultCode code) { int depth = 0; while (code != null) { depth++; code = code.SubCode; } return depth; } } internal class FaultReasonData { private string _xmlLang; private string _text; internal static FaultReason Construct(FaultReasonData[] nodes) { FaultReasonText[] reasons = new FaultReasonText[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { reasons[i] = new FaultReasonText(nodes[i]._text, nodes[i]._xmlLang); } return new FaultReason(reasons); } internal static FaultReasonData[] GetObjectData(FaultReason reason) { SynchronizedReadOnlyCollection<FaultReasonText> translations = reason.Translations; FaultReasonData[] array = new FaultReasonData[translations.Count]; for (int i = 0; i < translations.Count; i++) { array[i] = new FaultReasonData(); array[i]._xmlLang = translations[i].XmlLang; array[i]._text = translations[i].Text; } return array; } } } public class FaultException<TDetail> : FaultException { private TDetail _detail; public FaultException(TDetail detail) : base() { _detail = detail; } public FaultException(TDetail detail, string reason) : base(reason) { _detail = detail; } public FaultException(TDetail detail, FaultReason reason) : base(reason) { _detail = detail; } public FaultException(TDetail detail, string reason, FaultCode code) : base(reason, code) { _detail = detail; } public FaultException(TDetail detail, FaultReason reason, FaultCode code) : base(reason, code) { _detail = detail; } public FaultException(TDetail detail, string reason, FaultCode code, string action) : base(reason, code, action) { _detail = detail; } public FaultException(TDetail detail, FaultReason reason, FaultCode code, string action) : base(reason, code, action) { _detail = detail; } public TDetail Detail { get { return _detail; } } public override MessageFault CreateMessageFault() { return MessageFault.CreateFault(this.Code, this.Reason, _detail); } public override string ToString() { return SR.Format(SR.SFxFaultExceptionToString3, this.GetType(), this.Message, _detail != null ? _detail.ToString() : String.Empty); } } }
// 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.IO; using System.Reflection; using System.Text; using Gallio.Common.IO; using Gallio.Framework.Pattern; using Gallio.Common.Reflection; using Gallio.Framework; using Gallio.Model; namespace MbUnit.Framework { /// <summary> /// An abstract base class for data source attributes that obtain contents from /// a local file, manifest resource, or inline data. /// </summary> /// <remarks> /// <para> /// At most one location type may be used. /// </para> /// </remarks> [AttributeUsage(PatternAttributeTargets.DataContext, AllowMultiple = true, Inherited = true)] public abstract class ContentAttribute : DataPatternAttribute { // TODO: Add support for Uris. We will need to define an IUriLoader service to help // with this. Such a service would be quite useful for many other reasons also. /// <summary> /// Gets or sets the inline data contents as a string. /// </summary> /// <remarks> /// <para> /// It is an error to specify more than one content source property. /// </para> /// </remarks> public string Contents { get; set; } /// <summary> /// Gets or sets the path of a local file relative to the current working /// directory from which the file contents should be read. /// </summary> /// <remarks> /// <para> /// It is an error to specify more than one content source property. /// </para> /// </remarks> public string FilePath { get; set; } /// <summary> /// Gets or sets a <see cref="Type"/> that is used to locate the assembly and /// namespace within which to resolve a manifest resource in combination /// with the <see cref="ResourcePath"/> property. /// </summary> /// <remarks> /// <para> /// If no value is specified, the test fixture type is used as the resource scope. /// </para> /// </remarks> /// <seealso cref="ResourcePath"/> public Type ResourceScope { get; set; } /// <summary> /// Gets or sets the path of a manifest resource from which the contents should be read. /// </summary> /// <remarks> /// <para> /// The path will be resolved within the assembly containing the /// <see cref="ResourceScope"/> type or the test fixture type if none if provided. /// </para> /// <para> /// During resolution, a resource name is constructed from the resource path by /// translating backslashes to periods. If the named resource is found within /// the scoped assembly manifest, it is used. Otherwise, the name is prepended /// with the scoped type's namespace and second lookup is attempted. If this /// final attempt fails, then an error is raised at runtime. /// </para> /// <para> /// Examples: /// <list type="bullet"> /// <item>If the <see cref="ResourceScope" /> is <c>MyNamespace.MyType</c> within /// assembly <c>MyAssembly.dll</c> and if <see cref="ResourcePath" /> is <c>"Resources\Image.gif"</c>, then /// resolution will first check whether <c>Resources.Image.gif</c> in /// <c>MyAssembly.dll</c> is a valid resource. If not found, it will consider /// <c>MyNamespace.Resources.Image.gif</c>. If still not found, then a runtime error will be raised.</item> /// <item>If no <see cref="ResourceScope" /> is provided, then the containing test fixture type /// will be used as the resource scope. The above resolution strategy still applies.</item> /// </list> /// </para> /// <para> /// It is an error to specify more than one content source property. /// </para> /// </remarks> /// <seealso cref="ResourceScope"/> public string ResourcePath { get; set; } /// <summary> /// Gets or sets the outcome of the test when an error occured /// while opening or reading the data file or the resource. /// </summary> /// <remarks> /// <para> /// The default outcome is <see cref="MbUnit.Framework.OutcomeOnFileError.Failed"/>. /// </para> /// </remarks> public OutcomeOnFileError OutcomeOnFileError { get; set; } /// <summary> /// Default constructor. /// </summary> protected ContentAttribute() { OutcomeOnFileError = OutcomeOnFileError.Failed; } /// <summary> /// Gets the name of the location that is providing the data, or null if none. /// </summary> /// <remarks> /// <para> /// The name will be the filename or resource path if specified, or a special /// locale-aware string (such as "&lt;inline&gt;") if the contents were specified /// inline via the <see cref="Contents"/> property. /// </para> /// </remarks> protected virtual string GetDataLocationName() { return Contents != null ? "<inline>" : (FilePath ?? ResourcePath); } /// <summary> /// Opens the contents as a stream. /// </summary> /// <remarks> /// <para> /// If you override this method to return data from a different stream, consider /// also overriding <see cref="ValidateSource" /> in case the manner in which the /// data source location is specified has also changed. /// </para> /// </remarks> /// <param name="codeElementInfo">The code element to which the attribute was applied.</param> /// <returns>The stream.</returns> protected virtual Stream OpenStream(ICodeElementInfo codeElementInfo) { var content = GetContent(); content.CodeElementInfo = codeElementInfo; return content.OpenStream(); } /// <summary> /// Opens the contents as a text reader. /// </summary> /// <remarks> /// <para> /// If you override this method to return data from a different stream, consider /// also overriding <see cref="ValidateSource" /> in case the manner in which the /// data source location is specified has also changed. /// </para> /// </remarks> /// <param name="codeElementInfo">The code element to which the attribute was applied.</param> /// <returns>The text reader.</returns> protected virtual TextReader OpenTextReader(ICodeElementInfo codeElementInfo) { var content = GetContent(); content.CodeElementInfo = codeElementInfo; try { return content.OpenTextReader(); } catch (FileNotFoundException exception) { OnDataError(exception); throw; } catch (UnauthorizedAccessException exception) { OnDataError(exception); throw; } } private void OnDataError(Exception exception) { switch (OutcomeOnFileError) { case OutcomeOnFileError.Inconclusive: throw new TestInconclusiveException("An exception occurred while getting data items.", exception); case OutcomeOnFileError.Skipped: throw new TestTerminatedException(TestOutcome.Skipped, "An exception occurred while getting data items.", exception); default: break; } } /// <summary> /// Returns true if the contents are dynamic, or false if they are static. /// </summary> /// <remarks> /// <para> /// Static contents can only change if the test assembly is recompiled. /// </para> /// </remarks> protected virtual bool IsDynamic { get { return GetContent().IsDynamic; } } /// <inheritdoc /> protected override void Validate(IPatternScope scope, ICodeElementInfo codeElement) { base.Validate(scope, codeElement); ValidateSource(scope, codeElement); } /// <summary> /// Validates the data source properties of the content attribute. /// </summary> /// <remarks> /// <para> /// Throws a <see cref="PatternUsageErrorException" /> if none of the source /// properties, such as <see cref="Contents"/>, <see cref="FilePath" /> or /// <see cref="ResourcePath"/> have been set. /// </para> /// </remarks> /// <param name="scope">The pattern scope.</param> /// <param name="codeElement">The code element to which the attribute was applied.</param> /// <exception cref="PatternUsageErrorException">Thrown if none of the source properties, such as <see cref="Contents"/>, /// <see cref="FilePath" /> or <see cref="ResourcePath"/> have been set.</exception> protected virtual void ValidateSource(IPatternScope scope, ICodeElementInfo codeElement) { if (Contents == null && FilePath == null && ResourcePath == null) ThrowUsageErrorException("At least one source property must be specified."); } private Content GetContent() { if (Contents != null) { return new ContentInline(Contents); } if (FilePath != null) { return new ContentFile(FilePath); } return new ContentEmbeddedResource(ResourcePath, ResourceScope); } } /// <summary> /// Determines the outcome of data-driven test when an error occured while /// opening or reading the external data file or resource. /// </summary> public enum OutcomeOnFileError { /// <summary> /// The test is skipped on file error. /// </summary> /// <seealso cref="TestOutcome.Skipped"/> Skipped, /// <summary> /// The test is inconclusive on file error. /// </summary> /// <seealso cref="TestOutcome.Inconclusive"/> Inconclusive, /// <summary> /// The test failed on file error. /// </summary> /// <seealso cref="TestOutcome.Failed"/> /// <seealso cref="TestOutcome.Error"/> Failed, } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.Specialized; // DEBUG ON using System.Diagnostics; // DEBUG OFF using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar appearance data to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianAvatarServiceConnector")] public class SimianAvatarServiceConnector : IAvatarService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // private static string ZeroID = UUID.Zero.ToString(); private string m_serverUrl = String.Empty; private bool m_Enabled = false; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianAvatarServiceConnector() { } public string Name { get { return "SimianAvatarServiceConnector"; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IAvatarService>(this); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IAvatarService>(this); } } #endregion ISharedRegionModule public SimianAvatarServiceConnector(IConfigSource source) { CommonInit(source); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AvatarServices", ""); if (name == Name) CommonInit(source); } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["AvatarService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("AvatarServerURI"); if (!String.IsNullOrEmpty(serviceUrl)) { if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; m_Enabled = true; } } if (String.IsNullOrEmpty(m_serverUrl)) m_log.Info("[SIMIAN AVATAR CONNECTOR]: No AvatarServerURI specified, disabling connector"); } #region IAvatarService // <summary> // Retrieves the LLPackedAppearance field from user data and unpacks // it into an AvatarAppearance structure // </summary> // <param name="userID"></param> public AvatarAppearance GetAppearance(UUID userID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap map = null; try { map = OSDParser.DeserializeJson(response["LLPackedAppearance"].AsString()) as OSDMap; } catch { } if (map != null) { AvatarAppearance appearance = new AvatarAppearance(map); // DEBUG ON m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR] retrieved appearance for {0}:\n{1}",userID,appearance.ToString()); // DEBUG OFF return appearance; } m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to decode appearance for {0}",userID); return null; } m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to get appearance for {0}: {1}", userID,response["Message"].AsString()); return null; } // <summary> // </summary> // <param name=""></param> public bool SetAppearance(UUID userID, AvatarAppearance appearance) { OSDMap map = appearance.Pack(); if (map == null) { m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to encode appearance for {0}",userID); return false; } // m_log.DebugFormat("[SIMIAN AVATAR CONNECTOR] save appearance for {0}",userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LLPackedAppearance", OSDParser.SerializeJsonString(map) } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (! success) m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to save appearance for {0}: {1}", userID,response["Message"].AsString()); return success; } // <summary> // </summary> // <param name=""></param> public AvatarData GetAvatar(UUID userID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap map = null; try { map = OSDParser.DeserializeJson(response["LLAppearance"].AsString()) as OSDMap; } catch { } if (map != null) { AvatarWearable[] wearables = new AvatarWearable[13]; wearables[0] = new AvatarWearable(map["ShapeItem"].AsUUID(), map["ShapeAsset"].AsUUID()); wearables[1] = new AvatarWearable(map["SkinItem"].AsUUID(), map["SkinAsset"].AsUUID()); wearables[2] = new AvatarWearable(map["HairItem"].AsUUID(), map["HairAsset"].AsUUID()); wearables[3] = new AvatarWearable(map["EyesItem"].AsUUID(), map["EyesAsset"].AsUUID()); wearables[4] = new AvatarWearable(map["ShirtItem"].AsUUID(), map["ShirtAsset"].AsUUID()); wearables[5] = new AvatarWearable(map["PantsItem"].AsUUID(), map["PantsAsset"].AsUUID()); wearables[6] = new AvatarWearable(map["ShoesItem"].AsUUID(), map["ShoesAsset"].AsUUID()); wearables[7] = new AvatarWearable(map["SocksItem"].AsUUID(), map["SocksAsset"].AsUUID()); wearables[8] = new AvatarWearable(map["JacketItem"].AsUUID(), map["JacketAsset"].AsUUID()); wearables[9] = new AvatarWearable(map["GlovesItem"].AsUUID(), map["GlovesAsset"].AsUUID()); wearables[10] = new AvatarWearable(map["UndershirtItem"].AsUUID(), map["UndershirtAsset"].AsUUID()); wearables[11] = new AvatarWearable(map["UnderpantsItem"].AsUUID(), map["UnderpantsAsset"].AsUUID()); wearables[12] = new AvatarWearable(map["SkirtItem"].AsUUID(), map["SkirtAsset"].AsUUID()); AvatarAppearance appearance = new AvatarAppearance(); appearance.Wearables = wearables; appearance.AvatarHeight = (float)map["Height"].AsReal(); AvatarData avatar = new AvatarData(appearance); // Get attachments map = null; try { map = OSDParser.DeserializeJson(response["LLAttachments"].AsString()) as OSDMap; } catch { } if (map != null) { foreach (KeyValuePair<string, OSD> kvp in map) avatar.Data[kvp.Key] = kvp.Value.AsString(); } return avatar; } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ", LLAppearance is missing or invalid"); return null; } } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ": " + response["Message"].AsString()); } return null; } // <summary> // </summary> // <param name=""></param> public bool SetAvatar(UUID userID, AvatarData avatar) { m_log.Debug("[SIMIAN AVATAR CONNECTOR]: SetAvatar called for " + userID); if (avatar.AvatarType == 1) // LLAvatar { AvatarAppearance appearance = avatar.ToAvatarAppearance(); OSDMap map = new OSDMap(); map["Height"] = OSD.FromReal(appearance.AvatarHeight); map["BodyItem"] = appearance.Wearables[AvatarWearable.BODY][0].ItemID.ToString(); map["EyesItem"] = appearance.Wearables[AvatarWearable.EYES][0].ItemID.ToString(); map["GlovesItem"] = appearance.Wearables[AvatarWearable.GLOVES][0].ItemID.ToString(); map["HairItem"] = appearance.Wearables[AvatarWearable.HAIR][0].ItemID.ToString(); map["JacketItem"] = appearance.Wearables[AvatarWearable.JACKET][0].ItemID.ToString(); map["PantsItem"] = appearance.Wearables[AvatarWearable.PANTS][0].ItemID.ToString(); map["ShirtItem"] = appearance.Wearables[AvatarWearable.SHIRT][0].ItemID.ToString(); map["ShoesItem"] = appearance.Wearables[AvatarWearable.SHOES][0].ItemID.ToString(); map["SkinItem"] = appearance.Wearables[AvatarWearable.SKIN][0].ItemID.ToString(); map["SkirtItem"] = appearance.Wearables[AvatarWearable.SKIRT][0].ItemID.ToString(); map["SocksItem"] = appearance.Wearables[AvatarWearable.SOCKS][0].ItemID.ToString(); map["UnderPantsItem"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].ItemID.ToString(); map["UnderShirtItem"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].ItemID.ToString(); map["BodyAsset"] = appearance.Wearables[AvatarWearable.BODY][0].AssetID.ToString(); map["EyesAsset"] = appearance.Wearables[AvatarWearable.EYES][0].AssetID.ToString(); map["GlovesAsset"] = appearance.Wearables[AvatarWearable.GLOVES][0].AssetID.ToString(); map["HairAsset"] = appearance.Wearables[AvatarWearable.HAIR][0].AssetID.ToString(); map["JacketAsset"] = appearance.Wearables[AvatarWearable.JACKET][0].AssetID.ToString(); map["PantsAsset"] = appearance.Wearables[AvatarWearable.PANTS][0].AssetID.ToString(); map["ShirtAsset"] = appearance.Wearables[AvatarWearable.SHIRT][0].AssetID.ToString(); map["ShoesAsset"] = appearance.Wearables[AvatarWearable.SHOES][0].AssetID.ToString(); map["SkinAsset"] = appearance.Wearables[AvatarWearable.SKIN][0].AssetID.ToString(); map["SkirtAsset"] = appearance.Wearables[AvatarWearable.SKIRT][0].AssetID.ToString(); map["SocksAsset"] = appearance.Wearables[AvatarWearable.SOCKS][0].AssetID.ToString(); map["UnderPantsAsset"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].AssetID.ToString(); map["UnderShirtAsset"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].AssetID.ToString(); OSDMap items = new OSDMap(); foreach (KeyValuePair<string, string> kvp in avatar.Data) { if (kvp.Key.StartsWith("_ap_")) items.Add(kvp.Key, OSD.FromString(kvp.Value)); } NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LLAppearance", OSDParser.SerializeJsonString(map) }, { "LLAttachments", OSDParser.SerializeJsonString(items) } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed saving appearance for " + userID + ": " + response["Message"].AsString()); return success; } else { m_log.Error("[SIMIAN AVATAR CONNECTOR]: Can't save appearance for " + userID + ". Unhandled avatar type " + avatar.AvatarType); return false; } } public bool ResetAvatar(UUID userID) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: ResetAvatar called for " + userID + ", implement this"); return false; } public bool SetItems(UUID userID, string[] names, string[] values) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: SetItems called for " + userID + " with " + names.Length + " names and " + values.Length + " values, implement this"); return false; } public bool RemoveItems(UUID userID, string[] names) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: RemoveItems called for " + userID + " with " + names.Length + " names, implement this"); return false; } #endregion IAvatarService } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // An abstraction for holding and aggregating exceptions. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Disable the "reference to volatile field not treated as volatile" error. #pragma warning disable 0420 namespace System.Threading.Tasks { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Security; /// <summary> /// An exception holder manages a list of exceptions for one particular task. /// It offers the ability to aggregate, but more importantly, also offers intrinsic /// support for propagating unhandled exceptions that are never observed. It does /// this by aggregating and throwing if the holder is ever GC'd without the holder's /// contents ever having been requested (e.g. by a Task.Wait, Task.get_Exception, etc). /// This behavior is prominent in .NET 4 but is suppressed by default beyond that release. /// </summary> internal class TaskExceptionHolder { /// <summary>Whether we should propagate exceptions on the finalizer.</summary> private readonly static bool s_failFastOnUnobservedException = ShouldFailFastOnUnobservedException(); /// <summary>Whether the AppDomain has started to unload.</summary> private static volatile bool s_domainUnloadStarted; /// <summary>An event handler used to notify of domain unload.</summary> private static volatile EventHandler s_adUnloadEventHandler; /// <summary>The task with which this holder is associated.</summary> private readonly Task m_task; /// <summary> /// The lazily-initialized list of faulting exceptions. Volatile /// so that it may be read to determine whether any exceptions were stored. /// </summary> private volatile List<ExceptionDispatchInfo> m_faultExceptions; /// <summary>An exception that triggered the task to cancel.</summary> private ExceptionDispatchInfo m_cancellationException; /// <summary>Whether the holder was "observed" and thus doesn't cause finalization behavior.</summary> private volatile bool m_isHandled; /// <summary> /// Creates a new holder; it will be registered for finalization. /// </summary> /// <param name="task">The task this holder belongs to.</param> internal TaskExceptionHolder(Task task) { Contract.Requires(task != null, "Expected a non-null task."); m_task = task; EnsureADUnloadCallbackRegistered(); } private static bool ShouldFailFastOnUnobservedException() { return false; } private static void EnsureADUnloadCallbackRegistered() { if (s_adUnloadEventHandler == null && Interlocked.CompareExchange( ref s_adUnloadEventHandler, AppDomainUnloadCallback, null) == null) { AppDomain.CurrentDomain.DomainUnload += s_adUnloadEventHandler; } } private static void AppDomainUnloadCallback(object sender, EventArgs e) { s_domainUnloadStarted = true; } /// <summary> /// A finalizer that repropagates unhandled exceptions. /// </summary> ~TaskExceptionHolder() { // Raise unhandled exceptions only when we know that neither the process or nor the appdomain is being torn down. // We need to do this filtering because all TaskExceptionHolders will be finalized during shutdown or unload // regardles of reachability of the task (i.e. even if the user code was about to observe the task's exception), // which can otherwise lead to spurious crashes during shutdown. if (m_faultExceptions != null && !m_isHandled && !Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload() && !s_domainUnloadStarted) { // We don't want to crash the finalizer thread if any ThreadAbortExceptions // occur in the list or in any nested AggregateExceptions. // (Don't rethrow ThreadAbortExceptions.) foreach (ExceptionDispatchInfo edi in m_faultExceptions) { var exp = edi.SourceException; AggregateException aggExp = exp as AggregateException; if (aggExp != null) { AggregateException flattenedAggExp = aggExp.Flatten(); foreach (Exception innerExp in flattenedAggExp.InnerExceptions) { if (innerExp is ThreadAbortException) return; } } else if (exp is ThreadAbortException) { return; } } // We will only propagate if this is truly unhandled. The reason this could // ever occur is somewhat subtle: if a Task's exceptions are observed in some // other finalizer, and the Task was finalized before the holder, the holder // will have been marked as handled before even getting here. // Give users a chance to keep this exception from crashing the process // First, publish the unobserved exception and allow users to observe it AggregateException exceptionToThrow = new AggregateException( Environment.GetResourceString("TaskExceptionHolder_UnhandledException"), m_faultExceptions); UnobservedTaskExceptionEventArgs ueea = new UnobservedTaskExceptionEventArgs(exceptionToThrow); TaskScheduler.PublishUnobservedTaskException(m_task, ueea); // Now, if we are still unobserved and we're configured to crash on unobserved, throw the exception. // We need to publish the event above even if we're not going to crash, hence // why this check doesn't come at the beginning of the method. if (s_failFastOnUnobservedException && !ueea.m_observed) { throw exceptionToThrow; } } } /// <summary>Gets whether the exception holder is currently storing any exceptions for faults.</summary> internal bool ContainsFaultList { get { return m_faultExceptions != null; } } /// <summary> /// Add an exception to the holder. This will ensure the holder is /// in the proper state (handled/unhandled) depending on the list's contents. /// </summary> /// <param name="exceptionObject"> /// An exception object (either an Exception, an ExceptionDispatchInfo, /// an IEnumerable{Exception}, or an IEnumerable{ExceptionDispatchInfo}) /// to add to the list. /// </param> /// <remarks> /// Must be called under lock. /// </remarks> internal void Add(object exceptionObject) { Add(exceptionObject, representsCancellation: false); } /// <summary> /// Add an exception to the holder. This will ensure the holder is /// in the proper state (handled/unhandled) depending on the list's contents. /// </summary> /// <param name="representsCancellation"> /// Whether the exception represents a cancellation request (true) or a fault (false). /// </param> /// <param name="exceptionObject"> /// An exception object (either an Exception, an ExceptionDispatchInfo, /// an IEnumerable{Exception}, or an IEnumerable{ExceptionDispatchInfo}) /// to add to the list. /// </param> /// <remarks> /// Must be called under lock. /// </remarks> internal void Add(object exceptionObject, bool representsCancellation) { Contract.Requires(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); Contract.Requires( exceptionObject is Exception || exceptionObject is IEnumerable<Exception> || exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable<ExceptionDispatchInfo>, "TaskExceptionHolder.Add(): Expected Exception, IEnumerable<Exception>, ExceptionDispatchInfo, or IEnumerable<ExceptionDispatchInfo>"); if (representsCancellation) SetCancellationException(exceptionObject); else AddFaultException(exceptionObject); } /// <summary>Sets the cancellation exception.</summary> /// <param name="exceptionObject">The cancellation exception.</param> /// <remarks> /// Must be called under lock. /// </remarks> private void SetCancellationException(object exceptionObject) { Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null."); Debug.Assert(m_cancellationException == null, "Expected SetCancellationException to be called only once."); // Breaking this assumption will overwrite a previously OCE, // and implies something may be wrong elsewhere, since there should only ever be one. Debug.Assert(m_faultExceptions == null, "Expected SetCancellationException to be called before any faults were added."); // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere. // If this changes, make sure to only conditionally mark as handled below. // Store the cancellation exception var oce = exceptionObject as OperationCanceledException; if (oce != null) { m_cancellationException = ExceptionDispatchInfo.Capture(oce); } else { var edi = exceptionObject as ExceptionDispatchInfo; Debug.Assert(edi != null && edi.SourceException is OperationCanceledException, "Expected an OCE or an EDI that contained an OCE"); m_cancellationException = edi; } // This is just cancellation, and there are no faults, so mark the holder as handled. MarkAsHandled(false); } /// <summary>Adds the exception to the fault list.</summary> /// <param name="exceptionObject">The exception to store.</param> /// <remarks> /// Must be called under lock. /// </remarks> private void AddFaultException(object exceptionObject) { Contract.Requires(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject"); // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. var exceptions = m_faultExceptions; if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1); else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that var exception = exceptionObject as Exception; if (exception != null) { exceptions.Add(ExceptionDispatchInfo.Capture(exception)); } else { // Handle ExceptionDispatchInfo by storing it into the list var edi = exceptionObject as ExceptionDispatchInfo; if (edi != null) { exceptions.Add(edi); } else { // Handle enumerables of exceptions by capturing each of the contained exceptions into an EDI and storing it var exColl = exceptionObject as IEnumerable<Exception>; if (exColl != null) { #if DEBUG int numExceptions = 0; #endif foreach (var exc in exColl) { #if DEBUG Debug.Assert(exc != null, "No exceptions should be null"); numExceptions++; #endif exceptions.Add(ExceptionDispatchInfo.Capture(exc)); } #if DEBUG Debug.Assert(numExceptions > 0, "Collection should contain at least one exception."); #endif } else { // Handle enumerables of EDIs by storing them directly var ediColl = exceptionObject as IEnumerable<ExceptionDispatchInfo>; if (ediColl != null) { exceptions.AddRange(ediColl); #if DEBUG Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); foreach(var tmp in exceptions) { Debug.Assert(tmp != null, "No dispatch infos should be null"); } #endif } // Anything else is a programming error else { throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), nameof(exceptionObject)); } } } } // If all of the exceptions are ThreadAbortExceptions and/or // AppDomainUnloadExceptions, we do not want the finalization // probe to propagate them, so we consider the holder to be // handled. If a subsequent exception comes in of a different // kind, we will reactivate the holder. for (int i = 0; i < exceptions.Count; i++) { var t = exceptions[i].SourceException.GetType(); if (t != typeof(ThreadAbortException) && t != typeof(AppDomainUnloadedException)) { MarkAsUnhandled(); break; } else if (i == exceptions.Count - 1) { MarkAsHandled(false); } } } /// <summary> /// A private helper method that ensures the holder is considered /// unhandled, i.e. it is registered for finalization. /// </summary> private void MarkAsUnhandled() { // If a thread partially observed this thread's exceptions, we // should revert back to "not handled" so that subsequent exceptions // must also be seen. Otherwise, some could go missing. We also need // to reregister for finalization. if (m_isHandled) { GC.ReRegisterForFinalize(this); m_isHandled = false; } } /// <summary> /// A private helper method that ensures the holder is considered /// handled, i.e. it is not registered for finalization. /// </summary> /// <param name="calledFromFinalizer">Whether this is called from the finalizer thread.</param> internal void MarkAsHandled(bool calledFromFinalizer) { if (!m_isHandled) { if (!calledFromFinalizer) { GC.SuppressFinalize(this); } m_isHandled = true; } } /// <summary> /// Allocates a new aggregate exception and adds the contents of the list to /// it. By calling this method, the holder assumes exceptions to have been /// "observed", such that the finalization check will be subsequently skipped. /// </summary> /// <param name="calledFromFinalizer">Whether this is being called from a finalizer.</param> /// <param name="includeThisException">An extra exception to be included (optionally).</param> /// <returns>The aggregate exception to throw.</returns> internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException) { var exceptions = m_faultExceptions; Debug.Assert(exceptions != null, "Expected an initialized list."); Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); // Mark as handled and aggregate the exceptions. MarkAsHandled(calledFromFinalizer); // If we're only including the previously captured exceptions, // return them immediately in an aggregate. if (includeThisException == null) return new AggregateException(exceptions); // Otherwise, the caller wants a specific exception to be included, // so return an aggregate containing that exception and the rest. Exception[] combinedExceptions = new Exception[exceptions.Count + 1]; for (int i = 0; i < combinedExceptions.Length - 1; i++) { combinedExceptions[i] = exceptions[i].SourceException; } combinedExceptions[combinedExceptions.Length - 1] = includeThisException; return new AggregateException(combinedExceptions); } /// <summary> /// Wraps the exception dispatch infos into a new read-only collection. By calling this method, /// the holder assumes exceptions to have been "observed", such that the finalization /// check will be subsequently skipped. /// </summary> internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos() { var exceptions = m_faultExceptions; Debug.Assert(exceptions != null, "Expected an initialized list."); Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); MarkAsHandled(false); return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions); } /// <summary> /// Gets the ExceptionDispatchInfo representing the singular exception /// that was the cause of the task's cancellation. /// </summary> /// <returns> /// The ExceptionDispatchInfo for the cancellation exception. May be null. /// </returns> internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { var edi = m_cancellationException; Debug.Assert(edi == null || edi.SourceException is OperationCanceledException, "Expected the EDI to be for an OperationCanceledException"); return edi; } } }
// 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.Reflection; using Xunit; namespace System.Reflection.Compatibility.UnitTests.ConstructorTests { public class TestMultiDimensionalArray { [Fact] public void TestSZArrayConstructorInvoke() { Type type = Type.GetType("System.Object[]"); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(1, cia.Length); ConstructorInfo ci = cia[0]; object[] arr = null; int[] blength = new int[] { -100, -9, -1 }; for (int j = 0; j < blength.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (object[])ci.Invoke(new Object[] { blength[j] }); }); } int[] glength = new int[] { 0, 1, 2, 3, 5, 10, 99, 65535 }; for (int j = 0; j < glength.Length; j++) { arr = (object[])ci.Invoke(new Object[] { glength[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength[j], arr.Length); } } [Fact] public void Test1DArrayConstructorInvoke() { Type type = Type.GetType("System.Char[*]"); MethodInfo milb = type.GetMethod("GetLowerBound"); MethodInfo miub = type.GetMethod("GetUpperBound"); PropertyInfo pil = type.GetProperty("Length"); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(2, cia.Length); for (int i = 0; i < cia.Length; i++) { char[] arr = null; switch (cia[i].GetParameters().Length) { case 1: { int[] blength = new int[] { -100, -9, -1 }; for (int j = 0; j < blength.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (char[])cia[i].Invoke(new Object[] { blength[j] }); }); } int[] glength = new int[] { 0, 1, 2, 3, 5, 10, 99 }; for (int j = 0; j < glength.Length; j++) { arr = (char[])cia[i].Invoke(new Object[] { glength[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength[j], arr.Length); } } break; case 2: { int[] b_lower = new int[] { -20, 0, 20 }; int[] blength = new int[] { -100, -9, -1 }; for (int j = 0; j < blength.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (char[])cia[i].Invoke(new Object[] { b_lower[j], blength[j] }); }); } int[] glower = new int[] { 0, 1, -1, 2, -3, 5, -10, 99, 100 }; int[] glength = new int[] { 0, 1, 3, 2, 3, 5, 10, 99, 0 }; for (int j = 0; j < glength.Length; j++) { object o = cia[i].Invoke(new Object[] { glower[j], glength[j] }); Assert.Equal(glower[j], (int)milb.Invoke(o, new object[] { 0 })); Assert.Equal(glower[j] + glength[j] - 1, (int)miub.Invoke(o, new object[] { 0 })); Assert.Equal(glength[j], (int)pil.GetValue(o, null)); } } break; } } } [Fact] public void Test2DArrayConstructorInvoke() { Type type = Type.GetType("System.Int32[,]", false); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(2, cia.Length); for (int i = 0; i < cia.Length; i++) { int[,] arr = null; switch (cia[i].GetParameters().Length) { case 2: { int[] blength1 = new int[] { -11, -10, 0, 10 }; int[] blength2 = new int[] { -33, 0, -20, -33 }; for (int j = 0; j < blength1.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (int[,])cia[i].Invoke(new Object[] { blength1[j], blength2[j] }); }); } int[] glength1 = new int[] { 0, 0, 1, 1, 2, 1, 2, 10, 17, 99 }; int[] glength2 = new int[] { 0, 1, 0, 1, 1, 2, 2, 110, 5, 900 }; for (int j = 0; j < glength1.Length; j++) { arr = (int[,])cia[i].Invoke(new Object[] { glength1[j], glength2[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(0, arr.GetLowerBound(1)); Assert.Equal(glength2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(glength1[j] * glength2[j], arr.Length); } } break; case 4: { int[] b_lower1 = new int[] { 10, -10, 20 }; int[] b_lower2 = new int[] { -10, 10, 0 }; int[] blength1 = new int[] { -11, -10, 0 }; int[] blength2 = new int[] { -33, 0, -20 }; for (int j = 0; j < blength1.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (int[,])cia[i].Invoke(new Object[] { b_lower1[j], blength1[j], b_lower2[j], blength2[j] }); }); } int baseNum = 3; int baseNum4 = baseNum * baseNum * baseNum * baseNum; int[] glower1 = new int[baseNum4]; int[] glower2 = new int[baseNum4]; int[] glength1 = new int[baseNum4]; int[] glength2 = new int[baseNum4]; int cnt = 0; for (int pos1 = 0; pos1 < baseNum; pos1++) for (int pos2 = 0; pos2 < baseNum; pos2++) for (int pos3 = 0; pos3 < baseNum; pos3++) for (int pos4 = 0; pos4 < baseNum; pos4++) { int saved = cnt; glower1[cnt] = saved % baseNum; saved = saved / baseNum; glength1[cnt] = saved % baseNum; saved = saved / baseNum; glower2[cnt] = saved % baseNum; saved = saved / baseNum; glength2[cnt] = saved % baseNum; cnt++; } for (int j = 0; j < glength1.Length; j++) { arr = (int[,])cia[i].Invoke(new Object[] { glower1[j], glength1[j], glower2[j], glength2[j] }); Assert.Equal(glower1[j], arr.GetLowerBound(0)); Assert.Equal(glower1[j] + glength1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glower2[j], arr.GetLowerBound(1)); Assert.Equal(glower2[j] + glength2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(glength1[j] * glength2[j], arr.Length); } // lower can be < 0 glower1 = new int[] { 10, 10, 65535, 40, 0, -10, -10, -20, -40, 0 }; glower2 = new int[] { 5, 99, -100, 30, 4, -5, 99, 100, -30, 0 }; glength1 = new int[] { 1, 200, 2, 40, 0, 1, 200, 2, 40, 65535 }; glength2 = new int[] { 5, 10, 1, 0, 4, 5, 65535, 1, 0, 4 }; for (int j = 0; j < glength1.Length; j++) { arr = (int[,])cia[i].Invoke(new Object[] { glower1[j], glength1[j], glower2[j], glength2[j] }); Assert.Equal(glower1[j], arr.GetLowerBound(0)); Assert.Equal(glower1[j] + glength1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glower2[j], arr.GetLowerBound(1)); Assert.Equal(glower2[j] + glength2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(glength1[j] * glength2[j], arr.Length); } } break; } } } [Fact] public void Test4DArrayConstructorInvoke() { Type type = Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]"); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(2, cia.Length); Assert.Throws<TypeLoadException>(() => { type = Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]"); }); } [Fact] public void TestJaggedArrayConstructorInvoke() { Type type = Type.GetType("System.String[][]"); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(2, cia.Length); for (int i = 0; i < cia.Length; i++) { string[][] arr = null; ParameterInfo[] pia = cia[i].GetParameters(); switch (pia.Length) { case 1: { int[] blength1 = new int[] { -11, -10, -99 }; for (int j = 0; j < blength1.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (string[][])cia[i].Invoke(new Object[] { blength1[j] }); }); } int[] glength1 = new int[] { 0, 1, 2, 10, 17, 99 }; // for (int j = 0; j < glength1.Length; j++) { arr = (string[][])cia[i].Invoke(new Object[] { glength1[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength1[j], arr.Length); } } break; case 2: { int[] blength1 = new int[] { -11, -10, 10, 1 }; int[] blength2 = new int[] { -33, 0, -33, -1 }; for (int j = 0; j < blength1.Length; j++) { Assert.Throws<OverflowException>(() => { arr = (string[][])cia[i].Invoke(new Object[] { blength1[j], blength2[j] }); }); } int[] glength1 = new int[] { 0, 0, 0, 1, 1, 2, 1, 2, 10, 17, 500 }; int[] glength2 = new int[] { -33, 0, 1, 0, 1, 1, 2, 2, 110, 5, 100 }; for (int j = 0; j < glength1.Length; j++) { arr = (string[][])cia[i].Invoke(new Object[] { glength1[j], glength2[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength1[j], arr.Length); if (glength1[j] == 0) { Assert.Equal(arr.Length, 0); } else { Assert.Equal(0, arr[0].GetLowerBound(0)); Assert.Equal(glength2[j] - 1, arr[0].GetUpperBound(0)); Assert.Equal(glength2[j], arr[0].Length); } } } break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #define DEBUG // Do not remove this, it is needed to retain calls to these conditional methods in release builds namespace System.Diagnostics { /// <summary> /// Provides a set of properties and methods for debugging code. /// </summary> static partial class Debug { private static readonly object s_ForLock = new Object(); [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition) { Assert(condition, string.Empty, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message) { Assert(condition, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] [System.Security.SecuritySafeCritical] public static void Assert(bool condition, string message, string detailMessage) { if (!condition) { string stackTrace; try { stackTrace = Environment.StackTrace; } catch { stackTrace = ""; } WriteLine(FormatAssert(stackTrace, message, detailMessage)); s_logger.ShowAssertDialog(stackTrace, message, detailMessage); } } [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message) { Assert(false, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message, string detailMessage) { Assert(false, message, detailMessage); } private static string FormatAssert(string stackTrace, string message, string detailMessage) { return SR.DebugAssertBanner + Environment.NewLine + SR.DebugAssertShortMessage + Environment.NewLine + message + Environment.NewLine + SR.DebugAssertLongMessage + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace; } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args) { Assert(condition, message, string.Format(detailMessageFormat, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message) { Write(message + Environment.NewLine); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message) { s_logger.WriteCore(message ?? string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value) { WriteLine((value == null) ? string.Empty : value.ToString()); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value, string category) { WriteLine((value == null) ? string.Empty : value.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string format, params object[] args) { WriteLine(string.Format(null, format, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message, string category) { if (category == null) { WriteLine(message); } else { WriteLine(category + ":" + ((message == null) ? string.Empty : message)); } } [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value) { Write((value == null) ? string.Empty : value.ToString()); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message, string category) { if (category == null) { Write(message); } else { Write(category + ":" + ((message == null) ? string.Empty : message)); } } [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value, string category) { Write((value == null) ? string.Empty : value.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message) { if (condition) { Write(message); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value) { if (condition) { Write(value); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message, string category) { if (condition) { Write(message, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value, string category) { if (condition) { Write(value, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value) { if (condition) { WriteLine(value); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value, string category) { if (condition) { WriteLine(value, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string value) { if (condition) { WriteLine(value); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string value, string category) { if (condition) { WriteLine(value, category); } } internal interface IDebugLogger { void ShowAssertDialog(string stackTrace, string message, string detailMessage); void WriteCore(string message); } private sealed class DebugAssertException : Exception { internal DebugAssertException(string message, string detailMessage, string stackTrace) : base(message + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace) { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2 { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; /// <summary> /// This is a sample server Petstore server. You can find out more about /// Swagger at &lt;a /// href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on /// irc.freenode.net, #swagger. For this sample, you can use the api key /// "special-key" to test the authorization filters /// </summary> public partial interface ISwaggerPetstoreV2 : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Subscription credentials which uniquely identify client /// subscription. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an existing pet /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use /// tag1, tag2, tag3 for testing. /// </remarks> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a pet /// </summary> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Place an order for a pet /// </summary> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. /// Other values will generated exceptions /// </remarks> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything /// above 1000 or nonintegers will generate API errors /// </remarks> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs user into the system /// </summary> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get user by user name /// </summary> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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 TestCSByte() { var test = new BooleanBinaryOpTest__TestCSByte(); 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(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // 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(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_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 BooleanBinaryOpTest__TestCSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestCSByte testClass) { var result = Avx.TestC(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCSByte testClass) { fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestCSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public BooleanBinaryOpTest__TestCSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.TestC( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.TestC( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.TestC( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<SByte>* pClsVar1 = &_clsVar1) fixed (Vector256<SByte>* pClsVar2 = &_clsVar2) { var result = Avx.TestC( Avx.LoadVector256((SByte*)(pClsVar1)), Avx.LoadVector256((SByte*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestCSByte(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestCSByte(); fixed (Vector256<SByte>* pFld1 = &test._fld1) fixed (Vector256<SByte>* pFld2 = &test._fld2) { var result = Avx.TestC( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.TestC( Avx.LoadVector256((SByte*)(&test._fld1)), Avx.LoadVector256((SByte*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(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<SByte> op1, Vector256<SByte> op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
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 Remotus.Web.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) 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.Linq; using System.Text; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpemt { /// <summary> /// This class provide static method for Decode/Encode of some auto-detect structure /// </summary> public class RdpemtUtility { /// <summary> /// Parse RDP_BW_START structure from RDPEMT subheader /// </summary> /// <param name="data">Data of subheader, not include first two bytes of Parse RDP_BW_START</param> /// <returns></returns> public static RDP_BW_START ParseRdpBWStart(byte[] data) { RDP_BW_START bwStart = new RDP_BW_START(); bwStart.sequenceNumber = ParseUInt16(data, 0); bwStart.requestType = (AUTO_DETECT_REQUEST_TYPE)ParseUInt16(data, 2); return bwStart; } /// <summary> /// Encode a RDP_BW_START structure for subheader, don't encode the first two field /// </summary> /// <param name="bwStart"></param> /// <returns></returns> public static byte[] EncodeRdpBWStart(RDP_BW_START bwStart) { List<byte> bufferList = new List<byte>(); bufferList.AddRange(ToBytes(bwStart.sequenceNumber)); bufferList.AddRange(ToBytes((ushort)bwStart.requestType)); return bufferList.ToArray(); } /// <summary> /// Parse RDP_BW_STOP structure from RDPEMT subheader /// </summary> /// <param name="data">Data of subheader, not include first two bytes of Parse RDP_BW_STOP</param> /// <returns></returns> public static RDP_BW_STOP ParseRdpBWStop(byte[] data) { RDP_BW_STOP bwStop = new RDP_BW_STOP(); bwStop.sequenceNumber = ParseUInt16(data, 0); bwStop.requestType = (AUTO_DETECT_REQUEST_TYPE)ParseUInt16(data, 2); // payloadLength and payload Must not be present when the structure is in SubHeaderData of RDP_TUNNEL_SUBHEADER return bwStop; } /// <summary> /// Encode a RDP_BW_STOP structure for subheader, don't encode the first two field /// </summary> /// <param name="bwStop"></param> /// <returns></returns> public static byte[] EncodeRdpBWStop(RDP_BW_STOP bwStop) { List<byte> bufferList = new List<byte>(); bufferList.AddRange(ToBytes(bwStop.sequenceNumber)); bufferList.AddRange(ToBytes((ushort)bwStop.requestType)); // payloadLength and payload Must not be present when the structure is in SubHeaderData of RDP_TUNNEL_SUBHEADER return bufferList.ToArray(); } /// <summary> /// Parse RDP_NETCHAR_RESULT structure from RDPEMT subheader /// </summary> /// <param name="data">Data of subheader, not include first two bytes of Parse RDP_NETCHAR_RESULT</param> /// <returns></returns> public static RDP_NETCHAR_RESULT ParseRdpNetCharResult(byte[] data) { RDP_NETCHAR_RESULT ncRes = new RDP_NETCHAR_RESULT(); ncRes.sequenceNumber = ParseUInt16(data, 0); ncRes.requestType = (AUTO_DETECT_REQUEST_TYPE)ParseUInt16(data, 2); int index = 4; if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BANDWIDTH_AVERAGERTT) { ncRes.bandwidth = ParseUInt32(data, index); index += 4; ncRes.averageRTT = ParseUInt32(data, index); index += 4; } else if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BASERTT_AVERAGERTT) { ncRes.baseRTT = ParseUInt32(data, index); index += 4; ncRes.averageRTT = ParseUInt32(data, index); index += 4; } else if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BASERTT_BANDWIDTH_AVERAGERTT) { ncRes.baseRTT = ParseUInt32(data, index); index += 4; ncRes.bandwidth = ParseUInt32(data, index); index += 4; ncRes.averageRTT = ParseUInt32(data, index); index += 4; } return ncRes; } /// <summary> /// Encode a RDP_NETCHAR_RESULT structure for subheader, don't encode the first two field /// </summary> /// <param name="bwStop"></param> /// <returns></returns> public static byte[] EncodeNetCharResult(RDP_NETCHAR_RESULT ncRes) { List<byte> bufferList = new List<byte>(); bufferList.AddRange(ToBytes(ncRes.sequenceNumber)); bufferList.AddRange(ToBytes((ushort)ncRes.requestType)); if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BANDWIDTH_AVERAGERTT) { bufferList.AddRange(ToBytes(ncRes.bandwidth)); bufferList.AddRange(ToBytes(ncRes.averageRTT)); } else if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BASERTT_AVERAGERTT) { bufferList.AddRange(ToBytes(ncRes.baseRTT)); bufferList.AddRange(ToBytes(ncRes.averageRTT)); } else if (ncRes.requestType == AUTO_DETECT_REQUEST_TYPE.RDP_NETCHAR_RESULT_BASERTT_BANDWIDTH_AVERAGERTT) { bufferList.AddRange(ToBytes(ncRes.baseRTT)); bufferList.AddRange(ToBytes(ncRes.bandwidth)); bufferList.AddRange(ToBytes(ncRes.averageRTT)); } return bufferList.ToArray(); } /// <summary> /// Parse RDP_BW_RESULTS structure from RDPEMT subheader /// </summary> /// <param name="data">Data of subheader, not include first two bytes of Parse RDP_BW_RESULTS</param> /// <returns></returns> public static RDP_BW_RESULTS ParseRdpBWResults(byte[] data) { RDP_BW_RESULTS bwRes = new RDP_BW_RESULTS(); bwRes.sequenceNumber = ParseUInt16(data, 0); bwRes.responseType = (AUTO_DETECT_RESPONSE_TYPE)ParseUInt16(data, 2); int index = 4; bwRes.timeDelta = ParseUInt32(data, index); index += 4; bwRes.byteCount = ParseUInt32(data, index); index += 4; return bwRes; } /// <summary> /// Encode a RDP_BW_RESULTS structure for subheader, don't encode the first two field /// </summary> /// <param name="bwStop"></param> /// <returns></returns> public static byte[] EncodeRdpBWResults(RDP_BW_RESULTS bwRes) { List<byte> bufferList = new List<byte>(); bufferList.AddRange(ToBytes(bwRes.sequenceNumber)); bufferList.AddRange(ToBytes((ushort)bwRes.responseType)); bufferList.AddRange(ToBytes(bwRes.timeDelta)); bufferList.AddRange(ToBytes(bwRes.byteCount)); return bufferList.ToArray(); } #region Private Methods /// <summary> /// Parse UInt32 /// </summary> /// <param name="data"></param> /// <param name="startPos"></param> /// <returns></returns> private static uint ParseUInt32(byte[] data, int startPos) { byte[] buffer = new byte[4]; Array.Copy(data, startPos, buffer, 0, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(buffer); } return BitConverter.ToUInt32(buffer, 0); } /// <summary> /// Parse UInt16 /// </summary> /// <param name="data"></param> /// <param name="startPos"></param> /// <returns></returns> private static ushort ParseUInt16(byte[] data, int startPos) { byte[] buffer = new byte[2]; Array.Copy(data, startPos, buffer, 0, 2); if (!BitConverter.IsLittleEndian) { Array.Reverse(buffer); } return BitConverter.ToUInt16(buffer, 0); } /// <summary> /// Encode UInt32 /// </summary> /// <param name="value"></param> /// <returns></returns> private static byte[] ToBytes(uint value) { byte[] buffer = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) { Array.Reverse(buffer); } return buffer; } /// <summary> /// Encode UInt16 /// </summary> /// <param name="value"></param> /// <returns></returns> private static byte[] ToBytes(ushort value) { byte[] buffer = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) { Array.Reverse(buffer); } return buffer; } #endregion Private Methos } }
// 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.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks.Sources; using System.Threading.Tasks.Sources.Tests; using Xunit; namespace System.Threading.Tasks.Tests { public class ValueTaskTests { public enum CtorMode { Result, Task, ValueTaskSource } [Fact] public void NonGeneric_DefaultValueTask_DefaultValue() { Assert.True(default(ValueTask).IsCompleted); Assert.True(default(ValueTask).IsCompletedSuccessfully); Assert.False(default(ValueTask).IsFaulted); Assert.False(default(ValueTask).IsCanceled); } [Fact] public void Generic_DefaultValueTask_DefaultValue() { Assert.True(default(ValueTask<int>).IsCompleted); Assert.True(default(ValueTask<int>).IsCompletedSuccessfully); Assert.False(default(ValueTask<int>).IsFaulted); Assert.False(default(ValueTask<int>).IsCanceled); Assert.Equal(0, default(ValueTask<int>).Result); Assert.True(default(ValueTask<string>).IsCompleted); Assert.True(default(ValueTask<string>).IsCompletedSuccessfully); Assert.False(default(ValueTask<string>).IsFaulted); Assert.False(default(ValueTask<string>).IsCanceled); Assert.Equal(null, default(ValueTask<string>).Result); } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void NonGeneric_CreateFromSuccessfullyCompleted_IsCompletedSuccessfully(CtorMode mode) { ValueTask t = mode == CtorMode.Result ? default : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void Generic_CreateFromSuccessfullyCompleted_IsCompletedSuccessfully(CtorMode mode) { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Equal(42, t.Result); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void NonGeneric_CreateFromNotCompleted_ThenCompleteSuccessfully(CtorMode mode) { object completer = null; ValueTask t = default; switch (mode) { case CtorMode.Task: var tcs = new TaskCompletionSource<int>(); t = new ValueTask(tcs.Task); completer = tcs; break; case CtorMode.ValueTaskSource: var mre = new ManualResetValueTaskSource<int>(); t = new ValueTask(mre, 0); completer = mre; break; } Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); switch (mode) { case CtorMode.Task: ((TaskCompletionSource<int>)completer).SetResult(42); break; case CtorMode.ValueTaskSource: ((ManualResetValueTaskSource<int>)completer).SetResult(42); break; } Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void Generic_CreateFromNotCompleted_ThenCompleteSuccessfully(CtorMode mode) { object completer = null; ValueTask<int> t = default; switch (mode) { case CtorMode.Task: var tcs = new TaskCompletionSource<int>(); t = new ValueTask<int>(tcs.Task); completer = tcs; break; case CtorMode.ValueTaskSource: var mre = new ManualResetValueTaskSource<int>(); t = new ValueTask<int>(mre, 0); completer = mre; break; } Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); switch (mode) { case CtorMode.Task: ((TaskCompletionSource<int>)completer).SetResult(42); break; case CtorMode.ValueTaskSource: ((ManualResetValueTaskSource<int>)completer).SetResult(42); break; } Assert.Equal(42, t.Result); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void NonGeneric_CreateFromNotCompleted_ThenFault(CtorMode mode) { object completer = null; ValueTask t = default; switch (mode) { case CtorMode.Task: var tcs = new TaskCompletionSource<int>(); t = new ValueTask(tcs.Task); completer = tcs; break; case CtorMode.ValueTaskSource: var mre = new ManualResetValueTaskSource<int>(); t = new ValueTask(mre, 0); completer = mre; break; } Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Exception e = new InvalidOperationException(); switch (mode) { case CtorMode.Task: ((TaskCompletionSource<int>)completer).SetException(e); break; case CtorMode.ValueTaskSource: ((ManualResetValueTaskSource<int>)completer).SetException(e); break; } Assert.True(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.True(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.GetAwaiter().GetResult())); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void Generic_CreateFromNotCompleted_ThenFault(CtorMode mode) { object completer = null; ValueTask<int> t = default; switch (mode) { case CtorMode.Task: var tcs = new TaskCompletionSource<int>(); t = new ValueTask<int>(tcs.Task); completer = tcs; break; case CtorMode.ValueTaskSource: var mre = new ManualResetValueTaskSource<int>(); t = new ValueTask<int>(mre, 0); completer = mre; break; } Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Exception e = new InvalidOperationException(); switch (mode) { case CtorMode.Task: ((TaskCompletionSource<int>)completer).SetException(e); break; case CtorMode.ValueTaskSource: ((ManualResetValueTaskSource<int>)completer).SetException(e); break; } Assert.True(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.True(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.Result)); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.GetAwaiter().GetResult())); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void NonGeneric_CreateFromFaulted_IsFaulted(CtorMode mode) { InvalidOperationException e = new InvalidOperationException(); ValueTask t = mode == CtorMode.Task ? new ValueTask(Task.FromException(e)) : new ValueTask(ManualResetValueTaskSourceFactory.Completed<int>(0, e), 0); Assert.True(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.True(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.GetAwaiter().GetResult())); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void Generic_CreateFromFaulted_IsFaulted(CtorMode mode) { InvalidOperationException e = new InvalidOperationException(); ValueTask<int> t = mode == CtorMode.Task ? new ValueTask<int>(Task.FromException<int>(e)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed<int>(0, e), 0); Assert.True(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.True(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.Result)); Assert.Same(e, Assert.Throws<InvalidOperationException>(() => t.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_CreateFromNullTask_Throws() { AssertExtensions.Throws<ArgumentNullException>("task", () => new ValueTask((Task)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => new ValueTask((IValueTaskSource)null, 0)); } [Fact] public void Generic_CreateFromNullTask_Throws() { AssertExtensions.Throws<ArgumentNullException>("task", () => new ValueTask<int>((Task<int>)null)); AssertExtensions.Throws<ArgumentNullException>("task", () => new ValueTask<string>((Task<string>)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => new ValueTask<int>((IValueTaskSource<int>)null, 0)); AssertExtensions.Throws<ArgumentNullException>("source", () => new ValueTask<string>((IValueTaskSource<string>)null, 0)); } [Fact] public void NonGeneric_CreateFromTask_AsTaskIdempotent() { Task source = Task.FromResult(42); var t = new ValueTask(source); Assert.Same(source, t.AsTask()); Assert.Same(t.AsTask(), t.AsTask()); } [Fact] public void Generic_CreateFromTask_AsTaskIdempotent() { Task<int> source = Task.FromResult(42); var t = new ValueTask<int>(source); Assert.Same(source, t.AsTask()); Assert.Same(t.AsTask(), t.AsTask()); } [Fact] public void NonGeneric_CreateFromDefault_AsTaskIdempotent() { var t = new ValueTask(); Assert.Same(t.AsTask(), t.AsTask()); } [Fact] public void Generic_CreateFromValue_AsTaskNotIdempotent() { var t = new ValueTask<int>(42); Assert.NotSame(Task.FromResult(42), t.AsTask()); Assert.NotSame(t.AsTask(), t.AsTask()); } [Fact] public void NonGeneric_CreateFromValueTaskSource_AsTaskIdempotent() // validates unsupported behavior specific to the backing IValueTaskSource { var vt = new ValueTask(ManualResetValueTaskSourceFactory.Completed<int>(42, null), 0); Task t = vt.AsTask(); Assert.NotNull(t); Assert.Same(t, vt.AsTask()); Assert.Same(Task.CompletedTask, vt.AsTask()); } [Fact] public void Generic_CreateFromValueTaskSource_AsTaskNotIdempotent() // validates unsupported behavior specific to the backing IValueTaskSource { var t = new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed<int>(42, null), 0); Assert.NotSame(Task.FromResult(42), t.AsTask()); Assert.NotSame(t.AsTask(), t.AsTask()); } [Theory] [InlineData(false)] [InlineData(true)] public async Task NonGeneric_CreateFromValueTaskSource_Success(bool sync) { var vt = new ValueTask(sync ? ManualResetValueTaskSourceFactory.Completed(0) : ManualResetValueTaskSourceFactory.Delay(1, 0), 0); Task t = vt.AsTask(); if (sync) { Assert.True(t.Status == TaskStatus.RanToCompletion); } await t; } [Theory] [InlineData(false)] [InlineData(true)] public async Task Generic_CreateFromValueTaskSource_Success(bool sync) { var vt = new ValueTask<int>(sync ? ManualResetValueTaskSourceFactory.Completed(42) : ManualResetValueTaskSourceFactory.Delay(1, 42), 0); Task<int> t = vt.AsTask(); if (sync) { Assert.True(t.Status == TaskStatus.RanToCompletion); } Assert.Equal(42, await t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task NonGeneric_CreateFromValueTaskSource_Faulted(bool sync) { var vt = new ValueTask(sync ? ManualResetValueTaskSourceFactory.Completed(0, new FormatException()) : ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0); Task t = vt.AsTask(); if (sync) { Assert.True(t.IsFaulted); Assert.IsType<FormatException>(t.Exception.InnerException); } else { await Assert.ThrowsAsync<FormatException>(() => t); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task Generic_CreateFromValueTaskSource_Faulted(bool sync) { var vt = new ValueTask<int>(sync ? ManualResetValueTaskSourceFactory.Completed(0, new FormatException()) : ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0); Task<int> t = vt.AsTask(); if (sync) { Assert.True(t.IsFaulted); Assert.IsType<FormatException>(t.Exception.InnerException); } else { await Assert.ThrowsAsync<FormatException>(() => t); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task NonGeneric_CreateFromValueTaskSource_Canceled(bool sync) { var vt = new ValueTask(sync ? ManualResetValueTaskSourceFactory.Completed(0, new OperationCanceledException()) : ManualResetValueTaskSourceFactory.Delay(1, 0, new OperationCanceledException()), 0); Task t = vt.AsTask(); if (sync) { Assert.True(t.IsCanceled); } else { await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t); Assert.True(t.IsCanceled); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task Generic_CreateFromValueTaskSource_Canceled(bool sync) { var vt = new ValueTask<int>(sync ? ManualResetValueTaskSourceFactory.Completed(0, new OperationCanceledException()) : ManualResetValueTaskSourceFactory.Delay(1, 0, new OperationCanceledException()), 0); Task<int> t = vt.AsTask(); if (sync) { Assert.True(t.IsCanceled); } else { await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t); Assert.True(t.IsCanceled); } } [Fact] public void NonGeneric_Preserve_FromResult_NoChanges() { ValueTask vt1 = default; ValueTask vt2 = vt1.Preserve(); Assert.True(vt1 == vt2); } [Fact] public void NonGeneric_Preserve_FromTask_EqualityMaintained() { ValueTask vt1 = new ValueTask(Task.FromResult(42)); ValueTask vt2 = vt1.Preserve(); Assert.True(vt1 == vt2); } [Fact] public void NonGeneric_Preserve_FromValueTaskSource_TransitionedToTask() { ValueTask vt1 = new ValueTask(ManualResetValueTaskSourceFactory.Completed(42), 0); ValueTask vt2 = vt1.Preserve(); ValueTask vt3 = vt2.Preserve(); Assert.True(vt1 != vt2); Assert.True(vt2 == vt3); Assert.Same(vt2.AsTask(), vt2.AsTask()); } [Fact] public void Generic_Preserve_FromResult_EqualityMaintained() { ValueTask<int> vt1 = new ValueTask<int>(42); ValueTask<int> vt2 = vt1.Preserve(); Assert.True(vt1 == vt2); } [Fact] public void Generic_Preserve_FromTask_EqualityMaintained() { ValueTask<int> vt1 = new ValueTask<int>(Task.FromResult(42)); ValueTask<int> vt2 = vt1.Preserve(); Assert.True(vt1 == vt2); } [Fact] public void Generic_Preserve_FromValueTaskSource_TransitionedToTask() { ValueTask<int> vt1 = new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42), 0); ValueTask<int> vt2 = vt1.Preserve(); ValueTask<int> vt3 = vt2.Preserve(); Assert.True(vt1 != vt2); Assert.True(vt2 == vt3); Assert.Same(vt2.AsTask(), vt2.AsTask()); } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task NonGeneric_CreateFromCompleted_Await(CtorMode mode) { ValueTask Create() => mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.FromResult(42)) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); int thread = Environment.CurrentManagedThreadId; await Create(); Assert.Equal(thread, Environment.CurrentManagedThreadId); await Create().ConfigureAwait(false); Assert.Equal(thread, Environment.CurrentManagedThreadId); await Create().ConfigureAwait(true); Assert.Equal(thread, Environment.CurrentManagedThreadId); } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task Generic_CreateFromCompleted_Await(CtorMode mode) { ValueTask<int> Create() => mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); int thread = Environment.CurrentManagedThreadId; Assert.Equal(42, await Create()); Assert.Equal(thread, Environment.CurrentManagedThreadId); Assert.Equal(42, await Create().ConfigureAwait(false)); Assert.Equal(thread, Environment.CurrentManagedThreadId); Assert.Equal(42, await Create().ConfigureAwait(true)); Assert.Equal(thread, Environment.CurrentManagedThreadId); } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] public async Task NonGeneric_CreateFromTask_Await_Normal(bool? continueOnCapturedContext) { var t = new ValueTask(Task.Delay(1)); switch (continueOnCapturedContext) { case null: await t; break; default: await t.ConfigureAwait(continueOnCapturedContext.Value); break; } } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] public async Task Generic_CreateFromTask_Await_Normal(bool? continueOnCapturedContext) { var t = new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42)); switch (continueOnCapturedContext) { case null: Assert.Equal(42, await t); break; default: Assert.Equal(42, await t.ConfigureAwait(continueOnCapturedContext.Value)); break; } } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] public async Task CreateFromValueTaskSource_Await_Normal(bool? continueOnCapturedContext) { var mre = new ManualResetValueTaskSource<int>(); var t = new ValueTask(mre, 0); var ignored = Task.Delay(1).ContinueWith(_ => mre.SetResult(42)); switch (continueOnCapturedContext) { case null: await t; break; default: await t.ConfigureAwait(continueOnCapturedContext.Value); break; } } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] public async Task Generic_CreateFromValueTaskSource_Await_Normal(bool? continueOnCapturedContext) { var mre = new ManualResetValueTaskSource<int>(); var t = new ValueTask<int>(mre, 0); var ignored = Task.Delay(1).ContinueWith(_ => mre.SetResult(42)); switch (continueOnCapturedContext) { case null: Assert.Equal(42, await t); break; default: Assert.Equal(42, await t.ConfigureAwait(continueOnCapturedContext.Value)); break; } } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task NonGeneric_Awaiter_OnCompleted(CtorMode mode) { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task NonGeneric_Awaiter_UnsafeOnCompleted(CtorMode mode) { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().UnsafeOnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task Generic_Awaiter_OnCompleted(CtorMode mode) { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task Generic_Awaiter_UnsafeOnCompleted(CtorMode mode) { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().UnsafeOnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result, true)] [InlineData(CtorMode.Task, true)] [InlineData(CtorMode.ValueTaskSource, true)] [InlineData(CtorMode.Result, false)] [InlineData(CtorMode.Task, false)] [InlineData(CtorMode.ValueTaskSource, false)] public async Task NonGeneric_ConfiguredAwaiter_OnCompleted(CtorMode mode, bool continueOnCapturedContext) { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result, true)] [InlineData(CtorMode.Task, true)] [InlineData(CtorMode.ValueTaskSource, true)] [InlineData(CtorMode.Result, false)] [InlineData(CtorMode.Task, false)] [InlineData(CtorMode.ValueTaskSource, false)] public async Task NonGeneric_ConfiguredAwaiter_UnsafeOnCompleted(CtorMode mode, bool continueOnCapturedContext) { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result, true)] [InlineData(CtorMode.Task, true)] [InlineData(CtorMode.ValueTaskSource, true)] [InlineData(CtorMode.Result, false)] [InlineData(CtorMode.Task, false)] [InlineData(CtorMode.ValueTaskSource, false)] public async Task Generic_ConfiguredAwaiter_OnCompleted(CtorMode mode, bool continueOnCapturedContext) { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result, true)] [InlineData(CtorMode.Task, true)] [InlineData(CtorMode.ValueTaskSource, true)] [InlineData(CtorMode.Result, false)] [InlineData(CtorMode.Task, false)] [InlineData(CtorMode.ValueTaskSource, false)] public async Task Generic_ConfiguredAwaiter_UnsafeOnCompleted(CtorMode mode, bool continueOnCapturedContext) { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(Task.FromResult(42)) : new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(CtorMode.Result)] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public async Task NonGeneric_Awaiter_ContinuesOnCapturedContext(CtorMode mode) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(Task.CompletedTask) : new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, null), 0); var mres = new ManualResetEventSlim(); t.GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(1, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Theory] [InlineData(CtorMode.Task, false)] [InlineData(CtorMode.ValueTaskSource, false)] [InlineData(CtorMode.Result, true)] [InlineData(CtorMode.Task, true)] [InlineData(CtorMode.ValueTaskSource, true)] public async Task Generic_Awaiter_ContinuesOnCapturedContext(CtorMode mode, bool sync) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(sync ? Task.FromResult(42) : Task.Delay(1).ContinueWith(_ => 42)) : new ValueTask<int>(sync ? ManualResetValueTaskSourceFactory.Completed(42, null) : ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0); var mres = new ManualResetEventSlim(); t.GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(1, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Theory] [InlineData(CtorMode.Task, true, false)] [InlineData(CtorMode.ValueTaskSource, true, false)] [InlineData(CtorMode.Task, false, false)] [InlineData(CtorMode.ValueTaskSource, false, false)] [InlineData(CtorMode.Result, true, true)] [InlineData(CtorMode.Task, true, true)] [InlineData(CtorMode.ValueTaskSource, true, true)] [InlineData(CtorMode.Result, false, true)] [InlineData(CtorMode.Task, false, true)] [InlineData(CtorMode.ValueTaskSource, false, true)] public async Task NonGeneric_ConfiguredAwaiter_ContinuesOnCapturedContext(CtorMode mode, bool continueOnCapturedContext, bool sync) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask t = mode == CtorMode.Result ? new ValueTask() : mode == CtorMode.Task ? new ValueTask(sync ? Task.CompletedTask : Task.Delay(1)) : new ValueTask(sync ? ManualResetValueTaskSourceFactory.Completed(0, null) : ManualResetValueTaskSourceFactory.Delay(42, 0, null), 0); var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Theory] [InlineData(CtorMode.Task, true, false)] [InlineData(CtorMode.ValueTaskSource, true, false)] [InlineData(CtorMode.Task, false, false)] [InlineData(CtorMode.ValueTaskSource, false, false)] [InlineData(CtorMode.Result, true, true)] [InlineData(CtorMode.Task, true, true)] [InlineData(CtorMode.ValueTaskSource, true, true)] [InlineData(CtorMode.Result, false, true)] [InlineData(CtorMode.Task, false, true)] [InlineData(CtorMode.ValueTaskSource, false, true)] public async Task Generic_ConfiguredAwaiter_ContinuesOnCapturedContext(CtorMode mode, bool continueOnCapturedContext, bool sync) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = mode == CtorMode.Result ? new ValueTask<int>(42) : mode == CtorMode.Task ? new ValueTask<int>(sync ? Task.FromResult(42) : Task.Delay(1).ContinueWith(_ => 42)) : new ValueTask<int>(sync ? ManualResetValueTaskSourceFactory.Completed(42, null) : ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0); var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Fact] public void NonGeneric_GetHashCode_FromDefault_0() { Assert.Equal(0, new ValueTask().GetHashCode()); } [Fact] public void Generic_GetHashCode_FromResult_ContainsResult() { var vt = new ValueTask<int>(42); Assert.Equal(vt.Result.GetHashCode(), vt.GetHashCode()); var rt = new ValueTask<string>((string)null); Assert.Equal(0, rt.GetHashCode()); rt = new ValueTask<string>("12345"); Assert.Equal(rt.Result.GetHashCode(), rt.GetHashCode()); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void NonGeneric_GetHashCode_FromObject_MatchesObjectHashCode(CtorMode mode) { object obj; ValueTask vt; if (mode == CtorMode.Task) { Task t = Task.CompletedTask; vt = new ValueTask(t); obj = t; } else { var t = ManualResetValueTaskSourceFactory.Completed(42, null); vt = new ValueTask(t, 0); obj = t; } Assert.Equal(obj.GetHashCode(), vt.GetHashCode()); } [Theory] [InlineData(CtorMode.Task)] [InlineData(CtorMode.ValueTaskSource)] public void Generic_GetHashCode_FromObject_MatchesObjectHashCode(CtorMode mode) { object obj; ValueTask<int> vt; if (mode == CtorMode.Task) { Task<int> t = Task.FromResult(42); vt = new ValueTask<int>(t); obj = t; } else { ManualResetValueTaskSource<int> t = ManualResetValueTaskSourceFactory.Completed(42, null); vt = new ValueTask<int>(t, 0); obj = t; } Assert.Equal(obj.GetHashCode(), vt.GetHashCode()); } [Fact] public void NonGeneric_OperatorEquals() { var completedTcs = new TaskCompletionSource<int>(); completedTcs.SetResult(42); var completedVts = ManualResetValueTaskSourceFactory.Completed(42, null); Assert.True(new ValueTask() == new ValueTask()); Assert.True(new ValueTask(Task.CompletedTask) == new ValueTask(Task.CompletedTask)); Assert.True(new ValueTask(completedTcs.Task) == new ValueTask(completedTcs.Task)); Assert.True(new ValueTask(completedVts, 0) == new ValueTask(completedVts, 0)); Assert.False(new ValueTask(Task.CompletedTask) == new ValueTask(completedTcs.Task)); Assert.False(new ValueTask(Task.CompletedTask) == new ValueTask(completedVts, 0)); Assert.False(new ValueTask(completedTcs.Task) == new ValueTask(completedVts, 0)); Assert.False(new ValueTask(completedVts, 17) == new ValueTask(completedVts, 18)); } [Fact] public void Generic_OperatorEquals() { var completedTask = Task.FromResult(42); var completedVts = ManualResetValueTaskSourceFactory.Completed(42, null); Assert.True(new ValueTask<int>(42) == new ValueTask<int>(42)); Assert.True(new ValueTask<int>(completedTask) == new ValueTask<int>(completedTask)); Assert.True(new ValueTask<int>(completedVts, 17) == new ValueTask<int>(completedVts, 17)); Assert.True(new ValueTask<string>("42") == new ValueTask<string>("42")); Assert.True(new ValueTask<string>((string)null) == new ValueTask<string>((string)null)); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(43)); Assert.False(new ValueTask<string>("42") == new ValueTask<string>((string)null)); Assert.False(new ValueTask<string>((string)null) == new ValueTask<string>("42")); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(Task.FromResult(42))); Assert.False(new ValueTask<int>(Task.FromResult(42)) == new ValueTask<int>(42)); Assert.False(new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0) == new ValueTask<int>(42)); Assert.False(new ValueTask<int>(completedTask) == new ValueTask<int>(completedVts, 0)); Assert.False(new ValueTask<int>(completedVts, 17) == new ValueTask<int>(completedVts, 18)); } [Fact] public void NonGeneric_OperatorNotEquals() { var completedTcs = new TaskCompletionSource<int>(); completedTcs.SetResult(42); var completedVts = ManualResetValueTaskSourceFactory.Completed(42, null); Assert.False(new ValueTask() != new ValueTask()); Assert.False(new ValueTask(Task.CompletedTask) != new ValueTask(Task.CompletedTask)); Assert.False(new ValueTask(completedTcs.Task) != new ValueTask(completedTcs.Task)); Assert.False(new ValueTask(completedVts, 0) != new ValueTask(completedVts, 0)); Assert.True(new ValueTask(Task.CompletedTask) != new ValueTask(completedTcs.Task)); Assert.True(new ValueTask(Task.CompletedTask) != new ValueTask(completedVts, 0)); Assert.True(new ValueTask(completedTcs.Task) != new ValueTask(completedVts, 0)); Assert.True(new ValueTask(completedVts, 17) != new ValueTask(completedVts, 18)); } [Fact] public void Generic_OperatorNotEquals() { var completedTask = Task.FromResult(42); var completedVts = ManualResetValueTaskSourceFactory.Completed(42, null); Assert.False(new ValueTask<int>(42) != new ValueTask<int>(42)); Assert.False(new ValueTask<int>(completedTask) != new ValueTask<int>(completedTask)); Assert.False(new ValueTask<int>(completedVts, 0) != new ValueTask<int>(completedVts, 0)); Assert.False(new ValueTask<string>("42") != new ValueTask<string>("42")); Assert.False(new ValueTask<string>((string)null) != new ValueTask<string>((string)null)); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(43)); Assert.True(new ValueTask<string>("42") != new ValueTask<string>((string)null)); Assert.True(new ValueTask<string>((string)null) != new ValueTask<string>("42")); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(Task.FromResult(42))); Assert.True(new ValueTask<int>(Task.FromResult(42)) != new ValueTask<int>(42)); Assert.True(new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0) != new ValueTask<int>(42)); Assert.True(new ValueTask<int>(completedTask) != new ValueTask<int>(completedVts, 0)); Assert.True(new ValueTask<int>(completedVts, 17) != new ValueTask<int>(completedVts, 18)); } [Fact] public void NonGeneric_Equals_ValueTask() { Assert.True(new ValueTask().Equals(new ValueTask())); Assert.False(new ValueTask().Equals(new ValueTask(Task.CompletedTask))); Assert.False(new ValueTask(Task.CompletedTask).Equals(new ValueTask())); Assert.False(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals(new ValueTask())); Assert.False(new ValueTask().Equals(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0))); Assert.False(new ValueTask(Task.CompletedTask).Equals(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0))); Assert.False(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals(new ValueTask(Task.CompletedTask))); } [Fact] public void Generic_Equals_ValueTask() { Assert.True(new ValueTask<int>(42).Equals(new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals(new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals(new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals(new ValueTask<int>(42))); Assert.False(new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals(new ValueTask<int>(42))); } [Fact] public void NonGeneric_Equals_Object() { Assert.True(new ValueTask().Equals((object)new ValueTask())); Assert.False(new ValueTask().Equals((object)new ValueTask(Task.CompletedTask))); Assert.False(new ValueTask(Task.CompletedTask).Equals((object)new ValueTask())); Assert.False(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals((object)new ValueTask())); Assert.False(new ValueTask().Equals((object)new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0))); Assert.False(new ValueTask(Task.CompletedTask).Equals((object)new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0))); Assert.False(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals((object)new ValueTask(Task.CompletedTask))); Assert.False(new ValueTask().Equals(null)); Assert.False(new ValueTask().Equals("12345")); Assert.False(new ValueTask(Task.CompletedTask).Equals("12345")); Assert.False(new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals("12345")); } [Fact] public void Generic_Equals_Object() { Assert.True(new ValueTask<int>(42).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals((object)new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)null)); Assert.False(new ValueTask<int>(42).Equals(new object())); Assert.False(new ValueTask<int>(42).Equals((object)42)); } [Fact] public void NonGeneric_ToString_Success() { Assert.Equal("System.Threading.Tasks.ValueTask", new ValueTask().ToString()); Assert.Equal("System.Threading.Tasks.ValueTask", new ValueTask(Task.CompletedTask).ToString()); Assert.Equal("System.Threading.Tasks.ValueTask", new ValueTask(ManualResetValueTaskSourceFactory.Completed(42, null), 0).ToString()); } [Fact] public void Generic_ToString_Success() { Assert.Equal("Hello", new ValueTask<string>("Hello").ToString()); Assert.Equal("Hello", new ValueTask<string>(Task.FromResult("Hello")).ToString()); Assert.Equal("Hello", new ValueTask<string>(ManualResetValueTaskSourceFactory.Completed("Hello", null), 0).ToString()); Assert.Equal("42", new ValueTask<int>(42).ToString()); Assert.Equal("42", new ValueTask<int>(Task.FromResult(42)).ToString()); Assert.Equal("42", new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0).ToString()); Assert.Same(string.Empty, new ValueTask<string>(string.Empty).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult(string.Empty)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(ManualResetValueTaskSourceFactory.Completed(string.Empty, null), 0).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new InvalidOperationException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new OperationCanceledException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(ManualResetValueTaskSourceFactory.Completed<string>(null, new InvalidOperationException()), 0).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromCanceled<string>(new CancellationToken(true))).ToString()); Assert.Equal("0", default(ValueTask<int>).ToString()); Assert.Same(string.Empty, default(ValueTask<string>).ToString()); Assert.Same(string.Empty, new ValueTask<string>((string)null).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult<string>(null)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(ManualResetValueTaskSourceFactory.Completed<string>(null, null), 0).ToString()); Assert.Same(string.Empty, new ValueTask<DateTime>(new TaskCompletionSource<DateTime>().Task).ToString()); } [Theory] [InlineData(typeof(ValueTask))] public void NonGeneric_AsyncMethodBuilderAttribute_ValueTaskAttributed(Type valueTaskType) { CustomAttributeData cad = valueTaskType.GetTypeInfo().CustomAttributes.Single(attr => attr.AttributeType == typeof(AsyncMethodBuilderAttribute)); Type builderTypeCtorArg = (Type)cad.ConstructorArguments[0].Value; Assert.Equal(typeof(AsyncValueTaskMethodBuilder), builderTypeCtorArg); AsyncMethodBuilderAttribute amba = valueTaskType.GetTypeInfo().GetCustomAttribute<AsyncMethodBuilderAttribute>(); Assert.Equal(builderTypeCtorArg, amba.BuilderType); } [Theory] [InlineData(typeof(ValueTask<>))] [InlineData(typeof(ValueTask<int>))] [InlineData(typeof(ValueTask<string>))] public void Generic_AsyncMethodBuilderAttribute_ValueTaskAttributed(Type valueTaskType) { CustomAttributeData cad = valueTaskType.GetTypeInfo().CustomAttributes.Single(attr => attr.AttributeType == typeof(AsyncMethodBuilderAttribute)); Type builderTypeCtorArg = (Type)cad.ConstructorArguments[0].Value; Assert.Equal(typeof(AsyncValueTaskMethodBuilder<>), builderTypeCtorArg); AsyncMethodBuilderAttribute amba = valueTaskType.GetTypeInfo().GetCustomAttribute<AsyncMethodBuilderAttribute>(); Assert.Equal(builderTypeCtorArg, amba.BuilderType); } [Fact] public void NonGeneric_AsTask_ValueTaskSourcePassesInvalidStateToOnCompleted_Throws() { void Validate(IValueTaskSource vts) { var vt = new ValueTask(vts, 0); Assert.Throws<ArgumentOutOfRangeException>(() => { vt.AsTask(); }); } Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(null) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(new object()) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => { continuation(state); continuation(state); } }); } [Fact] public void Generic_AsTask_ValueTaskSourcePassesInvalidStateToOnCompleted_Throws() { void Validate(IValueTaskSource<int> vts) { var vt = new ValueTask<int>(vts, 0); Assert.Throws<ArgumentOutOfRangeException>(() => { vt.AsTask(); }); } Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(null) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(new object()) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => { continuation(state); continuation(state); } }); } [Fact] public void NonGeneric_OnCompleted_ValueTaskSourcePassesInvalidStateToOnCompleted_Throws() { void Validate(IValueTaskSource vts) { var vt = new ValueTask(vts, 0); Assert.Throws<ArgumentOutOfRangeException>(() => vt.GetAwaiter().OnCompleted(() => { })); Assert.Throws<ArgumentOutOfRangeException>(() => vt.GetAwaiter().UnsafeOnCompleted(() => { })); foreach (bool continueOnCapturedContext in new[] { true, false }) { Assert.Throws<ArgumentOutOfRangeException>(() => vt.ConfigureAwait(false).GetAwaiter().OnCompleted(() => { })); Assert.Throws<ArgumentOutOfRangeException>(() => vt.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => { })); } } Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(null) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(new object()) }); } [Fact] public void Generic_OnCompleted_ValueTaskSourcePassesInvalidStateToOnCompleted_Throws() { void Validate(IValueTaskSource<int> vts) { var vt = new ValueTask<int>(vts, 0); Assert.Throws<ArgumentOutOfRangeException>(() => vt.GetAwaiter().OnCompleted(() => { })); Assert.Throws<ArgumentOutOfRangeException>(() => vt.GetAwaiter().UnsafeOnCompleted(() => { })); foreach (bool continueOnCapturedContext in new[] { true, false }) { Assert.Throws<ArgumentOutOfRangeException>(() => vt.ConfigureAwait(false).GetAwaiter().OnCompleted(() => { })); Assert.Throws<ArgumentOutOfRangeException>(() => vt.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => { })); } } Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(null) }); Validate(new DelegateValueTaskSource<int> { OnCompletedFunc = (continuation, state, token, flags) => continuation(new object()) }); } [Fact] public void NonGeneric_TornRead_DoesNotCrashOrHang() { // Validate that if we incur a torn read, we may get an exception, but we won't crash or hang. object vtBoxed; // _obj is null but other fields are from Task construction vtBoxed = new ValueTask(Task.CompletedTask); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, null); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); // _obj is a Task but other fields are from result construction vtBoxed = new ValueTask(); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, Task.CompletedTask); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); // _obj is an IValueTaskSource but other fields are from Task construction vtBoxed = new ValueTask(Task.CompletedTask); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, ManualResetValueTaskSourceFactory.Completed(42)); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); } [Fact] public void Generic_TornRead_DoesNotCrashOrHang() { // Validate that if we incur a torn read, we may get an exception, but we won't crash or hang. object vtBoxed; // _obj is null but other fields are from Task construction vtBoxed = new ValueTask<int>(Task.FromResult(42)); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, null); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); // _obj is a Task but other fields are from result construction vtBoxed = new ValueTask<int>(42); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, Task.FromResult(42)); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); // _obj is an IValueTaskSource but other fields are from Task construction vtBoxed = new ValueTask<int>(Task.FromResult(42)); vtBoxed.GetType().GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(vtBoxed, ManualResetValueTaskSourceFactory.Completed(42)); Record.Exception(() => { bool completed = ((ValueTask)vtBoxed).IsCompleted; ((ValueTask)vtBoxed).GetAwaiter().GetResult(); }); } private sealed class DelegateValueTaskSource<T> : IValueTaskSource, IValueTaskSource<T> { public Func<short, ValueTaskSourceStatus> GetStatusFunc = null; public Action<short> GetResultAction = null; public Func<short, T> GetResultFunc = null; public Action<Action<object>, object, short, ValueTaskSourceOnCompletedFlags> OnCompletedFunc; public ValueTaskSourceStatus GetStatus(short token) => GetStatusFunc?.Invoke(token) ?? ValueTaskSourceStatus.Pending; public void GetResult(short token) => GetResultAction?.Invoke(token); T IValueTaskSource<T>.GetResult(short token) => GetResultFunc != null ? GetResultFunc(token) : default; public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => OnCompletedFunc?.Invoke(continuation, state, token, flags); } private sealed class TrackingSynchronizationContext : SynchronizationContext { internal int Posts { get; set; } public override void Post(SendOrPostCallback d, object state) { Posts++; base.Post(d, state); } } } }
using System; using Microsoft.SPOT; namespace IngenuityMicro.Radius.Fonts { public class DefautFont { public static byte[] Font = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, 0x18, 0x3C, 0x7E, 0x3C, 0x18, 0x1C, 0x57, 0x7D, 0x57, 0x1C, 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, 0x00, 0x18, 0x3C, 0x18, 0x00, 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, 0x00, 0x18, 0x24, 0x18, 0x00, 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, 0x30, 0x48, 0x3A, 0x06, 0x0E, 0x26, 0x29, 0x79, 0x29, 0x26, 0x40, 0x7F, 0x05, 0x05, 0x07, 0x40, 0x7F, 0x05, 0x25, 0x3F, 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, 0x7F, 0x3E, 0x1C, 0x1C, 0x08, 0x08, 0x1C, 0x1C, 0x3E, 0x7F, 0x14, 0x22, 0x7F, 0x22, 0x14, 0x5F, 0x5F, 0x00, 0x5F, 0x5F, 0x06, 0x09, 0x7F, 0x01, 0x7F, 0x00, 0x66, 0x89, 0x95, 0x6A, 0x60, 0x60, 0x60, 0x60, 0x60, 0x94, 0xA2, 0xFF, 0xA2, 0x94, 0x08, 0x04, 0x7E, 0x04, 0x08, 0x10, 0x20, 0x7E, 0x20, 0x10, 0x08, 0x08, 0x2A, 0x1C, 0x08, 0x08, 0x1C, 0x2A, 0x08, 0x08, 0x1E, 0x10, 0x10, 0x10, 0x10, 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, 0x30, 0x38, 0x3E, 0x38, 0x30, 0x06, 0x0E, 0x3E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x14, 0x7F, 0x14, 0x7F, 0x14, 0x24, 0x2A, 0x7F, 0x2A, 0x12, 0x23, 0x13, 0x08, 0x64, 0x62, 0x36, 0x49, 0x56, 0x20, 0x50, 0x00, 0x08, 0x07, 0x03, 0x00, 0x00, 0x1C, 0x22, 0x41, 0x00, 0x00, 0x41, 0x22, 0x1C, 0x00, 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x80, 0x70, 0x30, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x60, 0x60, 0x00, 0x20, 0x10, 0x08, 0x04, 0x02, 0x3E, 0x51, 0x49, 0x45, 0x3E, 0x00, 0x42, 0x7F, 0x40, 0x00, 0x72, 0x49, 0x49, 0x49, 0x46, 0x21, 0x41, 0x49, 0x4D, 0x33, 0x18, 0x14, 0x12, 0x7F, 0x10, 0x27, 0x45, 0x45, 0x45, 0x39, 0x3C, 0x4A, 0x49, 0x49, 0x31, 0x41, 0x21, 0x11, 0x09, 0x07, 0x36, 0x49, 0x49, 0x49, 0x36, 0x46, 0x49, 0x49, 0x29, 0x1E, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x40, 0x34, 0x00, 0x00, 0x00, 0x08, 0x14, 0x22, 0x41, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x41, 0x22, 0x14, 0x08, 0x02, 0x01, 0x59, 0x09, 0x06, 0x3E, 0x41, 0x5D, 0x59, 0x4E, 0x7C, 0x12, 0x11, 0x12, 0x7C, 0x7F, 0x49, 0x49, 0x49, 0x36, 0x3E, 0x41, 0x41, 0x41, 0x22, 0x7F, 0x41, 0x41, 0x41, 0x3E, 0x7F, 0x49, 0x49, 0x49, 0x41, 0x7F, 0x09, 0x09, 0x09, 0x01, 0x3E, 0x41, 0x41, 0x51, 0x73, 0x7F, 0x08, 0x08, 0x08, 0x7F, 0x00, 0x41, 0x7F, 0x41, 0x00, 0x20, 0x40, 0x41, 0x3F, 0x01, 0x7F, 0x08, 0x14, 0x22, 0x41, 0x7F, 0x40, 0x40, 0x40, 0x40, 0x7F, 0x02, 0x1C, 0x02, 0x7F, 0x7F, 0x04, 0x08, 0x10, 0x7F, 0x3E, 0x41, 0x41, 0x41, 0x3E, 0x7F, 0x09, 0x09, 0x09, 0x06, 0x3E, 0x41, 0x51, 0x21, 0x5E, 0x7F, 0x09, 0x19, 0x29, 0x46, 0x26, 0x49, 0x49, 0x49, 0x32, 0x03, 0x01, 0x7F, 0x01, 0x03, 0x3F, 0x40, 0x40, 0x40, 0x3F, 0x1F, 0x20, 0x40, 0x20, 0x1F, 0x3F, 0x40, 0x38, 0x40, 0x3F, 0x63, 0x14, 0x08, 0x14, 0x63, 0x03, 0x04, 0x78, 0x04, 0x03, 0x61, 0x59, 0x49, 0x4D, 0x43, 0x00, 0x7F, 0x41, 0x41, 0x41, 0x02, 0x04, 0x08, 0x10, 0x20, 0x00, 0x41, 0x41, 0x41, 0x7F, 0x04, 0x02, 0x01, 0x02, 0x04, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0x03, 0x07, 0x08, 0x00, 0x20, 0x54, 0x54, 0x78, 0x40, 0x7F, 0x28, 0x44, 0x44, 0x38, 0x38, 0x44, 0x44, 0x44, 0x28, 0x38, 0x44, 0x44, 0x28, 0x7F, 0x38, 0x54, 0x54, 0x54, 0x18, 0x00, 0x08, 0x7E, 0x09, 0x02, 0x18, 0xA4, 0xA4, 0x9C, 0x78, 0x7F, 0x08, 0x04, 0x04, 0x78, 0x00, 0x44, 0x7D, 0x40, 0x00, 0x20, 0x40, 0x40, 0x3D, 0x00, 0x7F, 0x10, 0x28, 0x44, 0x00, 0x00, 0x41, 0x7F, 0x40, 0x00, 0x7C, 0x04, 0x78, 0x04, 0x78, 0x7C, 0x08, 0x04, 0x04, 0x78, 0x38, 0x44, 0x44, 0x44, 0x38, 0xFC, 0x18, 0x24, 0x24, 0x18, 0x18, 0x24, 0x24, 0x18, 0xFC, 0x7C, 0x08, 0x04, 0x04, 0x08, 0x48, 0x54, 0x54, 0x54, 0x24, 0x04, 0x04, 0x3F, 0x44, 0x24, 0x3C, 0x40, 0x40, 0x20, 0x7C, 0x1C, 0x20, 0x40, 0x20, 0x1C, 0x3C, 0x40, 0x30, 0x40, 0x3C, 0x44, 0x28, 0x10, 0x28, 0x44, 0x4C, 0x90, 0x90, 0x90, 0x7C, 0x44, 0x64, 0x54, 0x4C, 0x44, 0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x36, 0x08, 0x00, 0x02, 0x01, 0x02, 0x04, 0x02, 0x3C, 0x26, 0x23, 0x26, 0x3C, 0x1E, 0xA1, 0xA1, 0x61, 0x12, 0x3A, 0x40, 0x40, 0x20, 0x7A, 0x38, 0x54, 0x54, 0x55, 0x59, 0x21, 0x55, 0x55, 0x79, 0x41, 0x21, 0x54, 0x54, 0x78, 0x41, 0x21, 0x55, 0x54, 0x78, 0x40, 0x20, 0x54, 0x55, 0x79, 0x40, 0x0C, 0x1E, 0x52, 0x72, 0x12, 0x39, 0x55, 0x55, 0x55, 0x59, 0x39, 0x54, 0x54, 0x54, 0x59, 0x39, 0x55, 0x54, 0x54, 0x58, 0x00, 0x00, 0x45, 0x7C, 0x41, 0x00, 0x02, 0x45, 0x7D, 0x42, 0x00, 0x01, 0x45, 0x7C, 0x40, 0xF0, 0x29, 0x24, 0x29, 0xF0, 0xF0, 0x28, 0x25, 0x28, 0xF0, 0x7C, 0x54, 0x55, 0x45, 0x00, 0x20, 0x54, 0x54, 0x7C, 0x54, 0x7C, 0x0A, 0x09, 0x7F, 0x49, 0x32, 0x49, 0x49, 0x49, 0x32, 0x32, 0x48, 0x48, 0x48, 0x32, 0x32, 0x4A, 0x48, 0x48, 0x30, 0x3A, 0x41, 0x41, 0x21, 0x7A, 0x3A, 0x42, 0x40, 0x20, 0x78, 0x00, 0x9D, 0xA0, 0xA0, 0x7D, 0x39, 0x44, 0x44, 0x44, 0x39, 0x3D, 0x40, 0x40, 0x40, 0x3D, 0x3C, 0x24, 0xFF, 0x24, 0x24, 0x48, 0x7E, 0x49, 0x43, 0x66, 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, 0xFF, 0x09, 0x29, 0xF6, 0x20, 0xC0, 0x88, 0x7E, 0x09, 0x03, 0x20, 0x54, 0x54, 0x79, 0x41, 0x00, 0x00, 0x44, 0x7D, 0x41, 0x4A, 0x7F, 0x73, 0x73, 0x42, 0x4A, 0x7F, 0x49, 0x49, 0x42, 0x00, 0x7A, 0x0A, 0x0A, 0x72, 0x7D, 0x0D, 0x19, 0x31, 0x7D, 0x26, 0x29, 0x29, 0x2F, 0x28, 0x26, 0x29, 0x29, 0x29, 0x26, 0x30, 0x48, 0x4D, 0x40, 0x20, 0x38, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x38, 0x2F, 0x10, 0xC8, 0xAC, 0xBA, 0x2F, 0x10, 0x28, 0x34, 0xFA, 0x00, 0x00, 0x7B, 0x00, 0x00, 0x08, 0x14, 0x2A, 0x14, 0x22, 0x22, 0x14, 0x2A, 0x14, 0x08, 0xAA, 0x00, 0x55, 0x00, 0xAA, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x10, 0x10, 0x10, 0xFF, 0x00, 0x14, 0x14, 0x14, 0xFF, 0x00, 0x10, 0x10, 0xFF, 0x00, 0xFF, 0x10, 0x10, 0xF0, 0x10, 0xF0, 0x14, 0x14, 0x14, 0xFC, 0x00, 0x14, 0x14, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x14, 0x14, 0xF4, 0x04, 0xFC, 0x14, 0x14, 0x17, 0x10, 0x1F, 0x10, 0x10, 0x1F, 0x10, 0x1F, 0x14, 0x14, 0x14, 0x1F, 0x00, 0x10, 0x10, 0x10, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x10, 0x10, 0x10, 0x10, 0x1F, 0x10, 0x10, 0x10, 0x10, 0xF0, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x14, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x1F, 0x10, 0x17, 0x00, 0x00, 0xFC, 0x04, 0xF4, 0x14, 0x14, 0x17, 0x10, 0x17, 0x14, 0x14, 0xF4, 0x04, 0xF4, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xF7, 0x00, 0xF7, 0x14, 0x14, 0x14, 0x17, 0x14, 0x10, 0x10, 0x1F, 0x10, 0x1F, 0x14, 0x14, 0x14, 0xF4, 0x14, 0x10, 0x10, 0xF0, 0x10, 0xF0, 0x00, 0x00, 0x1F, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x1F, 0x14, 0x00, 0x00, 0x00, 0xFC, 0x14, 0x00, 0x00, 0xF0, 0x10, 0xF0, 0x10, 0x10, 0xFF, 0x10, 0xFF, 0x14, 0x14, 0x14, 0xFF, 0x14, 0x10, 0x10, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x38, 0x44, 0x44, 0x38, 0x44, 0x7C, 0x2A, 0x2A, 0x3E, 0x14, 0x7E, 0x02, 0x02, 0x06, 0x06, 0x02, 0x7E, 0x02, 0x7E, 0x02, 0x63, 0x55, 0x49, 0x41, 0x63, 0x38, 0x44, 0x44, 0x3C, 0x04, 0x40, 0x7E, 0x20, 0x1E, 0x20, 0x06, 0x02, 0x7E, 0x02, 0x02, 0x99, 0xA5, 0xE7, 0xA5, 0x99, 0x1C, 0x2A, 0x49, 0x2A, 0x1C, 0x4C, 0x72, 0x01, 0x72, 0x4C, 0x30, 0x4A, 0x4D, 0x4D, 0x30, 0x30, 0x48, 0x78, 0x48, 0x30, 0xBC, 0x62, 0x5A, 0x46, 0x3D, 0x3E, 0x49, 0x49, 0x49, 0x00, 0x7E, 0x01, 0x01, 0x01, 0x7E, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x44, 0x44, 0x5F, 0x44, 0x44, 0x40, 0x51, 0x4A, 0x44, 0x40, 0x40, 0x44, 0x4A, 0x51, 0x40, 0x00, 0x00, 0xFF, 0x01, 0x03, 0xE0, 0x80, 0xFF, 0x00, 0x00, 0x08, 0x08, 0x6B, 0x6B, 0x08, 0x36, 0x12, 0x36, 0x24, 0x36, 0x06, 0x0F, 0x09, 0x0F, 0x06, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x30, 0x40, 0xFF, 0x01, 0x01, 0x00, 0x1F, 0x01, 0x01, 0x1E, 0x00, 0x19, 0x1D, 0x17, 0x12, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00 }; } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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. Note: This code has been heavily modified for the Duality framework. */ #endregion using System; using System.Runtime.InteropServices; namespace Duality { /// <summary> /// Represents a 3D vector using three single-precision floating-point numbers. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IEquatable<Vector3> { /// <summary> /// Defines a unit-length Vector3 that points towards the X-axis. /// </summary> public static readonly Vector3 UnitX = new Vector3(1, 0, 0); /// <summary> /// Defines a unit-length Vector3 that points towards the Y-axis. /// </summary> public static readonly Vector3 UnitY = new Vector3(0, 1, 0); /// <summary> /// /// Defines a unit-length Vector3 that points towards the Z-axis. /// </summary> public static readonly Vector3 UnitZ = new Vector3(0, 0, 1); /// <summary> /// Defines a zero-length Vector3. /// </summary> public static readonly Vector3 Zero = new Vector3(0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector3 One = new Vector3(1, 1, 1); /// <summary> /// The X component of the Vector3. /// </summary> public float X; /// <summary> /// The Y component of the Vector3. /// </summary> public float Y; /// <summary> /// The Z component of the Vector3. /// </summary> public float Z; /// <summary> /// Gets or sets an OpenTK.Vector2 with the X and Y components of this instance. /// </summary> public Vector2 Xy { get { return new Vector2(this.X, this.Y); } set { this.X = value.X; this.Y = value.Y; } } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector3(float value) { this.X = value; this.Y = value; this.Z = value; } /// <summary> /// Constructs a new Vector3. /// </summary> /// <param name="x">The x component of the Vector3.</param> /// <param name="y">The y component of the Vector3.</param> /// <param name="z">The z component of the Vector3.</param> public Vector3(float x, float y, float z) { this.X = x; this.Y = y; this.Z = z; } /// <summary> /// Constructs a new Vector3 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> public Vector3(Vector2 v) { this.X = v.X; this.Y = v.Y; this.Z = 0.0f; } /// <summary> /// Constructs a new Vector3 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> /// <param name="z"></param> public Vector3(Vector2 v, float z) { this.X = v.X; this.Y = v.Y; this.Z = z; } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt( this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <seealso cref="Length"/> public float LengthSquared { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Returns a normalized version of this vector. /// </summary> public Vector3 Normalized { get { float length = this.Length; if (length < 1e-15f) return Vector3.Zero; float scale = 1.0f / length; return new Vector3( this.X * scale, this.Y * scale, this.Z * scale); } } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { switch (index) { case 0: return this.X; case 1: return this.Y; case 2: return this.Z; default: throw new IndexOutOfRangeException("Vector3 access at index: " + index); } } set { switch (index) { case 0: this.X = value; return; case 1: this.Y = value; return; case 2: this.Z = value; return; default: throw new IndexOutOfRangeException("Vector3 access at index: " + index); } } } /// <summary> /// Scales the Vector3 to unit length. /// </summary> public void Normalize() { float length = this.Length; if (length < 1e-15f) { this = Vector3.Zero; } else { float scale = 1.0f / length; this.X *= scale; this.Y *= scale; this.Z *= scale; } } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector3 a, ref Vector3 b, out Vector3 result) { result = new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector3 a, ref Vector3 b, out Vector3 result) { result = new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3 vector, float scale, out Vector3 result) { result = new Vector3(vector.X * scale, vector.Y * scale, vector.Z * scale); } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3 vector, ref Vector3 scale, out Vector3 result) { result = new Vector3(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3 vector, float scale, out Vector3 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3 vector, ref Vector3 scale, out Vector3 result) { result = new Vector3(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z); } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector3 Min(Vector3 a, Vector3 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; a.Z = a.Z < b.Z ? a.Z : b.Z; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector3 a, ref Vector3 b, out Vector3 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector3 Max(Vector3 a, Vector3 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; a.Z = a.Z > b.Z ? a.Z : b.Z; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector3 a, ref Vector3 b, out Vector3 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector3 left, Vector3 right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector3 left, ref Vector3 right, out float result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> public static Vector3 Cross(Vector3 left, Vector3 right) { Vector3 result; Cross(ref left, ref right, out result); return result; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> /// <param name="result">The cross product of the two inputs</param> public static void Cross(ref Vector3 left, ref Vector3 right, out Vector3 result) { result = new Vector3(left.Y * right.Z - left.Z * right.Y, left.Z * right.X - left.X * right.Z, left.X * right.Y - left.Y * right.X); } /// <summary> /// Calculates the distance between two points described by two vectors. /// </summary> /// <param name="left"></param> /// <param name="right"></param> public static float Distance(ref Vector3 left, ref Vector3 right) { Vector3 diff; diff.X = left.X - right.X; diff.Y = left.Y - right.Y; diff.Z = left.Z - right.Z; return (float)Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y + diff.Z * diff.Z); } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector3 Lerp(Vector3 a, Vector3 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; a.Z = blend * (b.Z - a.Z) + a.Z; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector3 a, ref Vector3 b, float blend, out Vector3 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float AngleBetween(Vector3 first, Vector3 second) { return (float)System.Math.Acos((Vector3.Dot(first, second)) / (first.Length * second.Length)); } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void AngleBetween(ref Vector3 first, ref Vector3 second, out float result) { float temp; Vector3.Dot(ref first, ref second, out temp); result = (float)System.Math.Acos(temp / (first.Length * second.Length)); } /// <summary> /// Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3 Transform(Vector3 vec, Matrix4 mat) { Vector3 result; Transform(ref vec, ref mat, out result); return result; } /// <summary> /// Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector3 vec, ref Matrix4 mat, out Vector3 result) { Vector4 row0 = mat.Row0; Vector4 row1 = mat.Row1; Vector4 row2 = mat.Row2; Vector4 row3 = mat.Row3; result.X = vec.X * row0.X + vec.Y * row1.X + vec.Z * row2.X + row3.X; result.Y = vec.X * row0.Y + vec.Y * row1.Y + vec.Z * row2.Y + row3.Y; result.Z = vec.X * row0.Z + vec.Y * row1.Z + vec.Z * row2.Z + row3.Z; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector3 Transform(Vector3 vec, Quaternion quat) { Vector3 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector3 vec, ref Quaternion quat, out Vector3 result) { // Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows: // vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec) Vector3 xyz = quat.Xyz, temp, temp2; Vector3.Cross(ref xyz, ref vec, out temp); Vector3.Multiply(ref vec, quat.W, out temp2); Vector3.Add(ref temp, ref temp2, out temp); Vector3.Cross(ref xyz, ref temp, out temp); Vector3.Multiply(ref temp, 2, out temp); Vector3.Add(ref vec, ref temp, out result); } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator +(Vector3 left, Vector3 right) { return new Vector3( left.X + right.X, left.Y + right.Y, left.Z + right.Z); } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator -(Vector3 left, Vector3 right) { return new Vector3( left.X - right.X, left.Y - right.Y, left.Z - right.Z); } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator -(Vector3 vec) { return new Vector3( -vec.X, -vec.Y, -vec.Z); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator *(Vector3 vec, float scale) { return new Vector3( vec.X * scale, vec.Y * scale, vec.Z * scale); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator *(float scale, Vector3 vec) { return vec * scale; } /// <summary> /// Scales an instance by a vector. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scale.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator *(Vector3 vec, Vector3 scale) { return new Vector3( vec.X * scale.X, vec.Y * scale.Y, vec.Z * scale.Z); } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator /(Vector3 vec, float scale) { return vec * (1.0f / scale); } /// <summary> /// Divides an instance by a vector. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator /(Vector3 vec, Vector3 scale) { return new Vector3( vec.X / scale.X, vec.Y / scale.Y, vec.Z / scale.Z); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector3 left, Vector3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector3 left, Vector3 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector3. /// </summary> public override string ToString() { return string.Format("({0}, {1}, {2})", this.X, this.Y, this.Z); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return this.X.GetHashCode() ^ this.Y.GetHashCode() ^ this.Z.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector3)) return false; return this.Equals((Vector3)obj); } /// <summary> /// Indicates whether the current vector is equal to another vector. /// </summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector3 other) { return this.X == other.X && this.Y == other.Y && this.Z == other.Z; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="CustomerServiceClient"/> instances.</summary> public sealed partial class CustomerServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomerServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomerServiceSettings"/>.</returns> public static CustomerServiceSettings GetDefault() => new CustomerServiceSettings(); /// <summary>Constructs a new <see cref="CustomerServiceSettings"/> object with default settings.</summary> public CustomerServiceSettings() { } private CustomerServiceSettings(CustomerServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateCustomerSettings = existing.MutateCustomerSettings; ListAccessibleCustomersSettings = existing.ListAccessibleCustomersSettings; CreateCustomerClientSettings = existing.CreateCustomerClientSettings; OnCopy(existing); } partial void OnCopy(CustomerServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerServiceClient.MutateCustomer</c> and <c>CustomerServiceClient.MutateCustomerAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCustomerSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerServiceClient.ListAccessibleCustomers</c> and /// <c>CustomerServiceClient.ListAccessibleCustomersAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListAccessibleCustomersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerServiceClient.CreateCustomerClient</c> and <c>CustomerServiceClient.CreateCustomerClientAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateCustomerClientSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CustomerServiceSettings"/> object.</returns> public CustomerServiceSettings Clone() => new CustomerServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomerServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class CustomerServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomerServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomerServiceClientBuilder() { UseJwtAccessWithScopes = CustomerServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomerServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomerServiceClient Build() { CustomerServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomerServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomerServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomerServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomerServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomerServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomerServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomerServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CustomerService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage customers. /// </remarks> public abstract partial class CustomerServiceClient { /// <summary> /// The default endpoint for the CustomerService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CustomerService scopes.</summary> /// <remarks> /// The default CustomerService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CustomerServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="CustomerServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomerServiceClient"/>.</returns> public static stt::Task<CustomerServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomerServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomerServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="CustomerServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomerServiceClient"/>.</returns> public static CustomerServiceClient Create() => new CustomerServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomerServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CustomerServiceSettings"/>.</param> /// <returns>The created <see cref="CustomerServiceClient"/>.</returns> internal static CustomerServiceClient Create(grpccore::CallInvoker callInvoker, CustomerServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomerService.CustomerServiceClient grpcClient = new CustomerService.CustomerServiceClient(callInvoker); return new CustomerServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CustomerService client</summary> public virtual CustomerService.CustomerServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerResponse MutateCustomer(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, st::CancellationToken cancellationToken) => MutateCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the customer /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerResponse MutateCustomer(string customerId, CustomerOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateCustomer(new MutateCustomerRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the customer /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(string customerId, CustomerOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateCustomerAsync(new MutateCustomerRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the customer /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerResponse> MutateCustomerAsync(string customerId, CustomerOperation operation, st::CancellationToken cancellationToken) => MutateCustomerAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns resource names of customers directly accessible by the /// user authenticating the call. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListAccessibleCustomersResponse ListAccessibleCustomers(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns resource names of customers directly accessible by the /// user authenticating the call. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns resource names of customers directly accessible by the /// user authenticating the call. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, st::CancellationToken cancellationToken) => ListAccessibleCustomersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CreateCustomerClientResponse CreateCustomerClient(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, st::CancellationToken cancellationToken) => CreateCustomerClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the Manager under whom client customer is being created. /// </param> /// <param name="customerClient"> /// Required. The new client customer to create. The resource name on this customer /// will be ignored. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CreateCustomerClientResponse CreateCustomerClient(string customerId, gagvr::Customer customerClient, gaxgrpc::CallSettings callSettings = null) => CreateCustomerClient(new CreateCustomerClientRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CustomerClient = gax::GaxPreconditions.CheckNotNull(customerClient, nameof(customerClient)), }, callSettings); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the Manager under whom client customer is being created. /// </param> /// <param name="customerClient"> /// Required. The new client customer to create. The resource name on this customer /// will be ignored. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(string customerId, gagvr::Customer customerClient, gaxgrpc::CallSettings callSettings = null) => CreateCustomerClientAsync(new CreateCustomerClientRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CustomerClient = gax::GaxPreconditions.CheckNotNull(customerClient, nameof(customerClient)), }, callSettings); /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the Manager under whom client customer is being created. /// </param> /// <param name="customerClient"> /// Required. The new client customer to create. The resource name on this customer /// will be ignored. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(string customerId, gagvr::Customer customerClient, st::CancellationToken cancellationToken) => CreateCustomerClientAsync(customerId, customerClient, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomerService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage customers. /// </remarks> public sealed partial class CustomerServiceClientImpl : CustomerServiceClient { private readonly gaxgrpc::ApiCall<MutateCustomerRequest, MutateCustomerResponse> _callMutateCustomer; private readonly gaxgrpc::ApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse> _callListAccessibleCustomers; private readonly gaxgrpc::ApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse> _callCreateCustomerClient; /// <summary> /// Constructs a client wrapper for the CustomerService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CustomerServiceSettings"/> used within this client.</param> public CustomerServiceClientImpl(CustomerService.CustomerServiceClient grpcClient, CustomerServiceSettings settings) { GrpcClient = grpcClient; CustomerServiceSettings effectiveSettings = settings ?? CustomerServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateCustomer = clientHelper.BuildApiCall<MutateCustomerRequest, MutateCustomerResponse>(grpcClient.MutateCustomerAsync, grpcClient.MutateCustomer, effectiveSettings.MutateCustomerSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomer); Modify_MutateCustomerApiCall(ref _callMutateCustomer); _callListAccessibleCustomers = clientHelper.BuildApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse>(grpcClient.ListAccessibleCustomersAsync, grpcClient.ListAccessibleCustomers, effectiveSettings.ListAccessibleCustomersSettings); Modify_ApiCall(ref _callListAccessibleCustomers); Modify_ListAccessibleCustomersApiCall(ref _callListAccessibleCustomers); _callCreateCustomerClient = clientHelper.BuildApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse>(grpcClient.CreateCustomerClientAsync, grpcClient.CreateCustomerClient, effectiveSettings.CreateCustomerClientSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callCreateCustomerClient); Modify_CreateCustomerClientApiCall(ref _callCreateCustomerClient); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateCustomerApiCall(ref gaxgrpc::ApiCall<MutateCustomerRequest, MutateCustomerResponse> call); partial void Modify_ListAccessibleCustomersApiCall(ref gaxgrpc::ApiCall<ListAccessibleCustomersRequest, ListAccessibleCustomersResponse> call); partial void Modify_CreateCustomerClientApiCall(ref gaxgrpc::ApiCall<CreateCustomerClientRequest, CreateCustomerClientResponse> call); partial void OnConstruction(CustomerService.CustomerServiceClient grpcClient, CustomerServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomerService client</summary> public override CustomerService.CustomerServiceClient GrpcClient { get; } partial void Modify_MutateCustomerRequest(ref MutateCustomerRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListAccessibleCustomersRequest(ref ListAccessibleCustomersRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateCustomerClientRequest(ref CreateCustomerClientRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCustomerResponse MutateCustomer(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerRequest(ref request, ref callSettings); return _callMutateCustomer.Sync(request, callSettings); } /// <summary> /// Updates a customer. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCustomerResponse> MutateCustomerAsync(MutateCustomerRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerRequest(ref request, ref callSettings); return _callMutateCustomer.Async(request, callSettings); } /// <summary> /// Returns resource names of customers directly accessible by the /// user authenticating the call. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListAccessibleCustomersResponse ListAccessibleCustomers(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListAccessibleCustomersRequest(ref request, ref callSettings); return _callListAccessibleCustomers.Sync(request, callSettings); } /// <summary> /// Returns resource names of customers directly accessible by the /// user authenticating the call. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListAccessibleCustomersResponse> ListAccessibleCustomersAsync(ListAccessibleCustomersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListAccessibleCustomersRequest(ref request, ref callSettings); return _callListAccessibleCustomers.Async(request, callSettings); } /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override CreateCustomerClientResponse CreateCustomerClient(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateCustomerClientRequest(ref request, ref callSettings); return _callCreateCustomerClient.Sync(request, callSettings); } /// <summary> /// Creates a new client under manager. The new client customer is returned. /// /// List of thrown errors: /// [AccessInvitationError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CurrencyCodeError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [QuotaError]() /// [RequestError]() /// [StringLengthError]() /// [TimeZoneError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<CreateCustomerClientResponse> CreateCustomerClientAsync(CreateCustomerClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateCustomerClientRequest(ref request, ref callSettings); return _callCreateCustomerClient.Async(request, callSettings); } } }
using System; using System.Data; using System.Configuration; using System.Web; using DSL.POS.BusinessLogicLayer.Interface; using DSL.POS.BusinessLogicLayer.Imp; using DSL.POS.DTO.DTO; namespace DSL.POS.Facade { /// <summary> /// Summary description for ProductFacade /// </summary> /// public class Facade { private static Facade ProFacade = new Facade(); public static Facade GetInstance() { return ProFacade; } public IProductUnitBL GetPUBLImp() { return ProductUnitBLImpl.GetInstance(); } public IBranchInfoBL createBranchBL() { return BranchInfoBLImpl.GetInstance(); } public BranchInfoDTO getBranchInfoDTO(Guid pk) { return BranchInfoBLImpl.loadBranchInfoDTO(pk); } public IProductCategoryBL createProductCategoryBL() { return ProductCategoryBLImp.GetInstance(); } public IProductSubCategoryInfoBL createProductSubCategoryBL() { return ProductSubCategoryInfoBLImp.GetInstance(); } public ISupplierInfoBL createSupplierBL() { return SupplierInfoBLImp.getInstanceSupplierInfoBLImp(); } public SupplierInfoDTO getSupplierInfo(Guid pk) { return SupplierInfoBLImp.loadSupplierInfoDto(pk); } public IMemberInfoBL createMemberBL() { return MemberInfoBLImp.getInstanceMemberInfoBLImp(); } public MemberInfoDTO getMemberInfo(Guid pk) { return MemberInfoBLImp.loadMemberInfoDto(pk); } public SupplierInfoDTO getSupplierInfoByCode(string suppCode) { return SupplierInfoBLImp.getSupplierPKByCode(suppCode); } /// <summary> /// get Member Primary Code corresponding Member Code /// </summary> /// <param name="strCode"></param> /// <returns></returns> public Guid getMemberPKInfoByCode(string strCode) { MemberInfoBLImp oMemberInfoBLImp = new MemberInfoBLImp(); return oMemberInfoBLImp.getMemberPKByCode(strCode); } public ISalesInfoBL createSalesBL() { return SalesInfoBLImp.getInstanceSalesInfoBLImp(); } public ISalesReturnInfoBL createSalesReturnBL() { return SalesReturnInfoBLImp.getInstanceSalesReturnInfoBLImp(); } public IPurchaseInfoBL createPurchaseBL() { return PurchaseInfoBLImp.getInstancePurchaseInfoBLImp(); } public IBranchTypeInfoBL createBranchTypeBL() { return BranchTypeInfoBLImp.getInstanceBranchTypeInfoBLImp(); } public BranchTypeInfoDTO getBranchTypeInfo(Guid id) { return BranchTypeInfoBLImp.loadBranchTypeInfoDto(id); } public IBoothInfoBL createBoothInfoBL() { return BoothInfoBLImp.getInstanceBoothInfoBLImp(); } public BoothInfoDTO getBoothInfoDTO(Guid id) { return BoothInfoBLImp.loadBoothInfoDto(id); } /// <summary> /// get Booth, Branch & BranchType Information corresponding BoothPrimaryKey /// </summary> /// <param name="BoothPK"></param> /// <returns>BoothInfoDTO</returns> public BoothInfoDTO getBoothInfo_AllDTO(Guid BoothPK) { return BoothInfoBLImp.loadBoothInfo_AllDTO(BoothPK); } /// <summary> /// Get BoothInformation corresponding Booth Code /// </summary> /// <param name="shrot BoothCode"></param> /// <returns>BoothInfoDTO</returns> public BoothInfoDTO getBoothInfoByCodeDTO(short BoothCode) { return BoothInfoBLImp.GetDataBoothInfoByCode(BoothCode); } public IProductBrandBL GetProductBrandDataList() { return ProductBrandBLImp.GetInstance(); } public ProductInfoDTO GetProductInfoDTO(Guid pk) { return ProductInfoBLImp.LoadProductInfoDTO(pk); } public IProductInfoBL GetProductInfoInstance() { return ProductInfoBLImp.GetInstance(); } public IProductBrandBL GetPBBlImp() { return ProductBrandBLImp.GetInstance(); } public IProductInfoBL GetPBLImp() { return ProductInfoBLImp.GetInstance(); } /// <summary> /// Find Product Primary Key corresponding Product Code /// </summary> /// <param name="strCode"></param> /// <returns></returns> public Guid getProductPKInfoByCode(string strCode) { ProductInfoBLImp oProductInfoBLImp = new ProductInfoBLImp(); return oProductInfoBLImp.getProductPKByCode(strCode); } public IProductUnitBL GetProductUnitDataList() { return ProductUnitBLImpl.GetInstance(); } public ProductCategoryInfoDTO GetProductCategoryInfo(Guid guid) { return ProductCategoryBLImp.LoadCategoryInfo(guid); } public ProductSubCategoryInfoDTO GetProductsubCategoryInfo(Guid guid) { return ProductSubCategoryInfoBLImp.LoadSubCategoryInfo(guid); } public ProductBrandInfoDTO GetProductBrandInfo(Guid guid) { return ProductBrandBLImp.LoadProductBrandInfo(guid); } public ProductUnitInfoDTO GetProductUnitInfo(Guid guid) { return ProductUnitBLImpl.LoadProductUnitInfo(guid); } //public SalesMainInfoDTO GetSalesInfoDTO(string strInvoice) //{ // try // { // SalesInfoBLImp oSalesInfoBLImp = new SalesInfoBLImp(); // return oSalesInfoBLImp.GetSalesReturnInfoByInvoiceNo(strInvoice); // } // catch (Exception exp) // { // throw exp; // } //} public SalesReturnMainDTO GetSalesReturnInfoDTO(string strInvoice) { try { SalesReturnInfoBLImp oSalesReturnInfoBLImp = new SalesReturnInfoBLImp(); return oSalesReturnInfoBLImp.GetSalesReturnInfoByInvoiceNo(strInvoice); } catch (Exception exp) { throw exp; } } public IPurchaseReturnInfoBL createPurchaseReturnBL() { return PurchaseReturnInfoBLImp.getInstancePurchaseReturnInfoBLImp(); } public PurchaseReturnMainDTO GetPurchaseReturnInfoDTO(string strGRNNo) { try { PurchaseReturnInfoBLImp oPurchaseReturnInfoBLImp = new PurchaseReturnInfoBLImp(); return oPurchaseReturnInfoBLImp.GetPurchaseReturnInfoByGRNNo(strGRNNo); } catch (Exception Exp) { throw Exp; } } public IOpeningBalanceBL createOpeningBalanceBL() { return OpeningBalanceBLImp.getInstanceOpeningBalanceBLImp(); } protected Facade() { // // TODO: Add constructor logic here // } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Newtonsoft.Json.Schema; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE || ASPNETCORE50) using System.Numerics; #endif using System.Runtime.Serialization; using System.Text; #if !(NET20 || NET35) using System.Threading.Tasks; #endif using System.Xml; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif ASPNETCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonConvertTest : TestFixtureBase { [Test] public void DefaultSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }); StringAssert.AreEqual(@"{ ""test"": [ 1, 2, 3 ] }", json); } finally { JsonConvert.DefaultSettings = null; } } public class NameTableTestClass { public string Value { get; set; } } public class NameTableTestClassConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { reader.Read(); reader.Read(); JsonTextReader jsonTextReader = (JsonTextReader)reader; Assert.IsNotNull(jsonTextReader.NameTable); string s = serializer.Deserialize<string>(reader); Assert.AreEqual("hi", s); Assert.IsNotNull(jsonTextReader.NameTable); NameTableTestClass o = new NameTableTestClass { Value = s }; return o; } public override bool CanConvert(Type objectType) { return objectType == typeof(NameTableTestClass); } } [Test] public void NameTableTest() { StringReader sr = new StringReader("{'property':'hi'}"); JsonTextReader jsonTextReader = new JsonTextReader(sr); Assert.IsNull(jsonTextReader.NameTable); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new NameTableTestClassConverter()); NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader); Assert.IsNull(jsonTextReader.NameTable); Assert.AreEqual("hi", o.Value); } [Test] public void DefaultSettings_Example() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; Employee e = new Employee { FirstName = "Eric", LastName = "Example", BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc), Department = "IT", JobTitle = "Web Dude" }; string json = JsonConvert.SerializeObject(e); // { // "firstName": "Eric", // "lastName": "Example", // "birthDate": "1980-04-20T00:00:00Z", // "department": "IT", // "jobTitle": "Web Dude" // } StringAssert.AreEqual(@"{ ""firstName"": ""Eric"", ""lastName"": ""Example"", ""birthDate"": ""1980-04-20T00:00:00Z"", ""department"": ""IT"", ""jobTitle"": ""Web Dude"" }", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Override() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings { Formatting = Formatting.None }); Assert.AreEqual(@"{""test"":[1,2,3]}", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Override_JsonConverterOrder() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } } }; string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings { Formatting = Formatting.None, Converters = { // should take precedence new JavaScriptDateTimeConverter(), new IsoDateTimeConverter { DateTimeFormat = "dd" } } }); Assert.AreEqual(@"[new Date(976593724000)]", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Create() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer.Formatting = Formatting.None; serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = new JsonSerializer(); serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(); serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_CreateWithSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = { new IntConverter() } }); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 2, 4, 6 ]", sw.ToString()); sw = new StringWriter(); serializer.Converters.Clear(); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented }); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } public class IntConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { int i = (int)value; writer.WriteValue(i * 2); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(int); } } [Test] public void DeserializeObject_EmptyString() { object result = JsonConvert.DeserializeObject(string.Empty); Assert.IsNull(result); } [Test] public void DeserializeObject_Integer() { object result = JsonConvert.DeserializeObject("1"); Assert.AreEqual(1L, result); } [Test] public void DeserializeObject_Integer_EmptyString() { int? value = JsonConvert.DeserializeObject<int?>(""); Assert.IsNull(value); } [Test] public void DeserializeObject_Decimal_EmptyString() { decimal? value = JsonConvert.DeserializeObject<decimal?>(""); Assert.IsNull(value); } [Test] public void DeserializeObject_DateTime_EmptyString() { DateTime? value = JsonConvert.DeserializeObject<DateTime?>(""); Assert.IsNull(value); } [Test] public void EscapeJavaScriptString() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true); Assert.AreEqual(@"""How now brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true); Assert.AreEqual(@"""How now 'brown' cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true); Assert.AreEqual(@"""How now <brown> cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true); Assert.AreEqual(@"""How \r\nnow brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true); Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true); Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result); result = JavaScriptUtils.ToEscapedJavaScriptString( "\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true); Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result); result = JavaScriptUtils.ToEscapedJavaScriptString( "!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true); Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true); Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result); string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""; result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true); Assert.AreEqual(expected, result); result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true); Assert.AreEqual(result, @"'Fred\'s cat.'"); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true); Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true); Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true); Assert.AreEqual(result, @"'Fred\'s ""cat"".'"); result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true); Assert.AreEqual(result, @"""\u001farray<address"""); } [Test] public void EscapeJavaScriptString_UnicodeLinefeeds() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true); Assert.AreEqual(@"""before\u0085after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true); Assert.AreEqual(@"""before\u2028after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true); Assert.AreEqual(@"""before\u2029after""", result); } [Test] public void ToStringInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation."); } [Test] public void GuidToString() { Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"); string json = JsonConvert.ToString(guid); Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json); } [Test] public void EnumToString() { string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase); Assert.AreEqual("1", json); } [Test] public void ObjectToString() { object value; value = 1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = 1.1; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = 1.1m; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = (float)1.1; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = (short)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (long)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (byte)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (uint)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (ushort)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (sbyte)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (ulong)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind)); #if !NET20 value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value)); value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat)); #endif value = null; Assert.AreEqual("null", JsonConvert.ToString(value)); #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) value = DBNull.Value; Assert.AreEqual("null", JsonConvert.ToString(value)); #endif value = "I am a string"; Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value)); value = true; Assert.AreEqual("true", JsonConvert.ToString(value)); value = 'c'; Assert.AreEqual(@"""c""", JsonConvert.ToString(value)); } [Test] public void TestInvalidStrings() { ExceptionAssert.Throws<JsonReaderException>(() => { string orig = @"this is a string ""that has quotes"" "; string serialized = JsonConvert.SerializeObject(orig); // *** Make string invalid by stripping \" \" serialized = serialized.Replace(@"\""", "\""); JsonConvert.DeserializeObject<string>(serialized); }, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19."); } [Test] public void DeserializeValueObjects() { int i = JsonConvert.DeserializeObject<int>("1"); Assert.AreEqual(1, i); #if !NET20 DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/"""); Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d); #endif bool b = JsonConvert.DeserializeObject<bool>("true"); Assert.AreEqual(true, b); object n = JsonConvert.DeserializeObject<object>("null"); Assert.AreEqual(null, n); object u = JsonConvert.DeserializeObject<object>("undefined"); Assert.AreEqual(null, u); } [Test] public void FloatToString() { Assert.AreEqual("1.1", JsonConvert.ToString(1.1)); Assert.AreEqual("1.11", JsonConvert.ToString(1.11)); Assert.AreEqual("1.111", JsonConvert.ToString(1.111)); Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111)); Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111)); Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111)); Assert.AreEqual("1.0", JsonConvert.ToString(1.0)); Assert.AreEqual("1.0", JsonConvert.ToString(1d)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1d)); Assert.AreEqual("1.01", JsonConvert.ToString(1.01)); Assert.AreEqual("1.001", JsonConvert.ToString(1.001)); Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity)); Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity)); Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN)); } [Test] public void DecimalToString() { Assert.AreEqual("1.1", JsonConvert.ToString(1.1m)); Assert.AreEqual("1.11", JsonConvert.ToString(1.11m)); Assert.AreEqual("1.111", JsonConvert.ToString(1.111m)); Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m)); Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m)); Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m)); Assert.AreEqual("1.0", JsonConvert.ToString(1.0m)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1m)); Assert.AreEqual("1.0", JsonConvert.ToString(1m)); Assert.AreEqual("1.01", JsonConvert.ToString(1.01m)); Assert.AreEqual("1.001", JsonConvert.ToString(1.001m)); Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue)); Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue)); } [Test] public void StringEscaping() { string v = "It's a good day\r\n\"sunshine\""; string json = JsonConvert.ToString(v); Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json); } [Test] public void ToStringStringEscapeHandling() { string v = "<b>hi " + '\u20AC' + "</b>"; string json = JsonConvert.ToString(v, '"'); Assert.AreEqual(@"""<b>hi " + '\u20AC' + @"</b>""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml); Assert.AreEqual(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii); Assert.AreEqual(@"""<b>hi \u20ac</b>""", json); } [Test] public void WriteDateTime() { DateTimeResult result = null; result = TestDateTime("DateTime Max", DateTime.MaxValue); Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip); Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified); Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc); DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local); string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local", year2000local); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc); DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local); localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal); Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc); DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local); localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with ticks", ticksLocal); Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc); DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); result = TestDateTime("DateTime Unspecified", year2000Unspecified); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc); DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc); string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Utc", year2000Utc); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip); Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc); DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc); utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Unix Epoc", unixEpoc); Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip); Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc); result = TestDateTime("DateTime Min", DateTime.MinValue); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc); result = TestDateTime("DateTime Default", default(DateTime)); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc); #if !NET20 result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1))); Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5))); Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13))); Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero)); Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue); Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue); Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset)); Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); #endif } public class DateTimeResult { public string IsoDateRoundtrip { get; set; } public string IsoDateLocal { get; set; } public string IsoDateUnspecified { get; set; } public string IsoDateUtc { get; set; } public string MsDateRoundtrip { get; set; } public string MsDateLocal { get; set; } public string MsDateUnspecified { get; set; } public string MsDateUtc { get; set; } } private DateTimeResult TestDateTime<T>(string name, T value) { Console.WriteLine(name); DateTimeResult result = new DateTimeResult(); result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local); result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified); result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc); } result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local); result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified); result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc); } TestDateTimeFormat(value, new IsoDateTimeConverter()); #if !NETFX_CORE if (value is DateTime) { Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind)); } else { Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value)); } #endif #if !NET20 MemoryStream ms = new MemoryStream(); DataContractSerializer s = new DataContractSerializer(typeof(T)); s.WriteObject(ms, value); string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length)); Console.WriteLine(json); #endif Console.WriteLine(); return result; } private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { string date = null; if (value is DateTime) { date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling); } else { #if !NET20 date = JsonConvert.ToString((DateTimeOffset)(object)value, format); #endif } Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date); if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind) { T parsed = JsonConvert.DeserializeObject<T>(date); try { Assert.AreEqual(value, parsed); } catch (Exception) { long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.AreEqual(valueTicks, parsedTicks); } } return date.Trim('"'); } private static void TestDateTimeFormat<T>(T value, JsonConverter converter) { string date = Write(value, converter); Console.WriteLine(converter.GetType().Name + ": " + date); T parsed = Read<T>(date, converter); try { Assert.AreEqual(value, parsed); } catch (Exception) { // JavaScript ticks aren't as precise, recheck after rounding long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.AreEqual(valueTicks, parsedTicks); } } public static long GetTicks(object value) { return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks; } public static string Write(object value, JsonConverter converter) { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); converter.WriteJson(writer, value, null); writer.Flush(); return sw.ToString(); } public static T Read<T>(string text, JsonConverter converter) { JsonTextReader reader = new JsonTextReader(new StringReader(text)); reader.ReadAsString(); return (T)converter.ReadJson(reader, typeof(T), null, null); } #if !(NET20 || NET35 || PORTABLE40) [Test] public void Async() { Task<string> task = null; #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(42); #pragma warning restore 612,618 task.Wait(); Assert.AreEqual("42", task.Result); #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(new[] { 1, 2, 3, 4, 5 }, Formatting.Indented); #pragma warning restore 612,618 task.Wait(); StringAssert.AreEqual(@"[ 1, 2, 3, 4, 5 ]", task.Result); #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }); #pragma warning restore 612,618 task.Wait(); Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result); #pragma warning disable 612,618 var taskObject = JsonConvert.DeserializeObjectAsync("[]"); #pragma warning restore 612,618 taskObject.Wait(); CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result); #pragma warning disable 612,618 Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings { Converters = { new VersionConverter() } }); #pragma warning restore 612,618 taskVersionArray.Wait(); Version[] versionArray = (Version[])taskVersionArray.Result; Assert.AreEqual(1, versionArray.Length); Assert.AreEqual(2, versionArray[0].Major); #pragma warning disable 612,618 Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5"); #pragma warning restore 612,618 taskInt.Wait(); Assert.AreEqual(5, taskInt.Result); #pragma warning disable 612,618 var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings { Converters = { new VersionConverter() } }); #pragma warning restore 612,618 taskVersion.Wait(); Assert.AreEqual(2, taskVersion.Result.Major); Movie p = new Movie(); p.Name = "Existing,"; #pragma warning disable 612,618 Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings { Converters = new List<JsonConverter> { new StringAppenderConverter() } }); #pragma warning restore 612,618 taskVoid.Wait(); Assert.AreEqual("Existing,Appended", p.Name); } #endif [Test] public void SerializeObjectDateTimeZoneHandling() { string json = JsonConvert.SerializeObject( new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json); } [Test] public void DeserializeObject() { string json = @"{ 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }"; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; // Bad Boys Assert.AreEqual("Bad Boys", m.Name); } #if !NET20 [Test] public void TestJsonDateTimeOffsetRoundtrip() { var now = DateTimeOffset.Now; var dict = new Dictionary<string, object> { { "foo", now } }; var settings = new JsonSerializerSettings(); settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateParseHandling = DateParseHandling.DateTimeOffset; settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; var json = JsonConvert.SerializeObject(dict, settings); Console.WriteLine(json); var newDict = new Dictionary<string, object>(); JsonConvert.PopulateObject(json, newDict, settings); var date = newDict["foo"]; Assert.AreEqual(date, now); } [Test] public void MaximumDateTimeOffsetLength() { DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0)); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } #endif [Test] public void MaximumDateTimeLength() { DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } [Test] public void MaximumDateTimeMicrosoftDateFormatLength() { DateTime dt = DateTime.MaxValue; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE || ASPNETCORE50) [Test] public void IntegerLengthOverflows() { // Maximum javascript number length (in characters) is 380 JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}"); JValue v = (JValue)o["biginteger"]; Assert.AreEqual(JTokenType.Integer, v.Type); Assert.AreEqual(typeof(BigInteger), v.Value.GetType()); Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value); ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395."); } #endif [Test] public void ParseIsoDate() { StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00"""); JsonReader jsonReader = new JsonTextReader(sr); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(typeof(DateTime), jsonReader.ValueType); } //[Test] public void StackOverflowTest() { StringBuilder sb = new StringBuilder(); int depth = 900; for (int i = 0; i < depth; i++) { sb.Append("{'A':"); } // invalid json sb.Append("{***}"); for (int i = 0; i < depth; i++) { sb.Append("}"); } string json = sb.ToString(); JsonSerializer serializer = new JsonSerializer() { }; serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json))); } public class Nest { public Nest A { get; set; } } [Test] public void ParametersPassedToJsonConverterConstructor() { ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" }; string json = JsonConvert.SerializeObject(clobber); Assert.AreEqual("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json); } public class ClobberMyProperties { [JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)] public string One { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)] public string Two { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Tres")] public string Three { get; set; } public string Four { get; set; } } public class ClobberingJsonConverter : JsonConverter { public string ClobberValueString { get; private set; } public int ClobberValueInt { get; private set; } public ClobberingJsonConverter(string clobberValueString, int clobberValueInt) { ClobberValueString = clobberValueString; ClobberValueInt = clobberValueInt; } public ClobberingJsonConverter(string clobberValueString) : this(clobberValueString, 1337) { } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(string); } } [Test] public void WrongParametersPassedToJsonConvertConstructorShouldThrow() { IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" }; ExceptionAssert.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); }); } public class IncorrectJsonConvertParameters { /// <summary> /// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an /// exception is thrown. /// </summary> [JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")] public string One { get; set; } } [Test] public void CustomDoubleRounding() { var measurements = new Measurements { Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 }, Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 }, Gain = 12345.67895111213 }; string json = JsonConvert.SerializeObject(measurements); Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json); } public class Measurements { [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))] public List<double> Positions { get; set; } [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })] public List<double> Loads { get; set; } [JsonConverter(typeof(RoundingJsonConverter), 4)] public double Gain { get; set; } } public class RoundingJsonConverter : JsonConverter { int _precision; MidpointRounding _rounding; public RoundingJsonConverter() : this(2) { } public RoundingJsonConverter(int precision) : this(precision, MidpointRounding.AwayFromZero) { } public RoundingJsonConverter(int precision, MidpointRounding rounding) { _precision = precision; _rounding = rounding; } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return objectType == typeof(double); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(Math.Round((double)value, _precision, _rounding)); } } } }
using System; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Caliburn.Micro; using JetBrains.Annotations; using LogoFX.Client.Mvvm.Commanding; using LogoFX.Client.Mvvm.ViewModel.Extensions; using LogoFX.Client.Mvvm.ViewModel.Services; using LogoFX.Client.Mvvm.ViewModel.Shared; using LogoFX.Core; using Samples.Client.Model.Contracts; using Samples.Specifications.Client.Presentation.Shell.Contracts.ViewModels; namespace Samples.Specifications.Client.Presentation.Shell.ViewModels { [UsedImplicitly] public sealed class MainViewModel : BusyScreen, IMainViewModel { private readonly IViewModelCreatorService _viewModelCreatorService; private readonly IDataService _dataService; private readonly IWindowManager _windowManager; public MainViewModel( IViewModelCreatorService viewModelCreatorService, IDataService dataService, IWindowManager windowManager) { _viewModelCreatorService = viewModelCreatorService; _dataService = dataService; _windowManager = windowManager; NewWarehouseItem(); } private IActionCommand _newCommand; public ICommand NewCommand => CommandFactory.GetCommand(ref _newCommand, NewWarehouseItem); private IActionCommand _deleteCommand; public ICommand DeleteCommand => CommandFactory .GetCommand(ref _deleteCommand, DeleteSelectedItem, () => ActiveWarehouseItem?.Item.Model.IsNew == false) .RequeryOnPropertyChanged(this, () => ActiveWarehouseItem); private WarehouseItemContainerViewModel _activeWarehouseItem; public IWarehouseItemContainerViewModel ActiveWarehouseItem { get => _activeWarehouseItem; set { if (_activeWarehouseItem == value) { return; } if (_activeWarehouseItem != null) { _activeWarehouseItem.Saving -= OnSaving; _activeWarehouseItem.Saved -= OnSaved; } _activeWarehouseItem = value as WarehouseItemContainerViewModel; if (_activeWarehouseItem != null) { _activeWarehouseItem.Saving += OnSaving; _activeWarehouseItem.Saved += OnSaved; } NotifyOfPropertyChange(); } } private async void OnSaved(object sender, ResultEventArgs e) { IsBusy = true; try { await _dataService.GetWarehouseItemsAsync(); } finally { IsBusy = false; } NewWarehouseItem(); } private void OnSaving(object sender, EventArgs e) { IsBusy = true; } private WarehouseItemsViewModel _warehouseItems; public IWarehouseItemsViewModel WarehouseItems => _warehouseItems ?? (_warehouseItems = CreateWarehouseItems()); private WarehouseItemsViewModel CreateWarehouseItems() { var warehouseItemsViewModel = _viewModelCreatorService.CreateViewModel<WarehouseItemsViewModel>(); EventHandler strongHandler = WarehouseItemsSelectionChanged; warehouseItemsViewModel.Items.SelectionChanged += WeakDelegate.From(strongHandler); return warehouseItemsViewModel; } private void WarehouseItemsSelectionChanged(object sender, EventArgs e) { var selectedItem = WarehouseItems.Items.SelectedItem; ActiveWarehouseItem = selectedItem == null ? null : _viewModelCreatorService.CreateViewModel<IWarehouseItem, WarehouseItemContainerViewModel>( ((WarehouseItemViewModel) WarehouseItems.Items.SelectedItem).Model); } private EventsViewModel _events; public IEventsViewModel Events => _events ?? (_events = _viewModelCreatorService.CreateViewModel<EventsViewModel>()); private async void NewWarehouseItem() { IsBusy = true; try { var warehouseItem = await _dataService.NewWarehouseItemAsync(); var newItem = _viewModelCreatorService.CreateViewModel<IWarehouseItem, WarehouseItemContainerViewModel>(warehouseItem); ActiveWarehouseItem = newItem; } finally { IsBusy = false; } } private async void DeleteSelectedItem() { IsBusy = true; try { await _dataService.DeleteWarehouseItemAsync(ActiveWarehouseItem?.Item.Model); await _dataService.GetWarehouseItemsAsync(); } finally { IsBusy = false; } NewWarehouseItem(); } protected override async void OnInitialize() { base.OnInitialize(); await _dataService.GetWarehouseItemsAsync(); } public override async void CanClose(Action<bool> callback) { if (_dataService.WarehouseItems.Any(t => t.IsDirty)) { var exitOptionsViewModel = _viewModelCreatorService.CreateViewModel<ExitOptionsViewModel>(); _windowManager.ShowDialog(exitOptionsViewModel); var result = exitOptionsViewModel.Result; if (result == MessageResult.Yes) { foreach (var warehouseItem in _dataService.WarehouseItems.Where(t => t.IsDirty && t.CanCommitChanges)) { await _dataService.SaveWarehouseItemAsync(warehouseItem); warehouseItem.CommitChanges(); } await WaitForTestApplication(); callback(true); } else if (result == MessageResult.No) { foreach (var warehouseItem in _dataService.WarehouseItems.Where(t => t.IsDirty && t.CanCancelChanges)) { warehouseItem.CancelChanges(); } await WaitForTestApplication(); callback(true); } else if (result == MessageResult.Cancel) { callback(false); } } else { callback(true); } } private static async Task WaitForTestApplication() { //Added for testability purposes only //The UI test engine has to query controls and perform several actions await Task.Delay(1000); } public void Dispose() { _deleteCommand?.Dispose(); _newCommand?.Dispose(); _activeWarehouseItem?.Dispose(); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']" [global::Android.Runtime.Register ("org/webrtc/EglBase", DoNotGenerateAcw=true)] public sealed partial class EglBase : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']" [global::Android.Runtime.Register ("org/webrtc/EglBase$ConfigType", DoNotGenerateAcw=true)] public sealed partial class ConfigType : global::Java.Lang.Enum { static IntPtr PIXEL_BUFFER_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='PIXEL_BUFFER']" [Register ("PIXEL_BUFFER")] public static global::Org.Webrtc.EglBase.ConfigType PixelBuffer { get { if (PIXEL_BUFFER_jfieldId == IntPtr.Zero) PIXEL_BUFFER_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "PIXEL_BUFFER", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, PIXEL_BUFFER_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr PLAIN_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='PLAIN']" [Register ("PLAIN")] public static global::Org.Webrtc.EglBase.ConfigType Plain { get { if (PLAIN_jfieldId == IntPtr.Zero) PLAIN_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "PLAIN", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, PLAIN_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr RECORDABLE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='RECORDABLE']" [Register ("RECORDABLE")] public static global::Org.Webrtc.EglBase.ConfigType Recordable { get { if (RECORDABLE_jfieldId == IntPtr.Zero) RECORDABLE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "RECORDABLE", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, RECORDABLE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/EglBase$ConfigType", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ConfigType); } } internal ConfigType (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/EglBase$ConfigType;", "")] public static unsafe global::Org.Webrtc.EglBase.ConfigType ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/EglBase$ConfigType;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.EglBase.ConfigType __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/EglBase$ConfigType;", "")] public static unsafe global::Org.Webrtc.EglBase.ConfigType[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/EglBase$ConfigType;"); try { return (global::Org.Webrtc.EglBase.ConfigType[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.EglBase.ConfigType)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/EglBase", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (EglBase); } } internal EglBase (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/constructor[@name='EglBase' and count(parameter)=2 and parameter[1][@type='android.opengl.EGLContext'] and parameter[2][@type='org.webrtc.EglBase.ConfigType']]" [Register (".ctor", "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", "")] public unsafe EglBase (global::Android.Opengl.EGLContext p0, global::Org.Webrtc.EglBase.ConfigType p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); if (GetType () != typeof (EglBase)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", __args); return; } if (id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_ == IntPtr.Zero) id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_, __args); } finally { } } static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/constructor[@name='EglBase' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe EglBase () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (EglBase)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } static IntPtr id_getContext; public unsafe global::Android.Opengl.EGLContext Context { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='getContext' and count(parameter)=0]" [Register ("getContext", "()Landroid/opengl/EGLContext;", "GetGetContextHandler")] get { if (id_getContext == IntPtr.Zero) id_getContext = JNIEnv.GetMethodID (class_ref, "getContext", "()Landroid/opengl/EGLContext;"); try { return global::Java.Lang.Object.GetObject<global::Android.Opengl.EGLContext> (JNIEnv.CallObjectMethod (Handle, id_getContext), JniHandleOwnership.TransferLocalRef); } finally { } } } static IntPtr id_hasSurface; public unsafe bool HasSurface { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='hasSurface' and count(parameter)=0]" [Register ("hasSurface", "()Z", "GetHasSurfaceHandler")] get { if (id_hasSurface == IntPtr.Zero) id_hasSurface = JNIEnv.GetMethodID (class_ref, "hasSurface", "()Z"); try { return JNIEnv.CallBooleanMethod (Handle, id_hasSurface); } finally { } } } static IntPtr id_isEGL14Supported; public static unsafe bool IsEGL14Supported { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='isEGL14Supported' and count(parameter)=0]" [Register ("isEGL14Supported", "()Z", "GetIsEGL14SupportedHandler")] get { if (id_isEGL14Supported == IntPtr.Zero) id_isEGL14Supported = JNIEnv.GetStaticMethodID (class_ref, "isEGL14Supported", "()Z"); try { return JNIEnv.CallStaticBooleanMethod (class_ref, id_isEGL14Supported); } finally { } } } static IntPtr id_createDummyPbufferSurface; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createDummyPbufferSurface' and count(parameter)=0]" [Register ("createDummyPbufferSurface", "()V", "")] public unsafe void CreateDummyPbufferSurface () { if (id_createDummyPbufferSurface == IntPtr.Zero) id_createDummyPbufferSurface = JNIEnv.GetMethodID (class_ref, "createDummyPbufferSurface", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_createDummyPbufferSurface); } finally { } } static IntPtr id_createPbufferSurface_II; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createPbufferSurface' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]" [Register ("createPbufferSurface", "(II)V", "")] public unsafe void CreatePbufferSurface (int p0, int p1) { if (id_createPbufferSurface_II == IntPtr.Zero) id_createPbufferSurface_II = JNIEnv.GetMethodID (class_ref, "createPbufferSurface", "(II)V"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); JNIEnv.CallVoidMethod (Handle, id_createPbufferSurface_II, __args); } finally { } } static IntPtr id_createSurface_Landroid_view_Surface_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createSurface' and count(parameter)=1 and parameter[1][@type='android.view.Surface']]" [Register ("createSurface", "(Landroid/view/Surface;)V", "")] public unsafe void CreateSurface (global::Android.Views.Surface p0) { if (id_createSurface_Landroid_view_Surface_ == IntPtr.Zero) id_createSurface_Landroid_view_Surface_ = JNIEnv.GetMethodID (class_ref, "createSurface", "(Landroid/view/Surface;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (Handle, id_createSurface_Landroid_view_Surface_, __args); } finally { } } static IntPtr id_makeCurrent; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='makeCurrent' and count(parameter)=0]" [Register ("makeCurrent", "()V", "")] public unsafe void MakeCurrent () { if (id_makeCurrent == IntPtr.Zero) id_makeCurrent = JNIEnv.GetMethodID (class_ref, "makeCurrent", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_makeCurrent); } finally { } } static IntPtr id_release; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='release' and count(parameter)=0]" [Register ("release", "()V", "")] public unsafe void Release () { if (id_release == IntPtr.Zero) id_release = JNIEnv.GetMethodID (class_ref, "release", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_release); } finally { } } static IntPtr id_releaseSurface; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='releaseSurface' and count(parameter)=0]" [Register ("releaseSurface", "()V", "")] public unsafe void ReleaseSurface () { if (id_releaseSurface == IntPtr.Zero) id_releaseSurface = JNIEnv.GetMethodID (class_ref, "releaseSurface", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_releaseSurface); } finally { } } static IntPtr id_swapBuffers; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='swapBuffers' and count(parameter)=0]" [Register ("swapBuffers", "()V", "")] public unsafe void SwapBuffers () { if (id_swapBuffers == IntPtr.Zero) id_swapBuffers = JNIEnv.GetMethodID (class_ref, "swapBuffers", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_swapBuffers); } finally { } } } }
// 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.Generic; using System.Diagnostics; using System.Linq.Expressions; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Runtime.Formatting; using Gallio.Common.Linq; using Gallio.Common.Diagnostics; namespace Gallio.Framework.Assertions { /// <summary> /// Evaluates a conditional expression. If the condition evaluates differently /// than expected, returns a detailed <see cref="AssertionFailure"/> that /// describes the formatted values of relevant sub-expressions within the condtion. /// </summary> [SystemInternal] public static class AssertionConditionEvaluator { /// <summary> /// Evaluates a conditional expression. /// </summary> /// <param name="condition">The conditional expression.</param> /// <param name="expectedResult">The expected result.</param> /// <param name="messageFormat">The custom assertion message format, or null if none.</param> /// <param name="messageArgs">The custom assertion message arguments, or null if none.</param> /// <returns>The assertion failure if the conditional expression evaluated /// to a different result than was expected or threw an exception, otherwise null.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="condition"/> is null.</exception> public static AssertionFailure Eval(Expression<System.Func<bool>> condition, bool expectedResult, string messageFormat, params object[] messageArgs) { if (condition == null) throw new ArgumentNullException("condition"); return new Interpreter(condition, expectedResult, messageFormat, messageArgs).Eval(); } private sealed class Interpreter : ExpressionInstrumentor { private readonly Expression<System.Func<bool>> condition; private readonly bool expectedResult; private readonly string messageFormat; private readonly object[] messageArgs; private Trace currentTrace; public Interpreter(Expression<System.Func<bool>> condition, bool expectedResult, string messageFormat, object[] messageArgs) { this.condition = condition; this.expectedResult = expectedResult; this.messageFormat = messageFormat; this.messageArgs = messageArgs; } public AssertionFailure Eval() { currentTrace = new Trace(null); try { bool result = Compile(condition)(); if (result == expectedResult) return null; return DescribeAssertionFailure(currentTrace); } catch (AbruptTerminationException ex) { return DescribeAssertionFailure(ex.Trace); } } [DebuggerHidden, DebuggerStepThrough] protected override T Intercept<T>(Expression expr, System.Func<T> continuation) { Trace parentTrace = currentTrace; Trace trace = new Trace(expr); try { currentTrace.AddChild(trace); currentTrace = trace; T result = base.Intercept(expr, continuation); trace.Result = result; return result; } catch (AbruptTerminationException ex) { trace.Exception = ex.Trace.Exception; throw; } catch (Exception ex) { trace.Exception = ex; throw new AbruptTerminationException(trace); } finally { currentTrace = parentTrace; } } private AssertionFailure DescribeAssertionFailure(Trace trace) { // Skip trivial nodes in the trace tree that are not of much interest. while (IsTrivialExpression(trace.Expression) && trace.Children.Count == 1 && trace.Exception == null) trace = trace.Children[0]; string expectedResultString = expectedResult ? "true" : "false"; AssertionFailureBuilder failureBuilder; if (trace.Exception != null) { failureBuilder = new AssertionFailureBuilder( String.Format("Expected the condition to evaluate to {0} but it threw an exception.", expectedResultString)) .AddException(trace.Exception); } else { failureBuilder = new AssertionFailureBuilder( String.Format("Expected the condition to evaluate to {0}.", expectedResultString)); } failureBuilder.SetMessage(messageFormat, messageArgs); failureBuilder.AddRawLabeledValue("Condition", condition.Body); var labeledTraces = new List<Trace>(); AddLabeledTraces(labeledTraces, trace); var addedLabels = new System.Collections.Generic.HashSet<string>(); foreach (Trace labeledTrace in labeledTraces) { // Only include the first value associated with a unique label so if a variable // appears multiple times in an expression, only its value from the outermost // expression it appears is displayed. string label = Formatter.Instance.Format(labeledTrace.Expression); if (! addedLabels.Contains(label)) { addedLabels.Add(label); failureBuilder.AddRawLabeledValue(label, labeledTrace.Result); } } return failureBuilder.ToAssertionFailure(); } private static void AddLabeledTraces(List<Trace> labeledTraces, Trace trace) { // Perform a breadth-first traversal of the expressions. var traversalQueue = new Queue<Pair<Trace, int>>(); traversalQueue.Enqueue(new Pair<Trace, int>(trace, 0)); while (traversalQueue.Count != 0) { Trace currentTrace = traversalQueue.Peek().First; int currentDepth = traversalQueue.Dequeue().Second; if (currentTrace.Exception == null) { Expression expr = currentTrace.Expression; if (!(expr is ConstantExpression)) { // We print the expressions at depth 1 but not the one at depth 0 because // it will just be "false". We know that the value was not equal to what we expected // so printing the value at depth 0 tells us nothing of interest. // Instead, to help determine the cause of this effect, we print the value of // the sub-expressions at depth 1. // // The exception to this rule is when the expression is a captured // variable or parameter. We always print these values because they are // most instructive about the context in which the expression was being // evaluated. For example, they may describe the value of a loop iteration // variable and other terms. if (currentDepth == 1 || expr.IsCapturedVariableOrParameter()) labeledTraces.Add(currentTrace); } } foreach (Trace child in currentTrace.Children) traversalQueue.Enqueue(new Pair<Trace,int>(child, currentDepth + 1)); } } private static bool IsTrivialExpression(Expression expr) { return expr == null || expr.NodeType == ExpressionType.Not; } } private sealed class Trace { private List<Trace> children; public Trace(Expression expression) { Expression = expression; } public Expression Expression { get; private set; } public object Result { get; set; } public Exception Exception { get; set; } public IList<Trace> Children { get { return children ?? (IList<Trace>) EmptyArray<Trace>.Instance; } } public void AddChild(Trace child) { if (children == null) children = new List<Trace>(); children.Add(child); } } [Serializable] private sealed class AbruptTerminationException : Exception { public AbruptTerminationException(Trace trace) { Trace = trace; } public Trace Trace { get; private set; } } } }
// // CairoExtensions.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Runtime.InteropServices; using Gdk; using Cairo; namespace Hyena.Gui { [Flags] public enum CairoCorners { None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8, All = 15 } public static class CairoExtensions { public static Pango.Layout CreateLayout (Gtk.Widget widget, Cairo.Context cairo_context) { Pango.Layout layout = PangoCairoHelper.CreateLayout (cairo_context); layout.FontDescription = widget.PangoContext.FontDescription; double resolution = widget.Screen.Resolution; if (resolution != -1) { Pango.Context context = PangoCairoHelper.LayoutGetContext (layout); PangoCairoHelper.ContextSetResolution (context, resolution); context.Dispose (); } Log.Debug ("Creating Pango.Layout, configuring Cairo.Context"); return layout; } public static Surface CreateSurfaceForPixbuf (Cairo.Context cr, Gdk.Pixbuf pixbuf) { Surface surface = cr.GetTarget ().CreateSimilar (cr.GetTarget ().Content, pixbuf.Width, pixbuf.Height); Cairo.Context surface_cr = new Context (surface); Gdk.CairoHelper.SetSourcePixbuf (surface_cr, pixbuf, 0, 0); surface_cr.Paint (); ((IDisposable)surface_cr).Dispose (); return surface; } public static Cairo.Color AlphaBlend (Cairo.Color ca, Cairo.Color cb, double alpha) { return new Cairo.Color ( (1.0 - alpha) * ca.R + alpha * cb.R, (1.0 - alpha) * ca.G + alpha * cb.G, (1.0 - alpha) * ca.B + alpha * cb.B); } public static Cairo.Color GdkColorToCairoColor(Gdk.Color color) { return GdkColorToCairoColor(color, 1.0); } public static Cairo.Color GdkColorToCairoColor(Gdk.Color color, double alpha) { return new Cairo.Color( (double)(color.Red >> 8) / 255.0, (double)(color.Green >> 8) / 255.0, (double)(color.Blue >> 8) / 255.0, alpha); } public static Cairo.Color RgbToColor (uint rgbColor) { return RgbaToColor ((rgbColor << 8) | 0x000000ff); } public static Cairo.Color RgbaToColor (uint rgbaColor) { return new Cairo.Color ( (byte)(rgbaColor >> 24) / 255.0, (byte)(rgbaColor >> 16) / 255.0, (byte)(rgbaColor >> 8) / 255.0, (byte)(rgbaColor & 0x000000ff) / 255.0); } public static bool ColorIsDark (Cairo.Color color) { double h, s, b; HsbFromColor (color, out h, out s, out b); return b < 0.5; } public static void HsbFromColor(Cairo.Color color, out double hue, out double saturation, out double brightness) { double min, max, delta; double red = color.R; double green = color.G; double blue = color.B; hue = 0; saturation = 0; brightness = 0; if(red > green) { max = Math.Max(red, blue); min = Math.Min(green, blue); } else { max = Math.Max(green, blue); min = Math.Min(red, blue); } brightness = (max + min) / 2; if(Math.Abs(max - min) < 0.0001) { hue = 0; saturation = 0; } else { saturation = brightness <= 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min); delta = max - min; if(red == max) { hue = (green - blue) / delta; } else if(green == max) { hue = 2 + (blue - red) / delta; } else if(blue == max) { hue = 4 + (red - green) / delta; } hue *= 60; if(hue < 0) { hue += 360; } } } private static double Modula(double number, double divisor) { return ((int)number % divisor) + (number - (int)number); } public static Cairo.Color ColorFromHsb(double hue, double saturation, double brightness) { int i; double [] hue_shift = { 0, 0, 0 }; double [] color_shift = { 0, 0, 0 }; double m1, m2, m3; m2 = brightness <= 0.5 ? brightness * (1 + saturation) : brightness + saturation - brightness * saturation; m1 = 2 * brightness - m2; hue_shift[0] = hue + 120; hue_shift[1] = hue; hue_shift[2] = hue - 120; color_shift[0] = color_shift[1] = color_shift[2] = brightness; i = saturation == 0 ? 3 : 0; for(; i < 3; i++) { m3 = hue_shift[i]; if(m3 > 360) { m3 = Modula(m3, 360); } else if(m3 < 0) { m3 = 360 - Modula(Math.Abs(m3), 360); } if(m3 < 60) { color_shift[i] = m1 + (m2 - m1) * m3 / 60; } else if(m3 < 180) { color_shift[i] = m2; } else if(m3 < 240) { color_shift[i] = m1 + (m2 - m1) * (240 - m3) / 60; } else { color_shift[i] = m1; } } return new Cairo.Color(color_shift[0], color_shift[1], color_shift[2]); } public static Cairo.Color ColorShade (Cairo.Color @base, double ratio) { double h, s, b; HsbFromColor (@base, out h, out s, out b); b = Math.Max (Math.Min (b * ratio, 1), 0); s = Math.Max (Math.Min (s * ratio, 1), 0); Cairo.Color color = ColorFromHsb (h, s, b); color.A = @base.A; return color; } public static Cairo.Color ColorAdjustBrightness(Cairo.Color @base, double br) { double h, s, b; HsbFromColor(@base, out h, out s, out b); b = Math.Max(Math.Min(br, 1), 0); return ColorFromHsb(h, s, b); } public static string ColorGetHex (Cairo.Color color, bool withAlpha) { if (withAlpha) { return String.Format("#{0:x2}{1:x2}{2:x2}{3:x2}", (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255), (byte)(color.A * 255)); } else { return String.Format("#{0:x2}{1:x2}{2:x2}", (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255)); } } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r) { RoundedRectangle(cr, x, y, w, h, r, CairoCorners.All, false); } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r, CairoCorners corners) { RoundedRectangle(cr, x, y, w, h, r, corners, false); } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r, CairoCorners corners, bool topBottomFallsThrough) { if(topBottomFallsThrough && corners == CairoCorners.None) { cr.MoveTo(x, y - r); cr.LineTo(x, y + h + r); cr.MoveTo(x + w, y - r); cr.LineTo(x + w, y + h + r); return; } else if(r < 0.0001 || corners == CairoCorners.None) { cr.Rectangle(x, y, w, h); return; } if((corners & (CairoCorners.TopLeft | CairoCorners.TopRight)) == 0 && topBottomFallsThrough) { y -= r; h += r; cr.MoveTo(x + w, y); } else { if((corners & CairoCorners.TopLeft) != 0) { cr.MoveTo(x + r, y); } else { cr.MoveTo(x, y); } if((corners & CairoCorners.TopRight) != 0) { cr.Arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); } else { cr.LineTo(x + w, y); } } if((corners & (CairoCorners.BottomLeft | CairoCorners.BottomRight)) == 0 && topBottomFallsThrough) { h += r; cr.LineTo(x + w, y + h); cr.MoveTo(x, y + h); cr.LineTo(x, y + r); cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); } else { if((corners & CairoCorners.BottomRight) != 0) { cr.Arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); } else { cr.LineTo(x + w, y + h); } if((corners & CairoCorners.BottomLeft) != 0) { cr.Arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); } else { cr.LineTo(x, y + h); } if((corners & CairoCorners.TopLeft) != 0) { cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); } else { cr.LineTo(x, y); } } } public static void DisposeContext (Cairo.Context cr) { ((IDisposable)cr.GetTarget ()).Dispose (); ((IDisposable)cr).Dispose (); } private struct CairoInteropCall { public string Name; public MethodInfo ManagedMethod; public bool CallNative; public CairoInteropCall (string name) { Name = name; ManagedMethod = null; CallNative = false; } } private static bool CallCairoMethod (Cairo.Context cr, ref CairoInteropCall call) { if (call.ManagedMethod == null && !call.CallNative) { MemberInfo [] members = typeof (Cairo.Context).GetMember (call.Name, MemberTypes.Method, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public); if (members != null && members.Length > 0 && members[0] is MethodInfo) { call.ManagedMethod = (MethodInfo)members[0]; } else { call.CallNative = true; } } if (call.ManagedMethod != null) { call.ManagedMethod.Invoke (cr, null); return true; } return false; } private static bool native_push_pop_exists = true; [DllImport ("libcairo-2.dll")] private static extern void cairo_push_group (IntPtr ptr); private static CairoInteropCall cairo_push_group_call = new CairoInteropCall ("PushGroup"); public static void PushGroup (Cairo.Context cr) { if (!native_push_pop_exists) { return; } try { if (!CallCairoMethod (cr, ref cairo_push_group_call)) { cairo_push_group (cr.Handle); } } catch { native_push_pop_exists = false; } } [DllImport ("libcairo-2.dll")] private static extern void cairo_pop_group_to_source (IntPtr ptr); private static CairoInteropCall cairo_pop_group_to_source_call = new CairoInteropCall ("PopGroupToSource"); public static void PopGroupToSource (Cairo.Context cr) { if (!native_push_pop_exists) { return; } try { if (!CallCairoMethod (cr, ref cairo_pop_group_to_source_call)) { cairo_pop_group_to_source (cr.Handle); } } catch (EntryPointNotFoundException) { native_push_pop_exists = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // 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 Xunit; using System.IO; using System.Xml; using System.Data.SqlTypes; using System.Globalization; namespace System.Data.Tests.SqlTypes { public class SqlBytesTest { // Test constructor [Fact] public void SqlBytesItem() { SqlBytes bytes = new SqlBytes(); try { Assert.Equal(bytes[0], 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } byte[] b = null; bytes = new SqlBytes(b); try { Assert.Equal(bytes[0], 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } b = new byte[10]; bytes = new SqlBytes(b); Assert.Equal(bytes[0], 0); try { Assert.Equal(bytes[-1], 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); } try { Assert.Equal(bytes[10], 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); } } [Fact] public void SqlBytesLength() { byte[] b = null; SqlBytes bytes = new SqlBytes(); try { Assert.Equal(bytes.Length, 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } bytes = new SqlBytes(b); try { Assert.Equal(bytes.Length, 0); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } b = new byte[10]; bytes = new SqlBytes(b); Assert.Equal(bytes.Length, 10); } [Fact] public void SqlBytesMaxLength() { byte[] b = null; SqlBytes bytes = new SqlBytes(); Assert.Equal(bytes.MaxLength, -1); bytes = new SqlBytes(b); Assert.Equal(bytes.MaxLength, -1); b = new byte[10]; bytes = new SqlBytes(b); Assert.Equal(bytes.MaxLength, 10); } [Fact] public void SqlBytesNull() { byte[] b = null; SqlBytes bytes = SqlBytes.Null; Assert.Equal(bytes.IsNull, true); } [Fact] public void SqlBytesStorage() { byte[] b = null; SqlBytes bytes = new SqlBytes(); try { Assert.Equal(bytes.Storage, StorageState.Buffer); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } bytes = new SqlBytes(b); try { Assert.Equal(bytes.Storage, StorageState.Buffer); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } b = new byte[10]; bytes = new SqlBytes(b); Assert.Equal(bytes.Storage, StorageState.Buffer); FileStream fs = null; bytes = new SqlBytes(fs); try { Assert.Equal(bytes.Storage, StorageState.Buffer); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } } [Fact] public void SqlBytesValue() { byte[] b1 = new byte[10]; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = bytes.Value; Assert.Equal(b1[0], b2[0]); b2[0] = 10; Assert.Equal(b1[0], 0); Assert.Equal(b2[0], 10); } [Fact] public void SqlBytesSetLength() { byte[] b1 = new byte[10]; SqlBytes bytes = new SqlBytes(); try { bytes.SetLength(20); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlTypeException), ex.GetType()); } bytes = new SqlBytes(b1); Assert.Equal(bytes.Length, 10); try { bytes.SetLength(-1); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); } try { bytes.SetLength(11); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); } bytes.SetLength(2); Assert.Equal(bytes.Length, 2); } [Fact] public void SqlBytesSetNull() { byte[] b1 = new byte[10]; SqlBytes bytes = new SqlBytes(b1); Assert.Equal(bytes.Length, 10); bytes.SetNull(); try { Assert.Equal(bytes.Length, 10); Assert.False(true); } catch (Exception ex) { Assert.Equal(typeof(SqlNullValueException), ex.GetType()); } Assert.Equal(true, bytes.IsNull); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlBytes.GetXsdType(null); Assert.Equal("base64Binary", qualifiedName.Name); } /* Read tests */ [Fact] public void Read_SuccessTest1() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[10]; bytes.Read(0, b2, 0, (int)bytes.Length); Assert.Equal(bytes.Value[5], b2[5]); } [Fact] public void Read_NullBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = null; Assert.Throws<ArgumentNullException>(() => bytes.Read(0, b2, 0, 10)); } [Fact] public void Read_InvalidCountTest1() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 0, 10)); } [Fact] public void Read_NegativeOffsetTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(-1, b2, 0, 4)); } [Fact] public void Read_NegativeOffsetInBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, -1, 4)); } [Fact] public void Read_InvalidOffsetInBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 8, 4)); } [Fact] public void Read_NullInstanceValueTest() { byte[] b2 = new byte[5]; SqlBytes bytes = new SqlBytes(); Assert.Throws<SqlNullValueException>(() => bytes.Read(0, b2, 8, 4)); } [Fact] public void Read_SuccessTest2() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[10]; bytes.Read(5, b2, 0, 10); Assert.Equal(bytes.Value[5], b2[0]); Assert.Equal(bytes.Value[9], b2[4]); } [Fact] public void Read_NullBufferAndInstanceValueTest() { byte[] b2 = null; SqlBytes bytes = new SqlBytes(); Assert.Throws<SqlNullValueException>(() => bytes.Read(0, b2, 8, 4)); } [Fact] public void Read_NegativeCountTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 0, -1)); } [Fact] public void Read_InvalidCountTest2() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(b1); byte[] b2 = new byte[5]; Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 3, 4)); } /* Write Tests */ [Fact] public void Write_SuccessTest1() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); bytes.Write(0, b1, 0, b1.Length); Assert.Equal(bytes.Value[0], b1[0]); } [Fact] public void Write_NegativeOffsetTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(-1, b1, 0, b1.Length)); } [Fact] public void Write_InvalidOffsetTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<SqlTypeException>(() => bytes.Write(bytes.Length + 5, b1, 0, b1.Length)); } [Fact] public void Write_NegativeOffsetInBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, -1, b1.Length)); } [Fact] public void Write_InvalidOffsetInBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, b1.Length + 5, b1.Length)); } [Fact] public void Write_InvalidCountTest1() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, 0, b1.Length + 5)); } [Fact] public void Write_InvalidCountTest2() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<SqlTypeException>(() => bytes.Write(8, b1, 0, b1.Length)); } [Fact] public void Write_NullBufferTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = null; SqlBytes bytes = new SqlBytes(b1); Assert.Throws<ArgumentNullException>(() => bytes.Write(0, b2, 0, 10)); } [Fact] public void Write_NullInstanceValueTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; SqlBytes bytes = new SqlBytes(); Assert.Throws<SqlTypeException>(() => bytes.Write(0, b1, 0, 10)); } [Fact] public void Write_NullBufferAndInstanceValueTest() { byte[] b1 = null; SqlBytes bytes = new SqlBytes(); Assert.Throws<ArgumentNullException>(() => bytes.Write(0, b1, 0, 10)); } [Fact] public void Write_SuccessTest2() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[20]; SqlBytes bytes = new SqlBytes(b2); bytes.Write(8, b1, 0, 10); Assert.Equal(bytes.Value[8], b1[0]); Assert.Equal(bytes.Value[17], b1[9]); } [Fact] public void Write_NegativeCountTest() { byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; byte[] b2 = new byte[10]; SqlBytes bytes = new SqlBytes(b2); Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, 0, -1)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using AstUtils = System.Linq.Expressions.Utils; namespace System.Linq.Expressions.Interpreter { internal static partial class DelegateHelpers { private const int MaximumArity = 17; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static Type MakeDelegate(Type[] types) { Debug.Assert(types != null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) { throw Assert.Unreachable; } Type returnType = types[types.Length - 1]; if (returnType == typeof(void)) { Array.Resize(ref types, types.Length - 1); switch (types.Length) { case 0: return typeof(Action); case 1: return typeof(Action<>).MakeGenericType(types); case 2: return typeof(Action<,>).MakeGenericType(types); case 3: return typeof(Action<,,>).MakeGenericType(types); case 4: return typeof(Action<,,,>).MakeGenericType(types); case 5: return typeof(Action<,,,,>).MakeGenericType(types); case 6: return typeof(Action<,,,,,>).MakeGenericType(types); case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); } } else { switch (types.Length) { case 1: return typeof(Func<>).MakeGenericType(types); case 2: return typeof(Func<,>).MakeGenericType(types); case 3: return typeof(Func<,,>).MakeGenericType(types); case 4: return typeof(Func<,,,>).MakeGenericType(types); case 5: return typeof(Func<,,,,>).MakeGenericType(types); case 6: return typeof(Func<,,,,,>).MakeGenericType(types); case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); } } throw Assert.Unreachable; } } internal class ScriptingRuntimeHelpers { public static object Int32ToObject(int i) { switch (i) { case -1: return Int32_m; case 0: return Int32_0; case 1: return Int32_1; case 2: return Int32_2; } return i; } private static readonly object Int32_m = -1; private static readonly object Int32_0 = 0; private static readonly object Int32_1 = 1; private static readonly object Int32_2 = 2; public static object BooleanToObject(bool b) { return b ? True : False; } internal static readonly object True = true; internal static readonly object False = false; internal static object GetPrimitiveDefaultValue(Type type) { object result; switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type)) { case TypeCode.Boolean: result = ScriptingRuntimeHelpers.False; break; case TypeCode.SByte: result = default(SByte); break; case TypeCode.Byte: result = default(Byte); break; case TypeCode.Char: result = default(Char); break; case TypeCode.Int16: result = default(Int16); break; case TypeCode.Int32: result = ScriptingRuntimeHelpers.Int32_0; break; case TypeCode.Int64: result = default(Int64); break; case TypeCode.UInt16: result = default(UInt16); break; case TypeCode.UInt32: result = default(UInt32); break; case TypeCode.UInt64: result = default(UInt64); break; case TypeCode.Single: return default(Single); case TypeCode.Double: return default(Double); // case TypeCode.DBNull: // return default(DBNull); case TypeCode.DateTime: return default(DateTime); case TypeCode.Decimal: return default(Decimal); default: return null; } if (type.GetTypeInfo().IsEnum) { result = Enum.ToObject(type, result); } return result; } } /// <summary> /// Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate. /// The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them. /// </summary> internal sealed class ArgumentArray { private readonly object[] _arguments; // the index of the first item _arguments that represents an argument: private readonly int _first; // the number of items in _arguments that represent the arguments: private readonly int _count; internal ArgumentArray(object[] arguments, int first, int count) { _arguments = arguments; _first = first; _count = count; } public int Count { get { return _count; } } public object GetArgument(int index) { return _arguments[_first + index]; } public static object GetArg(ArgumentArray array, int index) { return array._arguments[array._first + index]; } } internal static class ExceptionHelpers { private const string prevStackTraces = "PreviousStackTraces"; /// <summary> /// Updates an exception before it's getting re-thrown so /// we can present a reasonable stack trace to the user. /// </summary> public static Exception UpdateForRethrow(Exception rethrow) { #if FEATURE_STACK_TRACES List<StackTrace> prev; // we don't have any dynamic stack trace data, capture the data we can // from the raw exception object. StackTrace st = new StackTrace(rethrow, true); if (!TryGetAssociatedStackTraces(rethrow, out prev)) { prev = new List<StackTrace>(); AssociateStackTraces(rethrow, prev); } prev.Add(st); #endif // FEATURE_STACK_TRACES return rethrow; } #if FEATURE_STACK_TRACES /// <summary> /// Returns all the stack traces associates with an exception /// </summary> public static IList<StackTrace> GetExceptionStackTraces(Exception rethrow) { List<StackTrace> result; return TryGetAssociatedStackTraces(rethrow, out result) ? result : null; } private static void AssociateStackTraces(Exception e, List<StackTrace> traces) { e.Data[prevStackTraces] = traces; } private static bool TryGetAssociatedStackTraces(Exception e, out List<StackTrace> traces) { traces = e.Data[prevStackTraces] as List<StackTrace>; return traces != null; } #endif // FEATURE_STACK_TRACES } /// <summary> /// A hybrid dictionary which compares based upon object identity. /// </summary> internal class HybridReferenceDictionary<TKey, TValue> where TKey : class { private KeyValuePair<TKey, TValue>[] _keysAndValues; private Dictionary<TKey, TValue> _dict; private int _count; private const int _arraySize = 10; public HybridReferenceDictionary() { } public HybridReferenceDictionary(int initialCapicity) { if (initialCapicity > _arraySize) { _dict = new Dictionary<TKey, TValue>(initialCapicity); } else { _keysAndValues = new KeyValuePair<TKey, TValue>[initialCapicity]; } } public bool TryGetValue(TKey key, out TValue value) { Debug.Assert(key != null); if (_dict != null) { return _dict.TryGetValue(key, out value); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { value = _keysAndValues[i].Value; return true; } } } value = default(TValue); return false; } public bool Remove(TKey key) { Debug.Assert(key != null); if (_dict != null) { return _dict.Remove(key); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(); _count--; return true; } } } return false; } public bool ContainsKey(TKey key) { Debug.Assert(key != null); if (_dict != null) { return _dict.ContainsKey(key); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { return true; } } } return false; } public int Count { get { if (_dict != null) { return _dict.Count; } return _count; } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (_dict != null) { return _dict.GetEnumerator(); } return GetEnumeratorWorker(); } private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker() { if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key != null) { yield return _keysAndValues[i]; } } } } public TValue this[TKey key] { get { Debug.Assert(key != null); TValue res; if (TryGetValue(key, out res)) { return res; } throw new KeyNotFoundException(); } set { Debug.Assert(key != null); if (_dict != null) { _dict[key] = value; } else { int index; if (_keysAndValues != null) { index = -1; for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value); return; } else if (_keysAndValues[i].Key == null) { index = i; } } } else { _keysAndValues = new KeyValuePair<TKey, TValue>[_arraySize]; index = 0; } if (index != -1) { _count++; _keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value); } else { _dict = new Dictionary<TKey, TValue>(); for (int i = 0; i < _keysAndValues.Length; i++) { _dict[_keysAndValues[i].Key] = _keysAndValues[i].Value; } _keysAndValues = null; _dict[key] = value; } } } } } internal static class Assert { internal static Exception Unreachable { get { Debug.Assert(false, "Unreachable"); return new InvalidOperationException("Code supposed to be unreachable"); } } [Conditional("DEBUG")] public static void NotNull(object var) { Debug.Assert(var != null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2) { Debug.Assert(var1 != null && var2 != null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2, object var3) { Debug.Assert(var1 != null && var2 != null && var3 != null); } [Conditional("DEBUG")] public static void NotNullItems<T>(IEnumerable<T> items) where T : class { Debug.Assert(items != null); foreach (object item in items) { Debug.Assert(item != null); } } [Conditional("DEBUG")] public static void NotEmpty(string str) { Debug.Assert(!String.IsNullOrEmpty(str)); } } [Flags] internal enum ExpressionAccess { None = 0, Read = 1, Write = 2, ReadWrite = Read | Write, } internal sealed class ListEqualityComparer<T> : EqualityComparer<ICollection<T>> { internal static readonly ListEqualityComparer<T> Instance = new ListEqualityComparer<T>(); private ListEqualityComparer() { } // EqualityComparer<T> handles null and object identity for us public override bool Equals(ICollection<T> x, ICollection<T> y) { return x.ListEquals(y); } public override int GetHashCode(ICollection<T> obj) { return obj.ListHashCode(); } } }
//#define DEBUG using System.Collections; using System.Collections.Generic; using UnityEngine; using wvr; using WaveVR_Log; [System.Serializable] public class ButtonIndication { public enum Alignment { RIGHT, LEFT }; public enum KeyIndicator { TriggerKey, TouchPad, DigitalTriggerKey, AppButton, HomeButton, VolumeKey }; public KeyIndicator keyType; public Alignment alignment = Alignment.RIGHT; public Vector3 indicationOffset = new Vector3(0f, 0f, 0f); public bool useMultiLanguage = false; public string indicationText = "system"; public bool followButtonRotation = false; } [System.Serializable] public class ComponentsIndication { public string Name; // Component name public string Description = "system"; // Component description public GameObject SourceObject; public GameObject LineIndicator; public GameObject DestObject; public ButtonIndication.Alignment alignment = ButtonIndication.Alignment.RIGHT; public Vector3 Offset; public bool followButtonRoration = false; } public class WaveVR_ShowIndicator : MonoBehaviour { private static string LOG_TAG = "WaveVR_ShowIndicator"; private void PrintDebugLog(string msg) { #if UNITY_EDITOR Debug.Log(LOG_TAG + msg); #endif Log.d(LOG_TAG, msg); } private void PrintInfoLog(string msg) { #if UNITY_EDITOR Debug.Log(LOG_TAG + msg); #endif Log.i(LOG_TAG, msg); } [Header("Indication feature")] public bool showIndicator = false; [Range(0, 90.0f)] public float showIndicatorAngle = 30.0f; public bool hideIndicatorByRoll = true; [Header("Line customization")] [Range(0.01f, 0.1f)] public float lineLength = 0.03f; [Range(0.0001f, 0.1f)] public float lineStartWidth = 0.0004f; [Range(0.0001f, 0.1f)] public float lineEndWidth = 0.0004f; public Color lineColor = Color.white; [Header("Text customization")] [Range(0.01f, 0.2f)] public float textCharacterSize = 0.08f; [Range(0.01f, 0.2f)] public float zhCharactarSize = 0.07f; [Range(50, 200)] public int textFontSize = 100; public Color textColor = Color.white; [Header("Indications")] public List<ButtonIndication> buttonIndicationList = new List<ButtonIndication>(); #if !UNITY_EDITOR private WaveVR_Resource rw = null; private string sysLang = null; private string sysCountry = null; private int checkCount = 0; #endif private GameObject indicatorPrefab = null; private GameObject linePrefab = null; private List<ComponentsIndication> compInd = new List<ComponentsIndication>(); private GameObject _HMD = null; private bool needRedraw = true; // reset for redraw void resetIndicator() { if (showIndicator) { needRedraw = true; clearResourceAndObject(); } } void OnApplicationPause(bool pauseStatus) { if (pauseStatus == true) { resetIndicator(); } } void clearResourceAndObject() { PrintDebugLog("clear Indicator!"); foreach (ComponentsIndication ci in compInd) { if (ci.DestObject != null) { Destroy(ci.DestObject); } if (ci.LineIndicator != null) { Destroy(ci.LineIndicator); } } compInd.Clear(); Resources.UnloadUnusedAssets(); } void onAdaptiveControllerModelReady(params object[] args) { createIndicator(); } void OnEnable() { WaveVR_Utils.Event.Listen(WaveVR_Utils.Event.ADAPTIVE_CONTROLLER_READY, onAdaptiveControllerModelReady); } void OnDisable() { WaveVR_Utils.Event.Remove(WaveVR_Utils.Event.ADAPTIVE_CONTROLLER_READY, onAdaptiveControllerModelReady); } // Use this for initialization void Start() { } public void createIndicator() { if (!showIndicator) return; clearResourceAndObject(); PrintDebugLog("create Indicator!"); #if !UNITY_EDITOR rw = WaveVR_Resource.instance; #endif indicatorPrefab = Resources.Load("ComponentIndicator") as GameObject; if (indicatorPrefab == null) { PrintInfoLog("ComponentIndicator is not found!"); return; } else { PrintDebugLog("ComponentIndicator is found!"); } linePrefab = Resources.Load("LineIndicator") as GameObject; if (linePrefab == null) { PrintInfoLog("LineIndicator is not found!"); return; } else { PrintDebugLog("LineIndicator is found!"); } if (_HMD == null) _HMD = WaveVR_Render.Instance.gameObject; if (_HMD == null) { PrintInfoLog("Can't get HMD!"); return; } PrintInfoLog("showIndicatorAngle: " + showIndicatorAngle + ", hideIndicatorByRoll: " + hideIndicatorByRoll); PrintInfoLog("Line settings--\n lineLength: " + lineLength + ", lineStartWidth: " + lineStartWidth + ", lineEndWidth: " + lineEndWidth + ", lineColor: " + lineColor); PrintInfoLog("Text settings--\n textCharacterSize: " + textCharacterSize + ", zhCharactarSize: " + zhCharactarSize + ", textFontSize: " + textFontSize + ", textColor: " + textColor); foreach (ButtonIndication bi in buttonIndicationList) { PrintInfoLog("keyType: " + bi.keyType + ", alignment: " + bi.alignment + ", offset: " + bi.indicationOffset + ", useMultiLanguage: " + bi.useMultiLanguage + ", indication: " + bi.indicationText + ", followRotation: " + bi.followButtonRotation); // find component by name string partName = null; string partName1 = null; string indicationKey = null; switch(bi.keyType) { case ButtonIndication.KeyIndicator.AppButton: partName = "_[CM]_AppButton"; partName1 = "__CM__AppButton"; indicationKey = "AppKey"; break; case ButtonIndication.KeyIndicator.DigitalTriggerKey: partName = "_[CM]_DigiTriggerKey"; partName1 = "__CM__DigiTriggerKey"; indicationKey = "DigitalTriggerKey"; break; case ButtonIndication.KeyIndicator.HomeButton: partName = "_[CM]_HomeButton"; partName1 = "__CM__HomeButton"; indicationKey = "HomeKey"; break; case ButtonIndication.KeyIndicator.TouchPad: partName = "_[CM]_TouchPad"; partName1 = "__CM__TouchPad"; indicationKey = "TouchPad"; break; case ButtonIndication.KeyIndicator.TriggerKey: partName = "_[CM]_TriggerKey"; partName1 = "__CM__TriggerKey"; indicationKey = "TriggerKey"; break; case ButtonIndication.KeyIndicator.VolumeKey: partName = "_[CM]_VolumeKey"; partName1 = "__CM__VolumeKey"; indicationKey = "VolumeKey"; break; default: partName = "_[CM]_unknown"; partName1 = "__CM__unknown"; indicationKey = "unknown"; PrintDebugLog("Unknown key type!"); break; } Transform tmp = transform.Find(partName); if (tmp == null) { tmp = transform.Find(partName1); } if (tmp != null) { ComponentsIndication tmpCom = new ComponentsIndication(); tmpCom.Name = partName; tmpCom.SourceObject = tmp.gameObject; tmpCom.alignment = bi.alignment; tmpCom.followButtonRoration = bi.followButtonRotation; Vector3 linePos; tmpCom.LineIndicator = null; linePos = transform.TransformPoint(new Vector3(0, tmp.localPosition.y, tmp.localPosition.z) + bi.indicationOffset); Quaternion spawnRot = Quaternion.identity; if (bi.followButtonRotation == true) { spawnRot = transform.rotation; } GameObject lineGO = Instantiate(linePrefab, linePos, spawnRot); lineGO.name = partName + "Line"; var li = lineGO.GetComponent<IndicatorLine>(); li.lineColor = lineColor; li.lineLength = lineLength; li.startWidth = lineStartWidth; li.endWidth = lineEndWidth; li.alignment = bi.alignment; li.updateMeshSettings(); if (bi.followButtonRotation == true) { lineGO.transform.parent = tmpCom.SourceObject.transform; } lineGO.SetActive(false); tmpCom.LineIndicator = lineGO; tmpCom.DestObject = null; Vector3 spawnPos; if (bi.alignment == ButtonIndication.Alignment.RIGHT) { spawnPos = transform.TransformPoint(new Vector3(lineLength, tmp.localPosition.y, tmp.localPosition.z) + bi.indicationOffset); } else { spawnPos = transform.TransformPoint(new Vector3(lineLength * (-1), tmp.localPosition.y, tmp.localPosition.z) + bi.indicationOffset); } GameObject destGO = Instantiate(indicatorPrefab, spawnPos, transform.rotation); destGO.name = partName + "Ind"; if (bi.followButtonRotation == true) { destGO.transform.parent = tmpCom.SourceObject.transform; } PrintInfoLog(" Source PartName: " + tmp.gameObject.name + " pos: " + tmp.position + " Rot: " + tmp.rotation); PrintInfoLog(" Line Name: " + lineGO.name + " pos: " + lineGO.transform.position + " Rot: " + lineGO.transform.rotation); PrintInfoLog(" Destination Name: " + destGO.name + " pos: " + destGO.transform.position + " Rot: " + destGO.transform.rotation); int childC = destGO.transform.childCount; for (int i = 0; i < childC; i++) { GameObject c = destGO.transform.GetChild(i).gameObject; if (bi.alignment == ButtonIndication.Alignment.LEFT) { float tx = c.transform.localPosition.x; c.transform.localPosition = new Vector3(tx * (-1), c.transform.localPosition.y, c.transform.localPosition.z); } TextMesh tm = c.GetComponent<TextMesh>(); MeshRenderer mr = c.GetComponent<MeshRenderer>(); if (tm == null) PrintInfoLog(" tm is null "); if (mr == null) PrintInfoLog(" mr is null "); if (tm != null && mr != null) { tm.characterSize = textCharacterSize; if (c.name != "Shadow") { mr.material.SetColor("_Color", textColor); } else { PrintDebugLog(" Shadow found "); } tm.fontSize = textFontSize; if (bi.useMultiLanguage) { #if !UNITY_EDITOR sysLang = rw.getSystemLanguage(); sysCountry = rw.getSystemCountry(); PrintDebugLog(" System language is " + sysLang); if (sysLang.StartsWith("zh")) { PrintDebugLog(" Chinese language"); tm.characterSize = zhCharactarSize; } // use default string - multi-language if (bi.indicationText == "system") { tm.text = rw.getString(indicationKey); PrintInfoLog(" Name: " + destGO.name + " uses default multi-language -> " + tm.text); } else { tm.text = rw.getString(bi.indicationText); PrintInfoLog(" Name: " + destGO.name + " uses custom multi-language -> " + tm.text); } #else tm.text = bi.indicationText; #endif } else { if (bi.indicationText == "system") tm.text = indicationKey; else tm.text = bi.indicationText; PrintInfoLog(" Name: " + destGO.name + " didn't uses multi-language -> " + tm.text); } if (bi.alignment == ButtonIndication.Alignment.LEFT) { tm.anchor = TextAnchor.MiddleRight; tm.alignment = TextAlignment.Right; } } } destGO.SetActive(false); tmpCom.DestObject = destGO; tmpCom.Offset = bi.indicationOffset; PrintInfoLog(tmpCom.Name + " line -> " + tmpCom.LineIndicator.name + " destObjName -> " + tmpCom.DestObject.name); compInd.Add(tmpCom); } else { PrintInfoLog("Neither " + partName + " or " + partName1 + " is not in the model!"); } } needRedraw = false; } // Update is called once per frame void Update () { if (!showIndicator) return; if (_HMD == null) return; #if !UNITY_EDITOR checkCount++; if (checkCount > 50) { checkCount = 0; if (rw.getSystemLanguage() != sysLang || rw.getSystemCountry() != sysCountry) resetIndicator(); } #endif if (needRedraw == true) createIndicator(); Vector3 _targetForward = transform.rotation * Vector3.forward; Vector3 _targetRight = transform.rotation * Vector3.right; Vector3 _targetUp = transform.rotation * Vector3.up; float zAngle = Vector3.Angle(_targetForward, _HMD.transform.forward); float xAngle = Vector3.Angle(_targetRight, _HMD.transform.right); float yAngle = Vector3.Angle(_targetUp, _HMD.transform.up); #if DEBUG Log.gpl.d(LOG_TAG, "Z: " + _targetForward + ":" + zAngle + ", X: " + _targetRight + ":" + xAngle + ", Y: " + _targetUp + ":" + yAngle); #endif if ((_targetForward.y < (showIndicatorAngle / 90f)) || (zAngle < showIndicatorAngle)) { foreach (ComponentsIndication ci in compInd) { ci.LineIndicator.SetActive(false); ci.DestObject.SetActive(false); } return; } if (hideIndicatorByRoll) { if (xAngle > 90.0f) //if ((_targetRight.x < 0f) || (xAngle > 90f)) { foreach (ComponentsIndication ci in compInd) { ci.LineIndicator.SetActive (false); ci.DestObject.SetActive (false); } return; } } foreach (ComponentsIndication ci in compInd) { if (ci.LineIndicator != null) { ci.LineIndicator.SetActive(true); } if (ci.DestObject != null) { ci.DestObject.SetActive(true); if (ci.followButtonRoration == false) { ci.LineIndicator.transform.position = ci.SourceObject.transform.position + ci.Offset; if (ci.alignment == ButtonIndication.Alignment.RIGHT) { ci.DestObject.transform.position = new Vector3(transform.position.x + lineLength, ci.SourceObject.transform.position.y, ci.SourceObject.transform.position.z) + ci.Offset; } else { ci.DestObject.transform.position = new Vector3(transform.position.x - lineLength, ci.SourceObject.transform.position.y, ci.SourceObject.transform.position.z) + ci.Offset; TextMesh[] texts = ci.DestObject.GetComponentsInChildren<TextMesh>(); foreach (TextMesh tm in texts) { if (tm != null) { tm.anchor = TextAnchor.MiddleRight; tm.alignment = TextAlignment.Right; } } } Transform[] transforms = ci.DestObject.GetComponentsInChildren<Transform>(); foreach (Transform tf in transforms) { if (tf != null) { tf.rotation = Quaternion.identity; } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using hw.DebugFormatter; using hw.Helper; using Reni.Feature; namespace Reni.Type { static class ConversionService { internal sealed class ClosureService { TypeBase Source { get; } readonly List<TypeBase> FoundTypes = new(); readonly ValueCache<List<ConversionPath>> NewPathsCache; ClosureService(TypeBase source) { Source = source; NewPathsCache = new(() => new()); } internal static IEnumerable<ConversionPath> Result(TypeBase source) => new ClosureService(source).Result(); IEnumerable<ConversionPath> ExtendPathByOneConversionAndCollect(ConversionPath startFeature = null) { var startType = startFeature?.Destination ?? Source; var newFeatures = startType .NextConversionStepOptions .Where(IsRelevantForConversionPathExtension) .Select(feature => startFeature + feature) .ToArray(); newFeatures.All(item => item.Source == Source).Assert(); NewPathsCache.Value.AddRange(newFeatures); FoundTypes.AddRange(newFeatures.Select(item => item.Destination)); return newFeatures; } bool IsRelevantForConversionPathExtension(IConversion feature) { var resultType = feature.ResultType(); return !(resultType == null || FoundTypes.Contains(resultType)); } IEnumerable<ConversionPath> Result() { NewPathsCache.IsValid = false; var singularPath = new ConversionPath(Source); NewPathsCache.Value.Add(singularPath); FoundTypes.Add(singularPath.Destination); (singularPath.Source == Source).Assert(); var results = new List<ConversionPath> { singularPath }; while(NewPathsCache.IsValid && NewPathsCache.Value.Any()) { var features = NewPathsCache.Value; NewPathsCache.IsValid = false; var newResults = features.SelectMany(ExtendPathByOneConversionAndCollect); results.AddRange(newResults); } return results.ToArray(); } } abstract class ConversionProcess : DumpableObject { TypeBase Source { get; } protected ConversionProcess(TypeBase source) => Source = source; protected abstract IEnumerable<ConversionPath> GetForcedConversions(ConversionPath left); protected abstract bool IsDestination(TypeBase source); internal ConversionPath Result { get { if(IsDestination(Source)) return SimplePath; var paths = ClosureService.Result(Source); if(paths == null) return new(); var others = new List<ConversionPath>(); foreach(var path in paths) { if(IsDestination(path.Destination)) return path; others.Add(path); } var results = others .SelectMany(GetForcedConversions) .ToArray(); var length = results.Min(path => (int?)path.Elements.Length); return results.SingleOrDefault(path => path.Elements.Length == length); } } ConversionPath SimplePath => new(Source); } sealed class GenericConversionProcess : ConversionProcess { readonly Func<TypeBase, bool> IsDestinationCache; public GenericConversionProcess(TypeBase source, Func<TypeBase, bool> isDestination) : base(source) => IsDestinationCache = isDestination; protected override IEnumerable<ConversionPath> GetForcedConversions(ConversionPath left) => left + left.Destination.GetForcedConversions(IsDestinationCache); protected override bool IsDestination(TypeBase source) => IsDestinationCache(source); } sealed class ExplicitConversionProcess : ConversionProcess { TypeBase Destination { get; } public ExplicitConversionProcess(TypeBase source, TypeBase destination) : base(source) => Destination = destination; protected override IEnumerable<ConversionPath> GetForcedConversions(ConversionPath left) => Destination .SymmetricPathsClosureBackwards() .SelectMany (right => left + left.Destination.GetForcedConversions(right.Source) + right); protected override bool IsDestination(TypeBase source) => source == Destination; } internal static ConversionPath FindPath(TypeBase source, TypeBase destination) => new ExplicitConversionProcess(source, destination).Result; static ConversionPath FindPath(TypeBase source, Func<TypeBase, bool> isDestination) => new GenericConversionProcess(source, isDestination).Result; internal static IEnumerable<TDestination> FindPathDestination<TDestination>(TypeBase source) where TDestination : TypeBase { var path = FindPath(source, t => t is TDestination); if(path == null) return Enumerable.Empty<TDestination>(); return path.IsValid? new[] { (TDestination)path.Destination } : null; } internal static IEnumerable<IConversion> ForcedConversions (ConversionPath source, ConversionPath destination) => source.Destination .GetForcedConversions(destination.Source); internal static IEnumerable<ConversionPath> CloseRelativeConversions(this TypeBase source) { var paths = ClosureService.Result(source); return paths.Where(path => path.Elements.Any()); } internal static IEnumerable<IConversion> SymmetricFeatureClosure(this TypeBase source) { var result = RawSymmetricFeatureClosure(source).ToArray(); result.IsSymmetric().Assert (() => result.Select ( path => new { source = path.Source.DumpPrintText, destination = path.ResultType().DumpPrintText } ) .Stringify("\n") ); return result; } static bool IsSymmetric(this IConversion[] list) { if(!list.Any()) return true; var x = list .Types() .Select (t => t.RawSymmetricFeatureClosure().Types().OrderBy(f => f.ObjectId).Count()) .ToArray(); var y = x.Distinct().ToArray(); return y.Length == 1 && x.Length == y.Single(); } internal static IEnumerable<TypeBase> Types(this IEnumerable<IConversion> list) => list .SelectMany(i => new[] { i.Source, i.ResultType() }) .Distinct(); static void AssertPath(this IReadOnlyList<IConversion> elements) { var features = elements .Skip(1) .Select ( (element, i) => new { i, result = elements[i].ResultType(), next = element.Source }) .Where(item => item.result != item.next) .ToArray(); (!features.Any()).Assert(features.Stringify("\n")); } internal static IEnumerable<IConversion> RemoveCircles (this IEnumerable<IConversion> list) { var result = new List<IConversion>(list); result.AssertPath(); if(!result.Any()) return list; var source = result.First().Source; if(source == result.Last().ResultType()) return new IConversion[0]; for(var i = 0; i < result.Count; i++) { var s = result[i].Source; var simpleFeatures = result.Skip(i + 1) .Reverse() .SkipWhile(element => element.Source != s) .ToArray(); var tailLength = simpleFeatures.Length; if(tailLength != 0) result.RemoveRange(i, result.Count - i - tailLength); (source == result.First().Source).Assert(); } return result; } static IEnumerable<IConversion> RawSymmetricFeatureClosure(this TypeBase source) { var types = new TypeBase[0]; var newTypes = new[] { source }; do { types = types.Union(newTypes).ToArray(); var newElements = newTypes .SelectMany(type => type.SymmetricConversions) .ToArray(); foreach(var element in newElements) yield return element; newTypes = newElements .Select(element => element.ResultType()) .Except(types) .ToArray(); } while(newTypes.Any()); } internal static IEnumerable<ConversionPath> SymmetricPathsClosure(this TypeBase source) => new[] { new ConversionPath(source) }.Concat (source.SymmetricClosureConversions.Select(f => new ConversionPath(f))); internal static IEnumerable<ConversionPath> SymmetricPathsClosureBackwards (this TypeBase destination) => new[] { new ConversionPath(destination) }.Concat (SymmetricClosureService.To(destination).Select(f => new ConversionPath(f))); internal static IEnumerable<SearchResult> RemoveLowPriorityResults (this IEnumerable<SearchResult> list) => list.FrameElementList((a, b) => a.HasHigherPriority(b)); static IEnumerable<T> FrameElementList<T> (this IEnumerable<T> list, Func<T, T, bool> isInRelation) { var l = list.ToArray(); return l.Where(item => l.All(other => other.Equals(item) || !isInRelation(other, item))); } } }
// 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. /*============================================================ ** ** ** Purpose: part of ComEventHelpers APIs which allow binding ** managed delegates to COM's connection point based events. ** **/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; namespace System.Runtime.InteropServices { // see code:ComEventsHelper#ComEventsArchitecture internal class ComEventsMethod { // This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's // existence is that under certain circumstances we need to coerce arguments to types expected by the // delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion // correctly but one known case is when the expected signature is 'ref Enum' - in this case // reflection by design does not do the coercion. Since we need to be compatible with COM interop // handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums' // and cache the types required for such coercion. internal class DelegateWrapper { private Delegate _d; private bool _once = false; private int _expectedParamsCount; private Type[] _cachedTargetTypes; public DelegateWrapper(Delegate d) { _d = d; } public Delegate Delegate { get { return _d; } set { _d = value; } } public object Invoke(object[] args) { if (_d == null) return null; if (_once == false) { PreProcessSignature(); _once = true; } if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) { for (int i = 0; i < _expectedParamsCount; i++) { if (_cachedTargetTypes[i] != null) { args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]); } } } return _d.DynamicInvoke(args); } private void PreProcessSignature() { ParameterInfo[] parameters = _d.Method.GetParameters(); _expectedParamsCount = parameters.Length; Type[] enumTypes = new Type[_expectedParamsCount]; bool needToHandleCoercion = false; for (int i = 0; i < _expectedParamsCount; i++) { ParameterInfo pi = parameters[i]; // recognize only 'ref Enum' signatures and cache // both enum type and the underlying type. if (pi.ParameterType.IsByRef && pi.ParameterType.HasElementType && pi.ParameterType.GetElementType().IsEnum) { needToHandleCoercion = true; enumTypes[i] = pi.ParameterType.GetElementType(); } } if (needToHandleCoercion == true) { _cachedTargetTypes = enumTypes; } } } #region private fields /// <summary> /// Invoking ComEventsMethod means invoking a multi-cast delegate attached to it. /// Since multicast delegate's built-in chaining supports only chaining instances of the same type, /// we need to complement this design by using an explicit linked list data structure. /// </summary> private DelegateWrapper [] _delegateWrappers; private int _dispid; private ComEventsMethod _next; #endregion #region ctor internal ComEventsMethod(int dispid) { _delegateWrappers = null; _dispid = dispid; } #endregion #region static internal methods internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) { while (methods != null && methods._dispid != dispid) { methods = methods._next; } return methods; } internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) { method._next = methods; return method; } internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) { if (methods == method) { methods = methods._next; } else { ComEventsMethod current = methods; while (current != null && current._next != method) current = current._next; if (current != null) current._next = method._next; } return methods; } #endregion #region public properties / methods internal int DispId { get { return _dispid; } } internal bool Empty { get { return _delegateWrappers == null || _delegateWrappers.Length == 0; } } internal void AddDelegate(Delegate d) { int count = 0; if (_delegateWrappers != null) { count = _delegateWrappers.Length; } for (int i = 0; i < count; i++) { if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { _delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d); return; } } DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1]; if (count > 0) { _delegateWrappers.CopyTo(newDelegateWrappers, 0); } DelegateWrapper wrapper = new DelegateWrapper(d); newDelegateWrappers[count] = wrapper; _delegateWrappers = newDelegateWrappers; } internal void RemoveDelegate(Delegate d) { int count = _delegateWrappers.Length; int removeIdx = -1; for (int i = 0; i < count; i++) { if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { removeIdx = i; break; } } if (removeIdx < 0) return; Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d); if (newDelegate != null) { _delegateWrappers[removeIdx].Delegate = newDelegate; return; } // now remove the found entry from the _delegates array if (count == 1) { _delegateWrappers = null; return; } DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1]; int j = 0; while (j < removeIdx) { newDelegateWrappers[j] = _delegateWrappers[j]; j++; } while (j < count-1) { newDelegateWrappers[j] = _delegateWrappers[j + 1]; j++; } _delegateWrappers = newDelegateWrappers; } internal object Invoke(object[] args) { BCLDebug.Assert(Empty == false, "event sink is executed but delegates list is empty"); // Issue: see code:ComEventsHelper#ComEventsRetValIssue object result = null; DelegateWrapper[] invocationList = _delegateWrappers; foreach (DelegateWrapper wrapper in invocationList) { if (wrapper == null || wrapper.Delegate == null) continue; result = wrapper.Invoke(args); } return result; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Services; using NUnit.Framework; /// <summary> /// Services tests. /// </summary> public class ServicesTest { /** */ private const string SvcName = "Service1"; /** */ private const string CacheName = "cache1"; /** */ private const int AffKey = 25; /** */ protected IIgnite Grid1; /** */ protected IIgnite Grid2; /** */ protected IIgnite Grid3; /** */ protected IIgnite[] Grids; [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); EventsTestHelper.ListenResult = true; } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { Services.Cancel(SvcName); TestUtils.AssertHandleRegistryIsEmpty(1000, Grid1, Grid2, Grid3); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { EventsTestHelper.AssertFailures(); if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests deployment. /// </summary> [Test] public void TestDeploy([Values(true, false)] bool portable) { var cfg = new ServiceConfiguration { Name = SvcName, MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.Cluster.LocalNode.Id}, Service = portable ? new TestIgniteServicePortable() : new TestIgniteServiceSerializable() }; Services.Deploy(cfg); CheckServiceStarted(Grid1, 3); } /// <summary> /// Tests cluster singleton deployment. /// </summary> [Test] public void TestDeployClusterSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployClusterSingleton(SvcName, svc); var svc0 = Services.GetServiceProxy<ITestIgniteService>(SvcName); // Check that only one node has the service. foreach (var grid in Grids) { if (grid.Cluster.LocalNode.Id == svc0.NodeId) CheckServiceStarted(grid); else Assert.IsNull(grid.Services().GetService<TestIgniteServiceSerializable>(SvcName)); } } /// <summary> /// Tests node singleton deployment. /// </summary> [Test] public void TestDeployNodeSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployNodeSingleton(SvcName, svc); Assert.AreEqual(1, Grid1.Services().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(1, Grid2.Services().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(1, Grid3.Services().GetServices<ITestIgniteService>(SvcName).Count); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingleton() { var svc = new TestIgniteServicePortable(); Services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, AffKey); var affNode = Grid1.Affinity(CacheName).MapKeyToNode(AffKey); var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(affNode.Id, prx.NodeId); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingletonPortable() { var services = Services.WithKeepPortable(); var svc = new TestIgniteServicePortable(); var affKey = new PortableObject {Val = AffKey}; services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, affKey); var prx = services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.IsTrue(prx.Initialized); } /// <summary> /// Tests multiple deployment. /// </summary> [Test] public void TestDeployMultiple() { var svc = new TestIgniteServiceSerializable(); Services.DeployMultiple(SvcName, svc, Grids.Length * 5, 5); foreach (var grid in Grids) CheckServiceStarted(grid, 5); } /// <summary> /// Tests cancellation. /// </summary> [Test] public void TestCancel() { for (var i = 0; i < 10; i++) { Services.DeployNodeSingleton(SvcName + i, new TestIgniteServicePortable()); Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); } Services.Cancel(SvcName + 0); Services.Cancel(SvcName + 1); Assert.IsNull(Services.GetService<ITestIgniteService>(SvcName + 0)); Assert.IsNull(Services.GetService<ITestIgniteService>(SvcName + 1)); for (var i = 2; i < 10; i++) Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); Services.CancelAll(); for (var i = 0; i < 10; i++) Assert.IsNull(Services.GetService<ITestIgniteService>(SvcName + i)); } /// <summary> /// Tests service proxy. /// </summary> [Test] public void TestGetServiceProxy([Values(true, false)] bool portable) { // Test proxy without a service var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.IsTrue(prx != null); var ex = Assert.Throws<ServiceInvocationException>(() => Assert.IsTrue(prx.Initialized)).InnerException; Assert.AreEqual("Failed to find deployed service: " + SvcName, ex.Message); // Deploy to grid2 & grid3 var svc = portable ? new TestIgniteServicePortable {TestProperty = 17} : new TestIgniteServiceSerializable {TestProperty = 17}; Grid1.Cluster.ForNodeIds(Grid2.Cluster.LocalNode.Id, Grid3.Cluster.LocalNode.Id).Services() .DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid1 Assert.IsNull(Services.GetService<ITestIgniteService>(SvcName)); // Get proxy prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); // Check proxy properties Assert.IsNotNull(prx); Assert.AreEqual(prx.GetType(), svc.GetType()); Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual(17, prx.TestProperty); Assert.IsTrue(prx.Initialized); Assert.IsTrue(prx.Executed); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Check err method Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); // Check local scenario (proxy should not be created for local instance) Assert.IsTrue(ReferenceEquals(Grid2.Services().GetService<ITestIgniteService>(SvcName), Grid2.Services().GetServiceProxy<ITestIgniteService>(SvcName))); // Check sticky = false: call multiple times, check that different nodes get invoked var invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(2, invokedIds.Count); // Check sticky = true: all calls should be to the same node prx = Services.GetServiceProxy<ITestIgniteService>(SvcName, true); invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(1, invokedIds.Count); // Proxy does not work for cancelled service. Services.CancelAll(); Assert.Throws<ServiceInvocationException>(() => { Assert.IsTrue(prx.Cancelled); }); } /// <summary> /// Tests the duck typing: proxy interface can be different from actual service interface, /// only called method signature should be compatible. /// </summary> [Test] public void TestDuckTyping([Values(true, false)] bool local) { var svc = new TestIgniteServicePortable {TestProperty = 33}; // Deploy locally or to the remote node var nodeId = (local ? Grid1 : Grid2).Cluster.LocalNode.Id; var cluster = Grid1.Cluster.ForNodeIds(nodeId); cluster.Services().DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.GetServiceProxy<ITestIgniteServiceProxyInterface>(SvcName); // NodeId signature is the same as in service Assert.AreEqual(nodeId, prx.NodeId); // Method signature is different from service signature (object -> object), but is compatible. Assert.AreEqual(15, prx.Method(15)); // TestProperty is object in proxy and int in service, getter works.. Assert.AreEqual(33, prx.TestProperty); // .. but setter does not var ex = Assert.Throws<ServiceInvocationException>(() => { prx.TestProperty = new object(); }); Assert.AreEqual("Object of type 'System.Object' cannot be converted to type 'System.Int32'.", ex.InnerException.Message); } /// <summary> /// Tests service descriptors. /// </summary> [Test] public void TestServiceDescriptors() { Services.DeployKeyAffinitySingleton(SvcName, new TestIgniteServiceSerializable(), CacheName, 1); var descriptors = Services.GetServiceDescriptors(); Assert.AreEqual(1, descriptors.Count); var desc = descriptors.Single(); Assert.AreEqual(SvcName, desc.Name); Assert.AreEqual(CacheName, desc.CacheName); Assert.AreEqual(1, desc.AffinityKey); Assert.AreEqual(1, desc.MaxPerNodeCount); Assert.AreEqual(1, desc.TotalCount); Assert.AreEqual(typeof(TestIgniteServiceSerializable), desc.Type); Assert.AreEqual(Grid1.Cluster.LocalNode.Id, desc.OriginNodeId); var top = desc.TopologySnapshot; var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(1, top.Count); Assert.AreEqual(prx.NodeId, top.Keys.Single()); Assert.AreEqual(1, top.Values.Single()); } /// <summary> /// Tests the client portable flag. /// </summary> [Test] public void TestWithKeepPortableClient() { var svc = new TestIgniteServicePortable(); // Deploy to grid2 Grid1.Cluster.ForNodeIds(Grid2.Cluster.LocalNode.Id).Services().WithKeepPortable() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepPortable().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new PortableObject {Val = 11}; var res = (IPortableObject) prx.Method(obj); Assert.AreEqual(11, res.Deserialize<PortableObject>().Val); res = (IPortableObject) prx.Method(Grid1.Portables().ToPortable<IPortableObject>(obj)); Assert.AreEqual(11, res.Deserialize<PortableObject>().Val); } /// <summary> /// Tests the server portable flag. /// </summary> [Test] public void TestWithKeepPortableServer() { var svc = new TestIgniteServicePortable(); // Deploy to grid2 Grid1.Cluster.ForNodeIds(Grid2.Cluster.LocalNode.Id).Services().WithServerKeepPortable() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithServerKeepPortable().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new PortableObject { Val = 11 }; var res = (PortableObject) prx.Method(obj); Assert.AreEqual(11, res.Val); res = (PortableObject)prx.Method(Grid1.Portables().ToPortable<IPortableObject>(obj)); Assert.AreEqual(11, res.Val); } /// <summary> /// Tests server and client portable flag. /// </summary> [Test] public void TestWithKeepPortableBoth() { var svc = new TestIgniteServicePortable(); // Deploy to grid2 Grid1.Cluster.ForNodeIds(Grid2.Cluster.LocalNode.Id).Services().WithKeepPortable().WithServerKeepPortable() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepPortable().WithServerKeepPortable().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new PortableObject { Val = 11 }; var res = (IPortableObject)prx.Method(obj); Assert.AreEqual(11, res.Deserialize<PortableObject>().Val); res = (IPortableObject)prx.Method(Grid1.Portables().ToPortable<IPortableObject>(obj)); Assert.AreEqual(11, res.Deserialize<PortableObject>().Val); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestInitException() { var svc = new TestIgniteServiceSerializable { ThrowInit = true }; var ex = Assert.Throws<IgniteException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in Execute. /// </summary> [Test] public void TestExecuteException() { var svc = new TestIgniteServiceSerializable { ThrowExecute = true }; Services.DeployMultiple(SvcName, svc, Grids.Length, 1); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); // Execution failed, but service exists. Assert.IsNotNull(svc0); Assert.IsFalse(svc0.Executed); } /// <summary> /// Tests exception in Cancel. /// </summary> [Test] public void TestCancelException() { var svc = new TestIgniteServiceSerializable { ThrowCancel = true }; Services.DeployMultiple(SvcName, svc, Grids.Length, 1); CheckServiceStarted(Grid1); Services.CancelAll(); // Cancellation failed, but service is removed. foreach (var grid in Grids) Assert.IsNull(grid.Services().GetService<ITestIgniteService>(SvcName)); } [Test] public void TestMarshalExceptionOnRead() { var svc = new TestIgniteServicePortableErr(); var ex = Assert.Throws<IgniteException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } [Test] public void TestMarshalExceptionOnWrite() { var svc = new TestIgniteServicePortableErr {ThrowOnWrite = true}; var ex = Assert.Throws<Exception>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (Grid1 != null) return; Grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml")); Grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml")); Grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml")); Grids = new[] { Grid1, Grid2, Grid3 }; } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { Grid1 = Grid2 = Grid3 = null; Grids = null; Ignition.StopAll(true); } /// <summary> /// Checks that service has started on specified grid. /// </summary> private static void CheckServiceStarted(IIgnite grid, int count = 1) { var services = grid.Services().GetServices<TestIgniteServiceSerializable>(SvcName); Assert.AreEqual(count, services.Count); var svc = services.First(); Assert.IsNotNull(svc); Assert.IsTrue(svc.Initialized); Thread.Sleep(100); // Service runs in a separate thread, wait for it to execute. Assert.IsTrue(svc.Executed); Assert.IsFalse(svc.Cancelled); Assert.AreEqual(grid.Cluster.LocalNode.Id, svc.NodeId); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration Configuration(string springConfigUrl) { return new IgniteConfiguration { SpringConfigUrl = springConfigUrl, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), PortableConfiguration = new PortableConfiguration { TypeConfigurations = new List<PortableTypeConfiguration> { new PortableTypeConfiguration(typeof(TestIgniteServicePortable)), new PortableTypeConfiguration(typeof(TestIgniteServicePortableErr)), new PortableTypeConfiguration(typeof(PortableObject)) } } }; } /// <summary> /// Gets the services. /// </summary> protected virtual IServices Services { get { return Grid1.Services(); } } /// <summary> /// Test service interface for proxying. /// </summary> private interface ITestIgniteService { int TestProperty { get; set; } /** */ bool Initialized { get; } /** */ bool Cancelled { get; } /** */ bool Executed { get; } /** */ Guid NodeId { get; } /** */ string LastCallContextName { get; } /** */ object Method(object arg); /** */ object ErrMethod(object arg); } /// <summary> /// Test service interface for proxy usage. /// Has some of the original interface members with different signatures. /// </summary> private interface ITestIgniteServiceProxyInterface { /** */ Guid NodeId { get; } /** */ object TestProperty { get; set; } /** */ int Method(int arg); } #pragma warning disable 649 /// <summary> /// Test serializable service. /// </summary> [Serializable] private class TestIgniteServiceSerializable : IService, ITestIgniteService { /** */ [InstanceResource] private IIgnite _grid; /** <inheritdoc /> */ public int TestProperty { get; set; } /** <inheritdoc /> */ public bool Initialized { get; private set; } /** <inheritdoc /> */ public bool Cancelled { get; private set; } /** <inheritdoc /> */ public bool Executed { get; private set; } /** <inheritdoc /> */ public Guid NodeId { get { return _grid.Cluster.LocalNode.Id; } } /** <inheritdoc /> */ public string LastCallContextName { get; private set; } /** */ public bool ThrowInit { get; set; } /** */ public bool ThrowExecute { get; set; } /** */ public bool ThrowCancel { get; set; } /** */ public object Method(object arg) { return arg; } /** */ public object ErrMethod(object arg) { throw new ArgumentNullException("arg", "ExpectedException"); } /** <inheritdoc /> */ public void Init(IServiceContext context) { if (ThrowInit) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Initialized = true; } /** <inheritdoc /> */ public void Execute(IServiceContext context) { if (ThrowExecute) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Assert.IsTrue(Initialized); Assert.IsFalse(Cancelled); Executed = true; } /** <inheritdoc /> */ public void Cancel(IServiceContext context) { if (ThrowCancel) throw new Exception("Expected exception"); CheckContext(context); Assert.IsTrue(context.IsCancelled); Cancelled = true; } /// <summary> /// Checks the service context. /// </summary> private void CheckContext(IServiceContext context) { LastCallContextName = context.Name; if (context.AffinityKey != null && !(context.AffinityKey is int)) { var portableObject = context.AffinityKey as IPortableObject; var key = portableObject != null ? portableObject.Deserialize<PortableObject>() : (PortableObject) context.AffinityKey; Assert.AreEqual(AffKey, key.Val); } Assert.IsNotNull(_grid); Assert.IsTrue(context.Name.StartsWith(SvcName)); Assert.AreNotEqual(Guid.Empty, context.ExecutionId); } } /// <summary> /// Test portable service. /// </summary> private class TestIgniteServicePortable : TestIgniteServiceSerializable, IPortableMarshalAware { /** <inheritdoc /> */ public void WritePortable(IPortableWriter writer) { writer.WriteInt("TestProp", TestProperty); } /** <inheritdoc /> */ public void ReadPortable(IPortableReader reader) { TestProperty = reader.ReadInt("TestProp"); } } /// <summary> /// Test portable service with exceptions in marshalling. /// </summary> private class TestIgniteServicePortableErr : TestIgniteServiceSerializable, IPortableMarshalAware { /** */ public bool ThrowOnWrite { get; set; } /** <inheritdoc /> */ public void WritePortable(IPortableWriter writer) { writer.WriteInt("TestProp", TestProperty); if (ThrowOnWrite) throw new Exception("Expected exception"); } /** <inheritdoc /> */ public void ReadPortable(IPortableReader reader) { TestProperty = reader.ReadInt("TestProp"); throw new Exception("Expected exception"); } } /// <summary> /// Test node filter. /// </summary> [Serializable] private class NodeFilter : IClusterNodeFilter { /// <summary> /// Gets or sets the node identifier. /// </summary> public Guid NodeId { get; set; } /** <inheritdoc /> */ public bool Invoke(IClusterNode node) { return node.Id == NodeId; } } /// <summary> /// Portable object. /// </summary> private class PortableObject { public int Val { get; set; } } } }