context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class ContentRangeHeaderValue : ICloneable { private string _unit; private long? _from; private long? _to; private long? _length; public string Unit { get { return _unit; } set { HeaderUtilities.CheckValidToken(value, "value"); _unit = value; } } public long? From { get { return _from; } } public long? To { get { return _to; } } public long? Length { get { return _length; } } public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { get { return _length != null; } } public bool HasRange // e.g. "Content-Range: bytes */1234" { get { return _from != null; } } public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" if (to < 0) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _unit = HeaderUtilities.BytesUnit; } private ContentRangeHeaderValue() { } private ContentRangeHeaderValue(ContentRangeHeaderValue source) { Contract.Requires(source != null); _from = source._from; _to = source._to; _length = source._length; _unit = source._unit; } public override bool Equals(object obj) { ContentRangeHeaderValue other = obj as ContentRangeHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to) && (_length == other._length) && string.Equals(_unit, other._unit, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_unit); if (HasRange) { result = result ^ _from.GetHashCode() ^ _to.GetHashCode(); } if (HasLength) { result = result ^ _length.GetHashCode(); } return result; } public override string ToString() { StringBuilder sb = new StringBuilder(_unit); sb.Append(' '); if (HasRange) { sb.Append(_from.Value.ToString(NumberFormatInfo.InvariantInfo)); sb.Append('-'); sb.Append(_to.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } sb.Append('/'); if (HasLength) { sb.Append(_length.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } return sb.ToString(); } public static ContentRangeHeaderValue Parse(string input) { int index = 0; return (ContentRangeHeaderValue)GenericHeaderParser.ContentRangeParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out ContentRangeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.ContentRangeParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (ContentRangeHeaderValue)output; return true; } return false; } internal static int GetContentRangeLength(string input, int startIndex, out object parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' int unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return 0; } string unit = input.Substring(startIndex, unitLength); int current = startIndex + unitLength; int separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return 0; } current = current + separatorLength; if (current == input.Length) { return 0; } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' int fromStartIndex = current; int fromLength = 0; int toStartIndex = 0; int toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return 0; } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return 0; } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. int lengthStartIndex = current; int lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return 0; } return current - startIndex; } private static bool TryGetLengthLength(string input, ref int current, out int lengthLength) { lengthLength = 0; if (input[current] == '*') { current++; } else { // Parse length value: <length> in '<unit> <from>-<to>/<length>' lengthLength = HttpRuleParser.GetNumberLength(input, current, false); if ((lengthLength == 0) || (lengthLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + lengthLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryGetRangeLength(string input, ref int current, out int fromLength, out int toStartIndex, out int toLength) { fromLength = 0; toStartIndex = 0; toLength = 0; // Check if we have a value like 'bytes */133'. If yes, skip the range part and continue parsing the // length separator '/'. if (input[current] == '*') { current++; } else { // Parse first range value: <from> in '<unit> <from>-<to>/<length>' fromLength = HttpRuleParser.GetNumberLength(input, current, false); if ((fromLength == 0) || (fromLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // After the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return false; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } // Parse second range value: <to> in '<unit> <from>-<to>/<length>' toStartIndex = current; toLength = HttpRuleParser.GetNumberLength(input, current, false); if ((toLength == 0) || (toLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + toLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryCreateContentRange(string input, string unit, int fromStartIndex, int fromLength, int toStartIndex, int toLength, int lengthStartIndex, int lengthLength, out object parsedValue) { parsedValue = null; long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from)) { return false; } long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to)) { return false; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return false; } long length = 0; if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(lengthStartIndex, lengthLength), out length)) { return false; } // 'from' and 'to' must be less than 'length' if ((toLength > 0) && (lengthLength > 0) && (to >= length)) { return false; } ContentRangeHeaderValue result = new ContentRangeHeaderValue(); result._unit = unit; if (fromLength > 0) { result._from = from; result._to = to; } if (lengthLength > 0) { result._length = length; } parsedValue = result; return true; } object ICloneable.Clone() { return new ContentRangeHeaderValue(this); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Trifolia.Web.Areas.HelpPage.ModelDescriptions; using Trifolia.Web.Areas.HelpPage.Models; namespace Trifolia.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); // SPM: Changed to ignore FHIR2 sample generations because of bug in FHIR2 library generating stack overflow exceptions if (!apiDescription.ID.Contains("FHIR2") && !apiDescription.ID.Contains("FHIR3")) GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (C) 2012-2014 DataStax 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; namespace Cassandra { /// <summary> /// Options related to connection pooling. <p> The driver uses connections in an /// asynchronous way. Meaning that multiple requests can be submitted on the same /// connection at the same time. This means that the driver only needs to /// maintain a relatively small number of connections to each Cassandra host. /// These options allow to control how many connections are kept exactly. </p><p> For /// each host, the driver keeps a core amount of connections open at all time /// (<link>PoolingOptions#getCoreConnectionsPerHost</link>). If the utilization /// of those connections reaches a configurable threshold /// (<link>PoolingOptions#getMaxSimultaneousRequestsPerConnectionTreshold</link>), /// more connections are created up to a configurable maximum number of /// connections (<link>PoolingOptions#getMaxConnectionPerHost</link>). Once more /// than core connections have been created, connections in excess are reclaimed /// if the utilization of opened connections drops below the configured threshold /// (<link>PoolingOptions#getMinSimultaneousRequestsPerConnectionTreshold</link>). /// </p><p> Each of these parameters can be separately set for <c>Local</c> and /// <c>Remote</c> hosts (<link>HostDistance</link>). For /// <c>Ignored</c> hosts, the default for all those settings is 0 and /// cannot be changed.</p> /// </summary> public class PoolingOptions { //the defaults target small number concurrent requests (protocol 1 and 2) and multiple connections to a host private const int DefaultMinRequests = 25; private const int DefaultMaxRequests = 128; private const int DefaultCorePoolLocal = 2; private const int DefaultCorePoolRemote = 1; private const int DefaultMaxPoolLocal = 8; private const int DefaultMaxPoolRemote = 2; private int _coreConnectionsForLocal = DefaultCorePoolLocal; private int _coreConnectionsForRemote = DefaultCorePoolRemote; private int _maxConnectionsForLocal = DefaultMaxPoolLocal; private int _maxConnectionsForRemote = DefaultMaxPoolRemote; private int _maxSimultaneousRequestsForLocal = DefaultMaxRequests; private int _maxSimultaneousRequestsForRemote = DefaultMaxRequests; private int _minSimultaneousRequestsForLocal = DefaultMinRequests; private int _minSimultaneousRequestsForRemote = DefaultMinRequests; private int? _heartBeatInterval; /// <summary> /// Number of simultaneous requests on a connection below which connections in /// excess are reclaimed. <p> If an opened connection to an host at distance /// <c>distance</c> handles less than this number of simultaneous requests /// and there is more than <link>#GetCoreConnectionsPerHost</link> connections /// open to this host, the connection is closed. </p><p> The default value for this /// option is 25 for <c>Local</c> and <c>Remote</c> hosts.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param> /// <returns>the configured threshold, or the default one if none have been set.</returns> public int GetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance) { switch (distance) { case HostDistance.Local: return _minSimultaneousRequestsForLocal; case HostDistance.Remote: return _minSimultaneousRequestsForRemote; default: return 0; } } /// <summary> /// Sets the number of simultaneous requests on a connection below which /// connections in excess are reclaimed. /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to configure this /// threshold. </param> /// <param name="minSimultaneousRequests"> the value to set. </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> public PoolingOptions SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int minSimultaneousRequests) { switch (distance) { case HostDistance.Local: _minSimultaneousRequestsForLocal = minSimultaneousRequests; break; case HostDistance.Remote: _minSimultaneousRequestsForRemote = minSimultaneousRequests; break; default: throw new ArgumentOutOfRangeException("Cannot set min streams per connection threshold for " + distance + " hosts"); } return this; } /// <summary> /// Number of simultaneous requests on all connections to an host after which /// more connections are created. <p> If all the connections opened to an host at /// distance <c>* distance</c> connection are handling more than this /// number of simultaneous requests and there is less than /// <link>#getMaxConnectionPerHost</link> connections open to this host, a new /// connection is open. </p><p> Note that a given connection cannot handle more than /// 128 simultaneous requests (protocol limitation). </p><p> The default value for /// this option is 100 for <c>Local</c> and <c>Remote</c> hosts.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param> /// <returns>the configured threshold, or the default one if none have been set.</returns> public int GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance) { switch (distance) { case HostDistance.Local: return _maxSimultaneousRequestsForLocal; case HostDistance.Remote: return _maxSimultaneousRequestsForRemote; default: return 0; } } /// <summary> /// Sets number of simultaneous requests on all connections to an host after /// which more connections are created. /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to configure this /// threshold. </param> /// <param name="maxSimultaneousRequests"> the value to set. </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> /// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignore</c>.</throws> public PoolingOptions SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int maxSimultaneousRequests) { switch (distance) { case HostDistance.Local: _maxSimultaneousRequestsForLocal = maxSimultaneousRequests; break; case HostDistance.Remote: _maxSimultaneousRequestsForRemote = maxSimultaneousRequests; break; default: throw new ArgumentOutOfRangeException("Cannot set max streams per connection threshold for " + distance + " hosts"); } return this; } /// <summary> /// The core number of connections per host. <p> For the provided /// <c>distance</c>, this correspond to the number of connections initially /// created and kept open to each host of that distance.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold. /// </param> /// /// <returns>the core number of connections per host at distance /// <c>distance</c>.</returns> public int GetCoreConnectionsPerHost(HostDistance distance) { switch (distance) { case HostDistance.Local: return _coreConnectionsForLocal; case HostDistance.Remote: return _coreConnectionsForRemote; default: return 0; } } /// <summary> /// Sets the core number of connections per host. /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to set this threshold. /// </param> /// <param name="coreConnections"> the value to set </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> /// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignored</c>.</throws> public PoolingOptions SetCoreConnectionsPerHost(HostDistance distance, int coreConnections) { switch (distance) { case HostDistance.Local: _coreConnectionsForLocal = coreConnections; break; case HostDistance.Remote: _coreConnectionsForRemote = coreConnections; break; default: throw new ArgumentOutOfRangeException("Cannot set core connections per host for " + distance + " hosts"); } return this; } /// <summary> /// The maximum number of connections per host. <p> For the provided /// <c>distance</c>, this correspond to the maximum number of connections /// that can be created per host at that distance.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold. /// </param> /// /// <returns>the maximum number of connections per host at distance /// <c>distance</c>.</returns> public int GetMaxConnectionPerHost(HostDistance distance) { switch (distance) { case HostDistance.Local: return _maxConnectionsForLocal; case HostDistance.Remote: return _maxConnectionsForRemote; default: return 0; } } /// <summary> /// Sets the maximum number of connections per host. /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to set this threshold. /// </param> /// <param name="maxConnections"> the value to set </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> public PoolingOptions SetMaxConnectionsPerHost(HostDistance distance, int maxConnections) { switch (distance) { case HostDistance.Local: _maxConnectionsForLocal = maxConnections; break; case HostDistance.Remote: _maxConnectionsForRemote = maxConnections; break; default: throw new ArgumentOutOfRangeException("Cannot set max connections per host for " + distance + " hosts"); } return this; } /// <summary> /// Gets the amount of idle time in milliseconds that has to pass before the driver issues a request on an active connection to avoid idle time disconnections. /// </summary> public int? GetHeartBeatInterval() { return _heartBeatInterval; } /// <summary> /// Sets the amount of idle time in milliseconds that has to pass before the driver issues a request on an active connection to avoid idle time disconnections. /// <remarks>When set to null the heartbeat functionality at connection level is disabled.</remarks> /// </summary> public PoolingOptions SetHeartBeatInterval(int value) { _heartBeatInterval = value; return this; } /// <summary> /// Gets the default protocol options by protocol version /// </summary> internal static PoolingOptions GetDefault(byte protocolVersion) { if (protocolVersion < 3) { //New instance of pooling options with default values return new PoolingOptions(); } else { //New instance of pooling options with default values for high number of concurrent requests return new PoolingOptions() .SetCoreConnectionsPerHost(HostDistance.Local, 1) .SetMaxConnectionsPerHost(HostDistance.Local, 2) .SetMaxConnectionsPerHost(HostDistance.Remote, 1) .SetMaxConnectionsPerHost(HostDistance.Remote, 1) .SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 1500) .SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Remote, 1500); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebApiUniqueConstraintHandling.Areas.HelpPage.ModelDescriptions; using WebApiUniqueConstraintHandling.Areas.HelpPage.Models; namespace WebApiUniqueConstraintHandling.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections; using System.Windows.Forms; using NationalInstruments.UI; using NationalInstruments.UI.WindowsForms; using Data; namespace ScanMaster.GUI { /// <summary> /// </summary> public class StandardViewerWindow : System.Windows.Forms.Form { // this windows associated Viewer private StandardViewer viewer; private System.ComponentModel.Container components = null; private NationalInstruments.UI.WindowsForms.ScatterGraph analog1Graph; private NationalInstruments.UI.XAxis xAxis1; private NationalInstruments.UI.YAxis yAxis1; private NationalInstruments.UI.WindowsForms.ScatterGraph analog2Graph; private NationalInstruments.UI.XAxis xAxis2; private NationalInstruments.UI.YAxis yAxis2; private NationalInstruments.UI.ScatterPlot analog1Plot; private NationalInstruments.UI.ScatterPlot analog2Plot; private NationalInstruments.UI.WindowsForms.ScatterGraph pmtGraph; private NationalInstruments.UI.ScatterPlot pmtOnPlot; private NationalInstruments.UI.XAxis pmtXAxis; private NationalInstruments.UI.YAxis pmtYAxis; private NationalInstruments.UI.XAxis xAxis3; private NationalInstruments.UI.ScatterPlot pmtOffPlot; private NationalInstruments.UI.XYCursor pmtLowCursor; private NationalInstruments.UI.XAxis xAxis5; private NationalInstruments.UI.WindowsForms.ScatterGraph differenceGraph; private NationalInstruments.UI.WindowsForms.WaveformGraph tofGraph; private NationalInstruments.UI.XAxis xAxis4; private NationalInstruments.UI.WaveformPlot tofOnPlot; private NationalInstruments.UI.WaveformPlot tofOffPlot; private NationalInstruments.UI.ScatterPlot differencePlot; private NationalInstruments.UI.ScatterPlot differenceAvgPlot; private NationalInstruments.UI.XYCursor tofLowCursor; private NationalInstruments.UI.XYCursor tofHighCursor; private NationalInstruments.UI.WaveformPlot tofOnAveragePlot; private NationalInstruments.UI.WaveformPlot tofOffAveragePlot; private NationalInstruments.UI.ScatterPlot pmtOnAvgPlot; private NationalInstruments.UI.ScatterPlot pmtOffAvgPlot; private NationalInstruments.UI.YAxis differenceYAxis; private NationalInstruments.UI.YAxis tofYAxis; private NationalInstruments.UI.YAxis tofAvgYAxis; private NationalInstruments.UI.ScatterPlot pmtFitPlot; private System.Windows.Forms.Label label1; public System.Windows.Forms.ComboBox tofFitFunctionCombo; private System.Windows.Forms.Label label2; public ComboBox tofFitModeCombo; public System.Windows.Forms.ComboBox spectrumFitFunctionCombo; public ComboBox spectrumFitModeCombo; public System.Windows.Forms.Label tofFitResultsLabel; public System.Windows.Forms.Label spectrumFitResultsLabel; private WaveformPlot tofFitPlot; private Button updateTOFFitButton; private Button updateSpectrumFitButton; public ComboBox tofFitDataSelectCombo; private SplitContainer splitContainer1; private StatusBar statusBar1; private Label label3; private Button updateNoiseResultsbutton; public Label noiseResultsLabel; private SplitContainer splitContainer2; private StatusBar statusBar2; private Button defaultGateButton; private WaveformGraph tofGraph2; private XYCursor normSigGateLow; private WaveformPlot tofOnAveragePlot2; private XAxis xAxis6; private YAxis yAxis3; private XYCursor normSigGateHigh; private WaveformPlot tofOnPlot2; private YAxis yAxis4; private WaveformPlot tofOffPlot2; private WaveformPlot tofOffAveragePlot2; private WaveformPlot tofFitPlot2; private WaveformGraph tofGraphNormed; private XYCursor xyCursor3; private WaveformPlot tofOnAverageNormedPlot; private XAxis xAxis7; private YAxis yAxis5; private XYCursor xyCursor4; private WaveformPlot tofOnNormedPlot; private YAxis yAxis6; private WaveformPlot tofOffNormedPlot; private WaveformPlot tofOffAverageNormedPlot; private WaveformPlot tofFitNormedPlot; private ToolStripLabel toolStripLabel1; private ToolStripPropertyEditor toolStripPropertyEditor1; private ToolStripLabel toolStripLabel2; private ToolStripPropertyEditor toolStripPropertyEditor2; private ToolStripLabel toolStripLabel3; private ToolStripPropertyEditor toolStripPropertyEditor3; private XYCursor normBgGateLow; private XYCursor normBgGateHigh; private NationalInstruments.UI.XYCursor pmtHighCursor; public StandardViewerWindow(StandardViewer viewer) { this.viewer = viewer; InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StandardViewerWindow)); this.analog1Graph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.analog1Plot = new NationalInstruments.UI.ScatterPlot(); this.xAxis1 = new NationalInstruments.UI.XAxis(); this.yAxis1 = new NationalInstruments.UI.YAxis(); this.analog2Graph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.analog2Plot = new NationalInstruments.UI.ScatterPlot(); this.xAxis2 = new NationalInstruments.UI.XAxis(); this.yAxis2 = new NationalInstruments.UI.YAxis(); this.pmtGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.pmtLowCursor = new NationalInstruments.UI.XYCursor(); this.pmtOnAvgPlot = new NationalInstruments.UI.ScatterPlot(); this.xAxis3 = new NationalInstruments.UI.XAxis(); this.pmtYAxis = new NationalInstruments.UI.YAxis(); this.pmtHighCursor = new NationalInstruments.UI.XYCursor(); this.pmtOnPlot = new NationalInstruments.UI.ScatterPlot(); this.pmtOffPlot = new NationalInstruments.UI.ScatterPlot(); this.pmtOffAvgPlot = new NationalInstruments.UI.ScatterPlot(); this.pmtFitPlot = new NationalInstruments.UI.ScatterPlot(); this.pmtXAxis = new NationalInstruments.UI.XAxis(); this.xAxis5 = new NationalInstruments.UI.XAxis(); this.differenceYAxis = new NationalInstruments.UI.YAxis(); this.differenceGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.differencePlot = new NationalInstruments.UI.ScatterPlot(); this.differenceAvgPlot = new NationalInstruments.UI.ScatterPlot(); this.tofGraph = new NationalInstruments.UI.WindowsForms.WaveformGraph(); this.tofLowCursor = new NationalInstruments.UI.XYCursor(); this.tofOnAveragePlot = new NationalInstruments.UI.WaveformPlot(); this.xAxis4 = new NationalInstruments.UI.XAxis(); this.tofAvgYAxis = new NationalInstruments.UI.YAxis(); this.tofHighCursor = new NationalInstruments.UI.XYCursor(); this.tofOnPlot = new NationalInstruments.UI.WaveformPlot(); this.tofYAxis = new NationalInstruments.UI.YAxis(); this.tofOffPlot = new NationalInstruments.UI.WaveformPlot(); this.tofOffAveragePlot = new NationalInstruments.UI.WaveformPlot(); this.tofFitPlot = new NationalInstruments.UI.WaveformPlot(); this.tofFitModeCombo = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.tofFitFunctionCombo = new System.Windows.Forms.ComboBox(); this.spectrumFitFunctionCombo = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.spectrumFitModeCombo = new System.Windows.Forms.ComboBox(); this.tofFitResultsLabel = new System.Windows.Forms.Label(); this.spectrumFitResultsLabel = new System.Windows.Forms.Label(); this.updateTOFFitButton = new System.Windows.Forms.Button(); this.updateSpectrumFitButton = new System.Windows.Forms.Button(); this.tofFitDataSelectCombo = new System.Windows.Forms.ComboBox(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.statusBar2 = new System.Windows.Forms.StatusBar(); this.defaultGateButton = new System.Windows.Forms.Button(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.label3 = new System.Windows.Forms.Label(); this.updateNoiseResultsbutton = new System.Windows.Forms.Button(); this.noiseResultsLabel = new System.Windows.Forms.Label(); this.tofGraph2 = new NationalInstruments.UI.WindowsForms.WaveformGraph(); this.normSigGateLow = new NationalInstruments.UI.XYCursor(); this.tofOnAveragePlot2 = new NationalInstruments.UI.WaveformPlot(); this.xAxis6 = new NationalInstruments.UI.XAxis(); this.yAxis3 = new NationalInstruments.UI.YAxis(); this.normSigGateHigh = new NationalInstruments.UI.XYCursor(); this.tofOnPlot2 = new NationalInstruments.UI.WaveformPlot(); this.yAxis4 = new NationalInstruments.UI.YAxis(); this.tofOffPlot2 = new NationalInstruments.UI.WaveformPlot(); this.tofOffAveragePlot2 = new NationalInstruments.UI.WaveformPlot(); this.tofFitPlot2 = new NationalInstruments.UI.WaveformPlot(); this.tofGraphNormed = new NationalInstruments.UI.WindowsForms.WaveformGraph(); this.xyCursor3 = new NationalInstruments.UI.XYCursor(); this.tofOnAverageNormedPlot = new NationalInstruments.UI.WaveformPlot(); this.xAxis7 = new NationalInstruments.UI.XAxis(); this.yAxis5 = new NationalInstruments.UI.YAxis(); this.xyCursor4 = new NationalInstruments.UI.XYCursor(); this.tofOnNormedPlot = new NationalInstruments.UI.WaveformPlot(); this.yAxis6 = new NationalInstruments.UI.YAxis(); this.tofOffNormedPlot = new NationalInstruments.UI.WaveformPlot(); this.tofOffAverageNormedPlot = new NationalInstruments.UI.WaveformPlot(); this.tofFitNormedPlot = new NationalInstruments.UI.WaveformPlot(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripPropertyEditor1 = new NationalInstruments.UI.WindowsForms.ToolStripPropertyEditor(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripPropertyEditor2 = new NationalInstruments.UI.WindowsForms.ToolStripPropertyEditor(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripPropertyEditor3 = new NationalInstruments.UI.WindowsForms.ToolStripPropertyEditor(); this.normBgGateLow = new NationalInstruments.UI.XYCursor(); this.normBgGateHigh = new NationalInstruments.UI.XYCursor(); ((System.ComponentModel.ISupportInitialize)(this.analog1Graph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.analog2Graph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtGraph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtLowCursor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtHighCursor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.differenceGraph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tofGraph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tofLowCursor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tofHighCursor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tofGraph2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.normSigGateLow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.normSigGateHigh)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tofGraphNormed)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xyCursor3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xyCursor4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.normBgGateLow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.normBgGateHigh)).BeginInit(); this.SuspendLayout(); // // analog1Graph // this.analog1Graph.Location = new System.Drawing.Point(376, 8); this.analog1Graph.Name = "analog1Graph"; this.analog1Graph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.analog1Plot}); this.analog1Graph.Size = new System.Drawing.Size(584, 126); this.analog1Graph.TabIndex = 0; this.analog1Graph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis1}); this.analog1Graph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis1}); // // analog1Plot // this.analog1Plot.AntiAliased = true; this.analog1Plot.LineColor = System.Drawing.Color.Red; this.analog1Plot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.analog1Plot.LineStyle = NationalInstruments.UI.LineStyle.None; this.analog1Plot.PointColor = System.Drawing.Color.Red; this.analog1Plot.PointStyle = NationalInstruments.UI.PointStyle.SolidDiamond; this.analog1Plot.XAxis = this.xAxis1; this.analog1Plot.YAxis = this.yAxis1; // // xAxis1 // this.xAxis1.Mode = NationalInstruments.UI.AxisMode.Fixed; // // analog2Graph // this.analog2Graph.Location = new System.Drawing.Point(376, 138); this.analog2Graph.Name = "analog2Graph"; this.analog2Graph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.analog2Plot}); this.analog2Graph.Size = new System.Drawing.Size(584, 125); this.analog2Graph.TabIndex = 1; this.analog2Graph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis2}); this.analog2Graph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis2}); // // analog2Plot // this.analog2Plot.AntiAliased = true; this.analog2Plot.LineColor = System.Drawing.Color.Blue; this.analog2Plot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.analog2Plot.LineStyle = NationalInstruments.UI.LineStyle.None; this.analog2Plot.PointColor = System.Drawing.Color.Blue; this.analog2Plot.PointStyle = NationalInstruments.UI.PointStyle.SolidDiamond; this.analog2Plot.XAxis = this.xAxis2; this.analog2Plot.YAxis = this.yAxis2; // // xAxis2 // this.xAxis2.Mode = NationalInstruments.UI.AxisMode.Fixed; // // pmtGraph // this.pmtGraph.Cursors.AddRange(new NationalInstruments.UI.XYCursor[] { this.pmtLowCursor, this.pmtHighCursor}); this.pmtGraph.InteractionMode = ((NationalInstruments.UI.GraphInteractionModes)((((((((NationalInstruments.UI.GraphInteractionModes.ZoomX | NationalInstruments.UI.GraphInteractionModes.ZoomY) | NationalInstruments.UI.GraphInteractionModes.ZoomAroundPoint) | NationalInstruments.UI.GraphInteractionModes.PanX) | NationalInstruments.UI.GraphInteractionModes.PanY) | NationalInstruments.UI.GraphInteractionModes.DragCursor) | NationalInstruments.UI.GraphInteractionModes.DragAnnotationCaption) | NationalInstruments.UI.GraphInteractionModes.EditRange))); this.pmtGraph.Location = new System.Drawing.Point(375, 269); this.pmtGraph.Name = "pmtGraph"; this.pmtGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.pmtOnPlot, this.pmtOffPlot, this.pmtOnAvgPlot, this.pmtOffAvgPlot, this.pmtFitPlot}); this.pmtGraph.Size = new System.Drawing.Size(586, 255); this.pmtGraph.TabIndex = 9; this.pmtGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis3}); this.pmtGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.pmtYAxis}); // // pmtLowCursor // this.pmtLowCursor.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.pmtLowCursor.LabelVisible = true; this.pmtLowCursor.Plot = this.pmtOnAvgPlot; this.pmtLowCursor.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; this.pmtLowCursor.AfterMove += new NationalInstruments.UI.AfterMoveXYCursorEventHandler(this.PMTCursorMoved); // // pmtOnAvgPlot // this.pmtOnAvgPlot.LineColor = System.Drawing.Color.Red; this.pmtOnAvgPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.pmtOnAvgPlot.XAxis = this.xAxis3; this.pmtOnAvgPlot.YAxis = this.pmtYAxis; // // xAxis3 // this.xAxis3.Mode = NationalInstruments.UI.AxisMode.Fixed; // // pmtHighCursor // this.pmtHighCursor.Color = System.Drawing.Color.Lime; this.pmtHighCursor.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.pmtHighCursor.LabelVisible = true; this.pmtHighCursor.Plot = this.pmtOnAvgPlot; this.pmtHighCursor.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; this.pmtHighCursor.AfterMove += new NationalInstruments.UI.AfterMoveXYCursorEventHandler(this.PMTCursorMoved); // // pmtOnPlot // this.pmtOnPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.pmtOnPlot.PointStyle = NationalInstruments.UI.PointStyle.Cross; this.pmtOnPlot.XAxis = this.xAxis3; this.pmtOnPlot.YAxis = this.pmtYAxis; // // pmtOffPlot // this.pmtOffPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.pmtOffPlot.PointColor = System.Drawing.Color.Magenta; this.pmtOffPlot.PointStyle = NationalInstruments.UI.PointStyle.Cross; this.pmtOffPlot.XAxis = this.xAxis3; this.pmtOffPlot.YAxis = this.pmtYAxis; // // pmtOffAvgPlot // this.pmtOffAvgPlot.LineColor = System.Drawing.Color.PowderBlue; this.pmtOffAvgPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.pmtOffAvgPlot.XAxis = this.xAxis3; this.pmtOffAvgPlot.YAxis = this.pmtYAxis; // // pmtFitPlot // this.pmtFitPlot.LineColor = System.Drawing.Color.Silver; this.pmtFitPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.pmtFitPlot.LineStyle = NationalInstruments.UI.LineStyle.DashDot; this.pmtFitPlot.LineWidth = 2F; this.pmtFitPlot.XAxis = this.xAxis3; this.pmtFitPlot.YAxis = this.pmtYAxis; // // pmtXAxis // this.pmtXAxis.Mode = NationalInstruments.UI.AxisMode.Fixed; // // xAxis5 // this.xAxis5.CaptionBackColor = System.Drawing.SystemColors.ControlLight; this.xAxis5.Mode = NationalInstruments.UI.AxisMode.Fixed; // // differenceYAxis // this.differenceYAxis.CaptionBackColor = System.Drawing.SystemColors.ControlLight; // // differenceGraph // this.differenceGraph.Location = new System.Drawing.Point(375, 530); this.differenceGraph.Name = "differenceGraph"; this.differenceGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.differencePlot, this.differenceAvgPlot}); this.differenceGraph.Size = new System.Drawing.Size(585, 255); this.differenceGraph.TabIndex = 15; this.differenceGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis5}); this.differenceGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.differenceYAxis}); // // differencePlot // this.differencePlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.differencePlot.PointColor = System.Drawing.Color.Lime; this.differencePlot.PointStyle = NationalInstruments.UI.PointStyle.Cross; this.differencePlot.XAxis = this.xAxis5; this.differencePlot.YAxis = this.differenceYAxis; // // differenceAvgPlot // this.differenceAvgPlot.LineColor = System.Drawing.Color.Red; this.differenceAvgPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.differenceAvgPlot.XAxis = this.xAxis5; this.differenceAvgPlot.YAxis = this.differenceYAxis; // // tofGraph // this.tofGraph.Cursors.AddRange(new NationalInstruments.UI.XYCursor[] { this.tofLowCursor, this.tofHighCursor}); this.tofGraph.InteractionMode = ((NationalInstruments.UI.GraphInteractionModes)((((((((NationalInstruments.UI.GraphInteractionModes.ZoomX | NationalInstruments.UI.GraphInteractionModes.ZoomY) | NationalInstruments.UI.GraphInteractionModes.ZoomAroundPoint) | NationalInstruments.UI.GraphInteractionModes.PanX) | NationalInstruments.UI.GraphInteractionModes.PanY) | NationalInstruments.UI.GraphInteractionModes.DragCursor) | NationalInstruments.UI.GraphInteractionModes.DragAnnotationCaption) | NationalInstruments.UI.GraphInteractionModes.EditRange))); this.tofGraph.Location = new System.Drawing.Point(8, 8); this.tofGraph.Name = "tofGraph"; this.tofGraph.Plots.AddRange(new NationalInstruments.UI.WaveformPlot[] { this.tofOnPlot, this.tofOffPlot, this.tofOnAveragePlot, this.tofOffAveragePlot, this.tofFitPlot}); this.tofGraph.Size = new System.Drawing.Size(362, 255); this.tofGraph.TabIndex = 16; this.tofGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis4}); this.tofGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.tofYAxis, this.tofAvgYAxis}); this.tofGraph.PlotDataChanged += new NationalInstruments.UI.XYPlotDataChangedEventHandler(this.tofGraph_PlotDataChanged); // // tofLowCursor // this.tofLowCursor.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.tofLowCursor.LabelVisible = true; this.tofLowCursor.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.tofLowCursor.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.tofLowCursor.Plot = this.tofOnAveragePlot; this.tofLowCursor.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; this.tofLowCursor.AfterMove += new NationalInstruments.UI.AfterMoveXYCursorEventHandler(this.TOFCursorMoved); // // tofOnAveragePlot // this.tofOnAveragePlot.LineColor = System.Drawing.Color.Red; this.tofOnAveragePlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnAveragePlot.XAxis = this.xAxis4; this.tofOnAveragePlot.YAxis = this.tofAvgYAxis; // // xAxis4 // this.xAxis4.Mode = NationalInstruments.UI.AxisMode.Fixed; // // tofAvgYAxis // this.tofAvgYAxis.Position = NationalInstruments.UI.YAxisPosition.Right; // // tofHighCursor // this.tofHighCursor.Color = System.Drawing.Color.Lime; this.tofHighCursor.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.tofHighCursor.LabelVisible = true; this.tofHighCursor.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.tofHighCursor.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.tofHighCursor.Plot = this.tofOnAveragePlot; this.tofHighCursor.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; this.tofHighCursor.AfterMove += new NationalInstruments.UI.AfterMoveXYCursorEventHandler(this.TOFCursorMoved); // // tofOnPlot // this.tofOnPlot.LineColor = System.Drawing.Color.Blue; this.tofOnPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOnPlot.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOnPlot.XAxis = this.xAxis4; this.tofOnPlot.YAxis = this.tofYAxis; // // tofOffPlot // this.tofOffPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOffPlot.PointColor = System.Drawing.Color.LawnGreen; this.tofOffPlot.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOffPlot.XAxis = this.xAxis4; this.tofOffPlot.YAxis = this.tofYAxis; // // tofOffAveragePlot // this.tofOffAveragePlot.LineColor = System.Drawing.Color.PowderBlue; this.tofOffAveragePlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOffAveragePlot.XAxis = this.xAxis4; this.tofOffAveragePlot.YAxis = this.tofAvgYAxis; // // tofFitPlot // this.tofFitPlot.LineColor = System.Drawing.Color.Silver; this.tofFitPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofFitPlot.LineStyle = NationalInstruments.UI.LineStyle.DashDot; this.tofFitPlot.LineWidth = 2F; this.tofFitPlot.XAxis = this.xAxis4; this.tofFitPlot.YAxis = this.tofAvgYAxis; // // tofFitModeCombo // this.tofFitModeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.tofFitModeCombo.Items.AddRange(new object[] { "off", "average"}); this.tofFitModeCombo.Location = new System.Drawing.Point(64, 810); this.tofFitModeCombo.Name = "tofFitModeCombo"; this.tofFitModeCombo.Size = new System.Drawing.Size(72, 21); this.tofFitModeCombo.TabIndex = 17; this.tofFitModeCombo.SelectedIndexChanged += new System.EventHandler(this.tofFitModeCombo_SelectedIndexChanged); // // label1 // this.label1.Location = new System.Drawing.Point(6, 789); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 23); this.label1.TabIndex = 18; this.label1.Text = "Fit TOF:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tofFitFunctionCombo // this.tofFitFunctionCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.tofFitFunctionCombo.Location = new System.Drawing.Point(142, 810); this.tofFitFunctionCombo.Name = "tofFitFunctionCombo"; this.tofFitFunctionCombo.Size = new System.Drawing.Size(88, 21); this.tofFitFunctionCombo.TabIndex = 19; this.tofFitFunctionCombo.SelectedIndexChanged += new System.EventHandler(this.tofFitFunctionCombo_SelectedIndexChanged); // // spectrumFitFunctionCombo // this.spectrumFitFunctionCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.spectrumFitFunctionCombo.Location = new System.Drawing.Point(632, 810); this.spectrumFitFunctionCombo.Name = "spectrumFitFunctionCombo"; this.spectrumFitFunctionCombo.Size = new System.Drawing.Size(88, 21); this.spectrumFitFunctionCombo.TabIndex = 22; this.spectrumFitFunctionCombo.SelectedIndexChanged += new System.EventHandler(this.spectrumFitFunctionCombo_SelectedIndexChanged); // // label2 // this.label2.Location = new System.Drawing.Point(551, 792); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 15); this.label2.TabIndex = 21; this.label2.Text = "Fit spectrum:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // spectrumFitModeCombo // this.spectrumFitModeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.spectrumFitModeCombo.Items.AddRange(new object[] { "off", "average", "shot"}); this.spectrumFitModeCombo.Location = new System.Drawing.Point(554, 810); this.spectrumFitModeCombo.Name = "spectrumFitModeCombo"; this.spectrumFitModeCombo.Size = new System.Drawing.Size(72, 21); this.spectrumFitModeCombo.TabIndex = 20; this.spectrumFitModeCombo.SelectedIndexChanged += new System.EventHandler(this.spectrumFitModeCombo_SelectedIndexChanged); // // tofFitResultsLabel // this.tofFitResultsLabel.ForeColor = System.Drawing.Color.Blue; this.tofFitResultsLabel.Location = new System.Drawing.Point(260, 807); this.tofFitResultsLabel.Name = "tofFitResultsLabel"; this.tofFitResultsLabel.Size = new System.Drawing.Size(100, 24); this.tofFitResultsLabel.TabIndex = 23; this.tofFitResultsLabel.Text = "..."; this.tofFitResultsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // spectrumFitResultsLabel // this.spectrumFitResultsLabel.ForeColor = System.Drawing.Color.Blue; this.spectrumFitResultsLabel.Location = new System.Drawing.Point(748, 807); this.spectrumFitResultsLabel.Name = "spectrumFitResultsLabel"; this.spectrumFitResultsLabel.Size = new System.Drawing.Size(210, 24); this.spectrumFitResultsLabel.TabIndex = 24; this.spectrumFitResultsLabel.Text = "..."; this.spectrumFitResultsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // updateTOFFitButton // this.updateTOFFitButton.Location = new System.Drawing.Point(236, 808); this.updateTOFFitButton.Name = "updateTOFFitButton"; this.updateTOFFitButton.Size = new System.Drawing.Size(18, 23); this.updateTOFFitButton.TabIndex = 25; this.updateTOFFitButton.Text = ">"; this.updateTOFFitButton.UseVisualStyleBackColor = true; this.updateTOFFitButton.Click += new System.EventHandler(this.updateTOFFitButton_Click); // // updateSpectrumFitButton // this.updateSpectrumFitButton.Location = new System.Drawing.Point(724, 810); this.updateSpectrumFitButton.Name = "updateSpectrumFitButton"; this.updateSpectrumFitButton.Size = new System.Drawing.Size(18, 23); this.updateSpectrumFitButton.TabIndex = 26; this.updateSpectrumFitButton.Text = ">"; this.updateSpectrumFitButton.UseVisualStyleBackColor = true; this.updateSpectrumFitButton.Click += new System.EventHandler(this.updateSpectrumFitButton_Click); // // tofFitDataSelectCombo // this.tofFitDataSelectCombo.FormattingEnabled = true; this.tofFitDataSelectCombo.Items.AddRange(new object[] { "On", "Off"}); this.tofFitDataSelectCombo.Location = new System.Drawing.Point(8, 810); this.tofFitDataSelectCombo.Name = "tofFitDataSelectCombo"; this.tofFitDataSelectCombo.Size = new System.Drawing.Size(50, 21); this.tofFitDataSelectCombo.TabIndex = 27; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Bottom; this.splitContainer1.Location = new System.Drawing.Point(0, 839); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.splitContainer2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.statusBar1); this.splitContainer1.Size = new System.Drawing.Size(970, 23); this.splitContainer1.SplitterDistance = 371; this.splitContainer1.TabIndex = 30; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.statusBar2); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.defaultGateButton); this.splitContainer2.Size = new System.Drawing.Size(371, 23); this.splitContainer2.SplitterDistance = 236; this.splitContainer2.TabIndex = 0; // // statusBar2 // this.statusBar2.Location = new System.Drawing.Point(0, 0); this.statusBar2.Name = "statusBar2"; this.statusBar2.Size = new System.Drawing.Size(236, 23); this.statusBar2.SizingGrip = false; this.statusBar2.TabIndex = 32; this.statusBar2.Text = "Ready"; // // defaultGateButton // this.defaultGateButton.Location = new System.Drawing.Point(3, 0); this.defaultGateButton.Name = "defaultGateButton"; this.defaultGateButton.Size = new System.Drawing.Size(120, 23); this.defaultGateButton.TabIndex = 26; this.defaultGateButton.Text = "Default Gate"; this.defaultGateButton.UseVisualStyleBackColor = true; this.defaultGateButton.Click += new System.EventHandler(this.defaultGateButton_Click); // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 0); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(595, 23); this.statusBar1.SizingGrip = false; this.statusBar1.TabIndex = 14; this.statusBar1.Text = "Ready"; // // label3 // this.label3.Location = new System.Drawing.Point(378, 792); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(117, 12); this.label3.TabIndex = 31; this.label3.Text = "Factor over shot noise:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // updateNoiseResultsbutton // this.updateNoiseResultsbutton.Location = new System.Drawing.Point(381, 807); this.updateNoiseResultsbutton.Name = "updateNoiseResultsbutton"; this.updateNoiseResultsbutton.Size = new System.Drawing.Size(18, 23); this.updateNoiseResultsbutton.TabIndex = 32; this.updateNoiseResultsbutton.Text = ">"; this.updateNoiseResultsbutton.UseVisualStyleBackColor = true; this.updateNoiseResultsbutton.Click += new System.EventHandler(this.updateNoiseResultsbutton_Click); // // noiseResultsLabel // this.noiseResultsLabel.ForeColor = System.Drawing.Color.Blue; this.noiseResultsLabel.Location = new System.Drawing.Point(405, 808); this.noiseResultsLabel.Name = "noiseResultsLabel"; this.noiseResultsLabel.Size = new System.Drawing.Size(143, 24); this.noiseResultsLabel.TabIndex = 33; this.noiseResultsLabel.Text = "..."; this.noiseResultsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tofGraph2 // this.tofGraph2.Cursors.AddRange(new NationalInstruments.UI.XYCursor[] { this.normSigGateLow, this.normSigGateHigh, this.normBgGateLow, this.normBgGateHigh}); this.tofGraph2.InteractionMode = ((NationalInstruments.UI.GraphInteractionModes)((((((((NationalInstruments.UI.GraphInteractionModes.ZoomX | NationalInstruments.UI.GraphInteractionModes.ZoomY) | NationalInstruments.UI.GraphInteractionModes.ZoomAroundPoint) | NationalInstruments.UI.GraphInteractionModes.PanX) | NationalInstruments.UI.GraphInteractionModes.PanY) | NationalInstruments.UI.GraphInteractionModes.DragCursor) | NationalInstruments.UI.GraphInteractionModes.DragAnnotationCaption) | NationalInstruments.UI.GraphInteractionModes.EditRange))); this.tofGraph2.Location = new System.Drawing.Point(8, 269); this.tofGraph2.Name = "tofGraph2"; this.tofGraph2.Plots.AddRange(new NationalInstruments.UI.WaveformPlot[] { this.tofOnPlot2, this.tofOffPlot2, this.tofOnAveragePlot2, this.tofOffAveragePlot2, this.tofFitPlot2}); this.tofGraph2.Size = new System.Drawing.Size(361, 255); this.tofGraph2.TabIndex = 34; this.tofGraph2.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis6}); this.tofGraph2.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis4, this.yAxis3}); // // normSigGateLow // this.normSigGateLow.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.normSigGateLow.LabelVisible = true; this.normSigGateLow.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.normSigGateLow.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.normSigGateLow.Plot = this.tofOnAveragePlot2; this.normSigGateLow.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // tofOnAveragePlot2 // this.tofOnAveragePlot2.LineColor = System.Drawing.Color.Red; this.tofOnAveragePlot2.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnAveragePlot2.XAxis = this.xAxis6; this.tofOnAveragePlot2.YAxis = this.yAxis3; // // xAxis6 // this.xAxis6.Mode = NationalInstruments.UI.AxisMode.Fixed; // // yAxis3 // this.yAxis3.Position = NationalInstruments.UI.YAxisPosition.Right; // // normSigGateHigh // this.normSigGateHigh.Color = System.Drawing.Color.Lime; this.normSigGateHigh.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.normSigGateHigh.LabelVisible = true; this.normSigGateHigh.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.normSigGateHigh.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.normSigGateHigh.Plot = this.tofOnAveragePlot2; this.normSigGateHigh.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // tofOnPlot2 // this.tofOnPlot2.LineColor = System.Drawing.Color.Blue; this.tofOnPlot2.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnPlot2.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOnPlot2.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOnPlot2.XAxis = this.xAxis6; this.tofOnPlot2.YAxis = this.yAxis4; // // tofOffPlot2 // this.tofOffPlot2.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOffPlot2.PointColor = System.Drawing.Color.LawnGreen; this.tofOffPlot2.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOffPlot2.XAxis = this.xAxis6; this.tofOffPlot2.YAxis = this.yAxis4; // // tofOffAveragePlot2 // this.tofOffAveragePlot2.LineColor = System.Drawing.Color.PowderBlue; this.tofOffAveragePlot2.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOffAveragePlot2.XAxis = this.xAxis6; this.tofOffAveragePlot2.YAxis = this.yAxis3; // // tofFitPlot2 // this.tofFitPlot2.LineColor = System.Drawing.Color.Silver; this.tofFitPlot2.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofFitPlot2.LineStyle = NationalInstruments.UI.LineStyle.DashDot; this.tofFitPlot2.LineWidth = 2F; this.tofFitPlot2.XAxis = this.xAxis6; this.tofFitPlot2.YAxis = this.yAxis3; // // tofGraphNormed // this.tofGraphNormed.Cursors.AddRange(new NationalInstruments.UI.XYCursor[] { this.xyCursor3, this.xyCursor4}); this.tofGraphNormed.InteractionMode = ((NationalInstruments.UI.GraphInteractionModes)((((((((NationalInstruments.UI.GraphInteractionModes.ZoomX | NationalInstruments.UI.GraphInteractionModes.ZoomY) | NationalInstruments.UI.GraphInteractionModes.ZoomAroundPoint) | NationalInstruments.UI.GraphInteractionModes.PanX) | NationalInstruments.UI.GraphInteractionModes.PanY) | NationalInstruments.UI.GraphInteractionModes.DragCursor) | NationalInstruments.UI.GraphInteractionModes.DragAnnotationCaption) | NationalInstruments.UI.GraphInteractionModes.EditRange))); this.tofGraphNormed.Location = new System.Drawing.Point(8, 530); this.tofGraphNormed.Name = "tofGraphNormed"; this.tofGraphNormed.Plots.AddRange(new NationalInstruments.UI.WaveformPlot[] { this.tofOnNormedPlot, this.tofOffNormedPlot, this.tofOnAverageNormedPlot, this.tofOffAverageNormedPlot, this.tofFitNormedPlot}); this.tofGraphNormed.Size = new System.Drawing.Size(361, 255); this.tofGraphNormed.TabIndex = 35; this.tofGraphNormed.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis7}); this.tofGraphNormed.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis6, this.yAxis5}); // // xyCursor3 // this.xyCursor3.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.xyCursor3.LabelVisible = true; this.xyCursor3.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.xyCursor3.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.xyCursor3.Plot = this.tofOnAverageNormedPlot; this.xyCursor3.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // tofOnAverageNormedPlot // this.tofOnAverageNormedPlot.LineColor = System.Drawing.Color.Red; this.tofOnAverageNormedPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnAverageNormedPlot.XAxis = this.xAxis7; this.tofOnAverageNormedPlot.YAxis = this.yAxis5; // // xAxis7 // this.xAxis7.Mode = NationalInstruments.UI.AxisMode.Fixed; // // yAxis5 // this.yAxis5.Position = NationalInstruments.UI.YAxisPosition.Right; // // xyCursor4 // this.xyCursor4.Color = System.Drawing.Color.Lime; this.xyCursor4.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.xyCursor4.LabelVisible = true; this.xyCursor4.LabelXFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.xyCursor4.LabelYFormat = new NationalInstruments.UI.FormatString(NationalInstruments.UI.FormatStringMode.Numeric, "G3"); this.xyCursor4.Plot = this.tofOnAverageNormedPlot; this.xyCursor4.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // tofOnNormedPlot // this.tofOnNormedPlot.LineColor = System.Drawing.Color.Blue; this.tofOnNormedPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOnNormedPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOnNormedPlot.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOnNormedPlot.XAxis = this.xAxis7; this.tofOnNormedPlot.YAxis = this.yAxis6; // // tofOffNormedPlot // this.tofOffNormedPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.tofOffNormedPlot.PointColor = System.Drawing.Color.LawnGreen; this.tofOffNormedPlot.PointStyle = NationalInstruments.UI.PointStyle.Plus; this.tofOffNormedPlot.XAxis = this.xAxis7; this.tofOffNormedPlot.YAxis = this.yAxis6; // // tofOffAverageNormedPlot // this.tofOffAverageNormedPlot.LineColor = System.Drawing.Color.PowderBlue; this.tofOffAverageNormedPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofOffAverageNormedPlot.XAxis = this.xAxis7; this.tofOffAverageNormedPlot.YAxis = this.yAxis5; // // tofFitNormedPlot // this.tofFitNormedPlot.LineColor = System.Drawing.Color.Silver; this.tofFitNormedPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.tofFitNormedPlot.LineStyle = NationalInstruments.UI.LineStyle.DashDot; this.tofFitNormedPlot.LineWidth = 2F; this.tofFitNormedPlot.XAxis = this.xAxis7; this.tofFitNormedPlot.YAxis = this.yAxis5; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(98, 22); this.toolStripLabel1.Text = "InteractionMode:"; // // toolStripPropertyEditor1 // this.toolStripPropertyEditor1.AutoSize = false; this.toolStripPropertyEditor1.Name = "toolStripPropertyEditor1"; this.toolStripPropertyEditor1.RenderMode = NationalInstruments.UI.PropertyEditorRenderMode.Inherit; this.toolStripPropertyEditor1.Size = new System.Drawing.Size(120, 23); this.toolStripPropertyEditor1.Source = new NationalInstruments.UI.PropertyEditorSource(this.tofGraph, "InteractionMode"); this.toolStripPropertyEditor1.Text = "ZoomX, ZoomY, ZoomAroundPoint, PanX, PanY, DragCursor, DragAnnotationCaption, Edi" + "tRange"; // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(23, 23); // // toolStripPropertyEditor2 // this.toolStripPropertyEditor2.AutoSize = false; this.toolStripPropertyEditor2.Name = "toolStripPropertyEditor2"; this.toolStripPropertyEditor2.RenderMode = NationalInstruments.UI.PropertyEditorRenderMode.Inherit; this.toolStripPropertyEditor2.Size = new System.Drawing.Size(120, 20); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(75, 15); this.toolStripLabel3.Text = "Annotations:"; // // toolStripPropertyEditor3 // this.toolStripPropertyEditor3.AutoSize = false; this.toolStripPropertyEditor3.Name = "toolStripPropertyEditor3"; this.toolStripPropertyEditor3.RenderMode = NationalInstruments.UI.PropertyEditorRenderMode.Inherit; this.toolStripPropertyEditor3.Size = new System.Drawing.Size(120, 23); this.toolStripPropertyEditor3.Source = new NationalInstruments.UI.PropertyEditorSource(this.tofGraph, "Annotations"); this.toolStripPropertyEditor3.Text = "(Collection)"; // // normBgGateLow // this.normBgGateLow.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.normBgGateLow.LabelVisible = true; this.normBgGateLow.LineStyle = NationalInstruments.UI.LineStyle.Dot; this.normBgGateLow.Plot = this.tofOnPlot2; this.normBgGateLow.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // normBgGateHigh // this.normBgGateHigh.Color = System.Drawing.Color.Lime; this.normBgGateHigh.HorizontalCrosshairMode = NationalInstruments.UI.CursorCrosshairMode.None; this.normBgGateHigh.LabelVisible = true; this.normBgGateHigh.LineStyle = NationalInstruments.UI.LineStyle.Dot; this.normBgGateHigh.Plot = this.tofOnPlot2; this.normBgGateHigh.SnapMode = NationalInstruments.UI.CursorSnapMode.Floating; // // StandardViewerWindow // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(970, 862); this.Controls.Add(this.tofGraphNormed); this.Controls.Add(this.tofGraph2); this.Controls.Add(this.noiseResultsLabel); this.Controls.Add(this.updateNoiseResultsbutton); this.Controls.Add(this.label3); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.tofFitDataSelectCombo); this.Controls.Add(this.updateSpectrumFitButton); this.Controls.Add(this.updateTOFFitButton); this.Controls.Add(this.spectrumFitResultsLabel); this.Controls.Add(this.tofFitResultsLabel); this.Controls.Add(this.spectrumFitFunctionCombo); this.Controls.Add(this.label2); this.Controls.Add(this.spectrumFitModeCombo); this.Controls.Add(this.tofFitFunctionCombo); this.Controls.Add(this.label1); this.Controls.Add(this.tofFitModeCombo); this.Controls.Add(this.tofGraph); this.Controls.Add(this.differenceGraph); this.Controls.Add(this.pmtGraph); this.Controls.Add(this.analog2Graph); this.Controls.Add(this.analog1Graph); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "StandardViewerWindow"; this.Text = "Standard View"; this.Closing += new System.ComponentModel.CancelEventHandler(this.WindowClosing); this.Load += new System.EventHandler(this.StandardViewerWindow_Load); ((System.ComponentModel.ISupportInitialize)(this.analog1Graph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.analog2Graph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtGraph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtLowCursor)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pmtHighCursor)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.differenceGraph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tofGraph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tofLowCursor)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tofHighCursor)).EndInit(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.tofGraph2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.normSigGateLow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.normSigGateHigh)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tofGraphNormed)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xyCursor3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xyCursor4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.normBgGateLow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.normBgGateHigh)).EndInit(); this.ResumeLayout(false); } #endregion private void TOFCursorMoved(object sender, NationalInstruments.UI.AfterMoveXYCursorEventArgs e) { viewer.TOFCursorMoved(); } private void PMTCursorMoved(object sender, NationalInstruments.UI.AfterMoveXYCursorEventArgs e) { viewer.PMTCursorMoved(); } private void tofFitModeCombo_SelectedIndexChanged(object sender, System.EventArgs e) { viewer.TOFFitModeChanged(((ComboBox)sender).SelectedIndex); } private void tofFitFunctionCombo_SelectedIndexChanged(object sender, System.EventArgs e) { viewer.TOFFitFunctionChanged(((ComboBox)sender).SelectedItem); } private void spectrumFitModeCombo_SelectedIndexChanged(object sender, System.EventArgs e) { viewer.SpectrumFitModeChanged(((ComboBox)sender).SelectedIndex); } private void spectrumFitFunctionCombo_SelectedIndexChanged(object sender, System.EventArgs e) { viewer.SpectrumFitFunctionChanged(((ComboBox)sender).SelectedItem); } private void updateTOFFitButton_Click(object sender, EventArgs e) { viewer.UpdateTOFFit(); } private void updateSpectrumFitButton_Click(object sender, EventArgs e) { viewer.UpdateSpectrumFit(); } // these functions and properties are all thread safe public void ClearAll() { ClearNIGraph(analog1Graph); ClearNIGraph(analog2Graph); ClearNIGraph(pmtGraph); ClearNIGraph(tofGraph); ClearNIGraph(tofGraph2); ClearNIGraph(tofGraphNormed); ClearNIGraph(differenceGraph); } public void ClearSpectra() { ClearNIGraph(analog1Graph); ClearNIGraph(analog2Graph); ClearNIGraph(pmtGraph); ClearNIGraph(differenceGraph); } public void ClearRealtimeSpectra() { ClearNIPlot(pmtGraph, pmtOnPlot); ClearNIPlot(pmtGraph, pmtOffPlot); ClearNIPlot(differenceGraph, differencePlot); ClearNIPlot(analog1Graph, analog1Plot); ClearNIPlot(analog2Graph, analog2Plot); } public void ClearRealtimeNotAnalog() { ClearNIPlot(tofGraph, tofOnPlot); ClearNIPlot(tofGraph, tofOffPlot); ClearNIPlot(tofGraph2, tofOnPlot2); ClearNIPlot(tofGraph2, tofOffPlot2); ClearNIPlot(pmtGraph, pmtOnPlot); ClearNIPlot(pmtGraph, pmtOffPlot); ClearNIPlot(differenceGraph, differencePlot); } public void ClearSpectrumFit() { ClearNIPlot(pmtGraph, pmtFitPlot); } public Range SpectrumAxes { set { SetGraphXAxisRange(pmtGraph, value.Minimum, value.Maximum); SetGraphXAxisRange(differenceGraph, value.Minimum, value.Maximum); SetGraphXAxisRange(analog1Graph, value.Minimum, value.Maximum); SetGraphXAxisRange(analog2Graph, value.Minimum, value.Maximum); } } public Range TOFAxes { set { if (value != null) { SetGraphXAxisRange(tofGraph, value.Minimum, value.Maximum); SetGraphXAxisRange(tofGraphNormed, value.Minimum, value.Maximum); } else { tofGraph.XAxes[0].Mode = AxisMode.AutoScaleLoose; tofGraphNormed.XAxes[0].Mode = AxisMode.AutoScaleLoose; } } } public Range TOF2Axes { set { if (value != null) { SetGraphXAxisRange(tofGraph2, value.Minimum, value.Maximum); } else { tofGraph2.XAxes[0].Mode = AxisMode.AutoScaleLoose; } } } public Range SpectrumGate { set { MoveCursor(pmtGraph, pmtLowCursor, value.Minimum); MoveCursor(pmtGraph, pmtHighCursor, value.Maximum); } get { double min = GetCursorPosition(pmtGraph, pmtLowCursor); double max = GetCursorPosition(pmtGraph, pmtHighCursor); if (max <= min) max = min + 1; //highly arbitrary return new Range(min, max); } } public Range TOFGate { set { MoveCursor(tofGraph, tofLowCursor, value.Minimum); MoveCursor(tofGraph, tofHighCursor, value.Maximum); } get { double min = GetCursorPosition(tofGraph, tofLowCursor); double max = GetCursorPosition(tofGraph, tofHighCursor); if (max <= min) max = min + 1; //also somewhat arbitrary return new Range(min, max); } } public Range NormSigGate { set { MoveCursor(tofGraph2, normSigGateLow, value.Minimum); MoveCursor(tofGraph2, normSigGateHigh, value.Maximum); } get { double min = GetCursorPosition(tofGraph2, normSigGateLow); double max = GetCursorPosition(tofGraph2, normSigGateHigh); if (max <= min) max = min + 1; //also somewhat arbitrary return new Range(min, max); } } public Range NormBgGate { set { MoveCursor(tofGraph2, normBgGateLow, value.Minimum); MoveCursor(tofGraph2, normBgGateHigh, value.Maximum); } get { double min = GetCursorPosition(tofGraph2, normBgGateLow); double max = GetCursorPosition(tofGraph2, normBgGateHigh); if (max <= min) max = min + 1; //still as arbitrary as ever return new Range(min, max); } } public void PlotOnTOF(TOF t) { PlotY(tofGraph, tofOnPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotOnTOF(ArrayList t) { PlotY(tofGraph, tofOnPlot, ((TOF)t[0]).GateStartTime, ((TOF)t[0]).ClockPeriod, ((TOF)t[0]).Data); if (t.Count > 1) { PlotY(tofGraph2, tofOnPlot2, ((TOF)t[1]).GateStartTime, ((TOF)t[1]).ClockPeriod, ((TOF)t[1]).Data); } } public void PlotOffTOF(TOF t) { PlotY(tofGraph, tofOffPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotOffTOF(ArrayList t) { PlotY(tofGraph, tofOffPlot, ((TOF)t[0]).GateStartTime, ((TOF)t[0]).ClockPeriod, ((TOF)t[0]).Data); if (t.Count > 1) { PlotY(tofGraph2, tofOffPlot2, ((TOF)t[1]).GateStartTime, ((TOF)t[1]).ClockPeriod, ((TOF)t[1]).Data); } } public void PlotAverageOnTOF(TOF t) { PlotY(tofGraph, tofOnAveragePlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotAverageOnTOF(ArrayList t) { PlotY(tofGraph, tofOnAveragePlot, ((TOF)t[0]).GateStartTime, ((TOF)t[0]).ClockPeriod, ((TOF)t[0]).Data); if (t.Count > 1) { PlotY(tofGraph2, tofOnAveragePlot2, ((TOF)t[1]).GateStartTime, ((TOF)t[1]).ClockPeriod, ((TOF)t[1]).Data); } } public void PlotAverageOffTOF(TOF t) { PlotY(tofGraph, tofOffAveragePlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotAverageOffTOF(ArrayList t) { PlotY(tofGraph, tofOffAveragePlot, ((TOF)t[0]).GateStartTime, ((TOF)t[0]).ClockPeriod, ((TOF)t[0]).Data); if (t.Count > 1) { PlotY(tofGraph2, tofOffAveragePlot2, ((TOF)t[1]).GateStartTime, ((TOF)t[1]).ClockPeriod, ((TOF)t[1]).Data); } } public void PlotNormedOnTOF(TOF t) { PlotY(tofGraphNormed, tofOnNormedPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotNormedOffTOF(TOF t) { PlotY(tofGraphNormed, tofOffNormedPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotAverageNormedOnTOF(TOF t) { PlotY(tofGraphNormed, tofOnAverageNormedPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void PlotAverageNormedOffTOF(TOF t) { PlotY(tofGraphNormed, tofOffAverageNormedPlot, t.GateStartTime, t.ClockPeriod, t.Data); } public void AppendToAnalog1(double[] x, double[] y) { PlotXYAppend(analog1Graph, analog1Plot, x, y); } public void AppendToAnalog2(double[] x, double[] y) { PlotXYAppend(analog2Graph, analog2Plot, x, y); } public void AppendToPMTOn(double[] x, double[] y) { PlotXYAppend(pmtGraph, pmtOnPlot, x, y); } public void AppendToPMTOff(double[] x, double[] y) { PlotXYAppend(pmtGraph, pmtOffPlot, x, y); } public void AppendToDifference(double[] x, double[] y) { PlotXYAppend(differenceGraph, differencePlot, x, y); } public void PlotAveragePMTOn(double[] x, double[] y) { PlotXY(pmtGraph, pmtOnAvgPlot, x, y); } public void PlotAveragePMTOff(double[] x, double[] y) { PlotXY(pmtGraph, pmtOffAvgPlot, x, y); } public void PlotAverageDifference(double[] x, double[] y) { PlotXY(differenceGraph, differenceAvgPlot, x, y); } public void PlotSpectrumFit(double[] x, double[] y) { PlotXY(pmtGraph, pmtFitPlot, x, y); } public void ClearTOFFit() { ClearNIPlot(tofGraph, tofFitPlot); } public void PlotTOFFit(int start, int period, double[] data) { PlotY(tofGraph, tofFitPlot, start, period, data); } // UI delegates and thread-safe helpers private delegate void ClearDataDelegate(); private void ClearNIGraph(Graph graph) { graph.Invoke(new ClearDataDelegate(graph.ClearData)); } private void ClearNIPlot(Graph graph, Plot plot) { graph.Invoke(new ClearDataDelegate(plot.ClearData)); } private void SetGraphXAxisRangeHelper(XYGraph graph, double start, double end) { graph.XAxes[0].Range = new Range(start, end); } private delegate void SetGraphXAxisRangeDelegate(XYGraph graph, double start, double end); private void SetGraphXAxisRange(XYGraph graph, double start, double end) { graph.Invoke(new SetGraphXAxisRangeDelegate(SetGraphXAxisRangeHelper), new Object[] { graph, start, end }); } private delegate void PlotXYDelegate(double[] x, double[] y); private void PlotXYAppend(Graph graph, ScatterPlot plot, double[] x, double[] y) { graph.Invoke(new PlotXYDelegate(plot.PlotXYAppend), new Object[] { x, y }); } private void PlotXY(Graph graph, ScatterPlot plot, double[] x, double[] y) { graph.Invoke(new PlotXYDelegate(plot.PlotXY), new Object[] { x, y }); } private delegate void PlotYDelegate(double[] yData, double start, double inc); private void PlotY(Graph graph, WaveformPlot p, double start, double inc, double[] ydata) { graph.Invoke(new PlotYDelegate(p.PlotY), new Object[] { ydata, start, inc }); } private void MoveCursorHelper(XYCursor cursor, double x) { cursor.XPosition = x; } private delegate void MoveCursorDelegate(XYCursor cursor, double x); private void MoveCursor(Graph graph, XYCursor cursor, double x) { graph.Invoke(new MoveCursorDelegate(MoveCursorHelper), new Object[] { cursor, x }); } private delegate double GetCursorPositionDelegate(XYCursor cursor); private double GetCursorPositionHelper(XYCursor cursor) { return cursor.XPosition; } private double GetCursorPosition(Graph graph, XYCursor cursor) { double x = (double)graph.Invoke(new GetCursorPositionDelegate(GetCursorPositionHelper), new Object[] { cursor }); return x; } public void SetLabel(Label label, string text) { label.Invoke(new SetLabelDelegate(SetLabelHelper), new object[] { label, text }); } private delegate void SetLabelDelegate(Label label, string text); private void SetLabelHelper(Label label, string text) { label.Text = text; } public void SetStatus(string text) { this.Invoke(new SetStatusDelegate(SetStatusHelper), new object[] { text }); } public void SetTOFStatus(string text) { this.Invoke(new SetStatusDelegate(SetTOFStatusHelper), new object[] { text }); } private delegate void SetStatusDelegate(string text); private void SetStatusHelper(string text) { statusBar1.Text = text; } private void SetTOFStatusHelper(string text) { statusBar2.Text = text; } private void TofFitComboHelper(bool state) { tofFitFunctionCombo.Enabled = state; } private delegate void ComboStateDelegate(bool state); public void SetTofFitFunctionComboState(bool state) { tofFitFunctionCombo.Invoke(new ComboStateDelegate(TofFitComboHelper), state); } private int TofFitDataSelectHelper() { return tofFitDataSelectCombo.SelectedIndex; } private delegate int TofFitDataDelegate(); public int GetTofFitDataSelection() { return (int) tofFitDataSelectCombo.Invoke(new TofFitDataDelegate(TofFitDataSelectHelper)); } private void SpectrumFitComboHelper(bool state) { spectrumFitFunctionCombo.Enabled = state; } public void SetSpectrumFitFunctionComboState(bool state) { spectrumFitFunctionCombo.Invoke(new ComboStateDelegate(SpectrumFitComboHelper), state); } private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { viewer.ToggleVisible(); e.Cancel = true; } private void updateNoiseResultsbutton_Click(object sender, EventArgs e) { viewer.UpdateNoiseResults(); } private void defaultGateButton_Click(object sender, EventArgs e) { viewer.SetGatesToDefault(); } private void StandardViewerWindow_Load(object sender, EventArgs e) { } private void tofGraph_PlotDataChanged(object sender, XYPlotDataChangedEventArgs e) { } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Configuration; using System.Reflection; using System.Text; using System.IO; using System.Runtime.InteropServices; using System.Collections; namespace log4net.Util { /// <summary> /// Utility class for system specific information. /// </summary> /// <remarks> /// <para> /// Utility class of static methods for system specific information. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Alexey Solofnenko</author> public sealed class SystemInfo { #region Private Constants private const string DEFAULT_NULL_TEXT = "(null)"; private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE"; #endregion #region Private Instance Constructors /// <summary> /// Private constructor to prevent instances. /// </summary> /// <remarks> /// <para> /// Only static methods are exposed from this type. /// </para> /// </remarks> private SystemInfo() { } #endregion Private Instance Constructors #region Public Static Constructor /// <summary> /// Initialize default values for private static fields. /// </summary> /// <remarks> /// <para> /// Only static methods are exposed from this type. /// </para> /// </remarks> static SystemInfo() { string nullText = DEFAULT_NULL_TEXT; string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; #if !NETCF // Look for log4net.NullText in AppSettings string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText"); if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) { LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "]."); nullText = nullTextAppSettingsKey; } // Look for log4net.NotAvailableText in AppSettings string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText"); if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) { LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); notAvailableText = notAvailableTextAppSettingsKey; } #endif s_notAvailableText = notAvailableText; s_nullText = nullText; } #endregion #region Public Static Properties /// <summary> /// Gets the system dependent line terminator. /// </summary> /// <value> /// The system dependent line terminator. /// </value> /// <remarks> /// <para> /// Gets the system dependent line terminator. /// </para> /// </remarks> public static string NewLine { get { #if NETCF return "\r\n"; #else return System.Environment.NewLine; #endif } } /// <summary> /// Gets the base directory for this <see cref="AppDomain"/>. /// </summary> /// <value>The base directory path for the current <see cref="AppDomain"/>.</value> /// <remarks> /// <para> /// Gets the base directory for this <see cref="AppDomain"/>. /// </para> /// <para> /// The value returned may be either a local file path or a URI. /// </para> /// </remarks> public static string ApplicationBaseDirectory { get { #if NETCF return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar; #else return AppDomain.CurrentDomain.BaseDirectory; #endif } } /// <summary> /// Gets the path to the configuration file for the current <see cref="AppDomain"/>. /// </summary> /// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value> /// <remarks> /// <para> /// The .NET Compact Framework 1.0 does not have a concept of a configuration /// file. For this runtime, we use the entry assembly location as the root for /// the configuration file name. /// </para> /// <para> /// The value returned may be either a local file path or a URI. /// </para> /// </remarks> public static string ConfigurationFileLocation { get { #if NETCF return SystemInfo.EntryAssemblyLocation+".config"; #else return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; #endif } } /// <summary> /// Gets the path to the file that first executed in the current <see cref="AppDomain"/>. /// </summary> /// <value>The path to the entry assembly.</value> /// <remarks> /// <para> /// Gets the path to the file that first executed in the current <see cref="AppDomain"/>. /// </para> /// </remarks> public static string EntryAssemblyLocation { get { #if NETCF return SystemInfo.NativeEntryAssemblyLocation; #else return System.Reflection.Assembly.GetEntryAssembly().Location; #endif } } /// <summary> /// Gets the ID of the current thread. /// </summary> /// <value>The ID of the current thread.</value> /// <remarks> /// <para> /// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method /// is used to obtain the thread ID for the current thread. This is the /// operating system ID for the thread. /// </para> /// <para> /// On the .NET Compact Framework 1.0 it is not possible to get the /// operating system thread ID for the current thread. The native method /// <c>GetCurrentThreadId</c> is implemented inline in a header file /// and cannot be called. /// </para> /// <para> /// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this /// gives a stable id unrelated to the operating system thread ID which may /// change if the runtime is using fibers. /// </para> /// </remarks> public static int CurrentThreadId { get { #if NETCF_1_0 return System.Threading.Thread.CurrentThread.GetHashCode(); #elif NET_2_0 || NETCF_2_0 || MONO_2_0 return System.Threading.Thread.CurrentThread.ManagedThreadId; #else return AppDomain.GetCurrentThreadId(); #endif } } /// <summary> /// Get the host name or machine name for the current machine /// </summary> /// <value> /// The hostname or machine name /// </value> /// <remarks> /// <para> /// Get the host name or machine name for the current machine /// </para> /// <para> /// The host name (<see cref="System.Net.Dns.GetHostName"/>) or /// the machine name (<c>Environment.MachineName</c>) for /// the current machine, or if neither of these are available /// then <c>NOT AVAILABLE</c> is returned. /// </para> /// </remarks> public static string HostName { get { if (s_hostName == null) { // Get the DNS host name of the current machine try { // Lookup the host name s_hostName = System.Net.Dns.GetHostName(); } catch (System.Net.Sockets.SocketException) { LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored."); } catch (System.Security.SecurityException) { // We may get a security exception looking up the hostname // You must have Unrestricted DnsPermission to access resource LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored."); } catch (Exception ex) { LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex); } // Get the NETBIOS machine name of the current machine if (s_hostName == null || s_hostName.Length == 0) { try { #if (!SSCLI && !NETCF) s_hostName = Environment.MachineName; #endif } catch(InvalidOperationException) { } catch(System.Security.SecurityException) { // We may get a security exception looking up the machine name // You must have Unrestricted EnvironmentPermission to access resource } } // Couldn't find a value if (s_hostName == null || s_hostName.Length == 0) { s_hostName = s_notAvailableText; LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used"); } } return s_hostName; } } /// <summary> /// Get this application's friendly name /// </summary> /// <value> /// The friendly name of this application as a string /// </value> /// <remarks> /// <para> /// If available the name of the application is retrieved from /// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>. /// </para> /// <para> /// Otherwise the file name of the entry assembly is used. /// </para> /// </remarks> public static string ApplicationFriendlyName { get { if (s_appFriendlyName == null) { try { #if !NETCF s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; #endif } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // some undefined set of SecurityPermission flags. LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored."); } if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) { try { string assemblyLocation = SystemInfo.EntryAssemblyLocation; s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation); } catch(System.Security.SecurityException) { // Caller needs path discovery permission } } if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) { s_appFriendlyName = s_notAvailableText; } } return s_appFriendlyName; } } /// <summary> /// Get the start time for the current process. /// </summary> /// <remarks> /// <para> /// This is the time at which the log4net library was loaded into the /// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c> /// this is not the start time for the current process. /// </para> /// <para> /// The log4net library should be loaded by an application early during its /// startup, therefore this start time should be a good approximation for /// the actual start time. /// </para> /// <para> /// Note that AppDomains may be loaded and unloaded within the /// same process without the process terminating, however this start time /// will be set per AppDomain. /// </para> /// </remarks> public static DateTime ProcessStartTime { get { return s_processStartTime; } } /// <summary> /// Text to output when a <c>null</c> is encountered. /// </summary> /// <remarks> /// <para> /// Use this value to indicate a <c>null</c> has been encountered while /// outputting a string representation of an item. /// </para> /// <para> /// The default value is <c>(null)</c>. This value can be overridden by specifying /// a value for the <c>log4net.NullText</c> appSetting in the application's /// .config file. /// </para> /// </remarks> public static string NullText { get { return s_nullText; } set { s_nullText = value; } } /// <summary> /// Text to output when an unsupported feature is requested. /// </summary> /// <remarks> /// <para> /// Use this value when an unsupported feature is requested. /// </para> /// <para> /// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying /// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's /// .config file. /// </para> /// </remarks> public static string NotAvailableText { get { return s_notAvailableText; } set { s_notAvailableText = value; } } #endregion Public Static Properties #region Public Static Methods /// <summary> /// Gets the assembly location path for the specified assembly. /// </summary> /// <param name="myAssembly">The assembly to get the location for.</param> /// <returns>The location of the assembly.</returns> /// <remarks> /// <para> /// This method does not guarantee to return the correct path /// to the assembly. If only tries to give an indication as to /// where the assembly was loaded from. /// </para> /// </remarks> public static string AssemblyLocationInfo(Assembly myAssembly) { #if NETCF return "Not supported on Microsoft .NET Compact Framework"; #else if (myAssembly.GlobalAssemblyCache) { return "Global Assembly Cache"; } else { try { #if NET_4_0 if (myAssembly.IsDynamic) { return "Dynamic Assembly"; } #else if (myAssembly is System.Reflection.Emit.AssemblyBuilder) { return "Dynamic Assembly"; } else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder") { return "Dynamic Assembly"; } #endif else { // This call requires FileIOPermission for access to the path // if we don't have permission then we just ignore it and // carry on. return myAssembly.Location; } } catch (NotSupportedException) { // The location information may be unavailable for dynamic assemblies and a NotSupportedException // is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx return "Dynamic Assembly"; } catch (TargetInvocationException ex) { return "Location Detect Failed (" + ex.Message + ")"; } catch (ArgumentException ex) { return "Location Detect Failed (" + ex.Message + ")"; } catch (System.Security.SecurityException) { return "Location Permission Denied"; } } #endif } /// <summary> /// Gets the fully qualified name of the <see cref="Type" />, including /// the name of the assembly from which the <see cref="Type" /> was /// loaded. /// </summary> /// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param> /// <returns>The fully qualified name for the <see cref="Type" />.</returns> /// <remarks> /// <para> /// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property, /// but this method works on the .NET Compact Framework 1.0 as well as /// the full .NET runtime. /// </para> /// </remarks> public static string AssemblyQualifiedName(Type type) { return type.FullName + ", " + type.Assembly.FullName; } /// <summary> /// Gets the short name of the <see cref="Assembly" />. /// </summary> /// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param> /// <returns>The short name of the <see cref="Assembly" />.</returns> /// <remarks> /// <para> /// The short name of the assembly is the <see cref="Assembly.FullName" /> /// without the version, culture, or public key. i.e. it is just the /// assembly's file name without the extension. /// </para> /// <para> /// Use this rather than <c>Assembly.GetName().Name</c> because that /// is not available on the Compact Framework. /// </para> /// <para> /// Because of a FileIOPermission security demand we cannot do /// the obvious Assembly.GetName().Name. We are allowed to get /// the <see cref="Assembly.FullName" /> of the assembly so we /// start from there and strip out just the assembly name. /// </para> /// </remarks> public static string AssemblyShortName(Assembly myAssembly) { string name = myAssembly.FullName; int offset = name.IndexOf(','); if (offset > 0) { name = name.Substring(0, offset); } return name.Trim(); // TODO: Do we need to unescape the assembly name string? // Doc says '\' is an escape char but has this already been // done by the string loader? } /// <summary> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </summary> /// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param> /// <returns>The file name of the assembly.</returns> /// <remarks> /// <para> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </para> /// </remarks> public static string AssemblyFileName(Assembly myAssembly) { #if NETCF // This is not very good because it assumes that only // the entry assembly can be an EXE. In fact multiple // EXEs can be loaded in to a process. string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly); string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation); if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0) { // assembly is entry assembly return assemblyShortName + ".exe"; } else { // assembly is not entry assembly return assemblyShortName + ".dll"; } #else return System.IO.Path.GetFileName(myAssembly.Location); #endif } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="relativeType">A sibling type to use to load the type.</param> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="M:Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified, it will be loaded from the assembly /// containing the specified relative type. If the type is not found in the assembly /// then all the loaded assemblies will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) { return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="M:Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified it will be loaded from the /// assembly that is directly calling this method. If the type is not found /// in the assembly then all the loaded assemblies will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) { return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); } /// <summary> /// Loads the type specified in the type string. /// </summary> /// <param name="relativeAssembly">An assembly to load the type from.</param> /// <param name="typeName">The name of the type to load.</param> /// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param> /// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param> /// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns> /// <remarks> /// <para> /// If the type name is fully qualified, i.e. if contains an assembly name in /// the type name, the type will be loaded from the system using /// <see cref="M:Type.GetType(string,bool)"/>. /// </para> /// <para> /// If the type name is not fully qualified it will be loaded from the specified /// assembly. If the type is not found in the assembly then all the loaded assemblies /// will be searched for the type. /// </para> /// </remarks> public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) { // Check if the type name specifies the assembly name if(typeName.IndexOf(',') == -1) { //LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); #if NETCF return relativeAssembly.GetType(typeName, throwOnError); #else // Attempt to lookup the type from the relativeAssembly Type type = relativeAssembly.GetType(typeName, false, ignoreCase); if (type != null) { // Found type in relative assembly //LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); return type; } Assembly[] loadedAssemblies = null; try { loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); } catch(System.Security.SecurityException) { // Insufficient permissions to get the list of loaded assemblies } if (loadedAssemblies != null) { // Search the loaded assemblies for the type foreach (Assembly assembly in loadedAssemblies) { type = assembly.GetType(typeName, false, ignoreCase); if (type != null) { // Found type in loaded assembly LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies."); return type; } } } // Didn't find the type if (throwOnError) { throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies"); } return null; #endif } else { // Includes explicit assembly name //LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type"); #if NETCF // In NETCF 2 and 3 arg versions seem to behave differently // https://issues.apache.org/jira/browse/LOG4NET-113 return Type.GetType(typeName, throwOnError); #else return Type.GetType(typeName, throwOnError, ignoreCase); #endif } } /// <summary> /// Generate a new guid /// </summary> /// <returns>A new Guid</returns> /// <remarks> /// <para> /// Generate a new guid /// </para> /// </remarks> public static Guid NewGuid() { #if NETCF_1_0 return PocketGuid.NewGuid(); #else return Guid.NewGuid(); #endif } /// <summary> /// Create an <see cref="ArgumentOutOfRangeException"/> /// </summary> /// <param name="parameterName">The name of the parameter that caused the exception</param> /// <param name="actualValue">The value of the argument that causes this exception</param> /// <param name="message">The message that describes the error</param> /// <returns>the ArgumentOutOfRangeException object</returns> /// <remarks> /// <para> /// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class /// with a specified error message, the parameter name, and the value /// of the argument. /// </para> /// <para> /// The Compact Framework does not support the 3 parameter constructor for the /// <see cref="ArgumentOutOfRangeException"/> type. This method provides an /// implementation that works for all platforms. /// </para> /// </remarks> public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) { #if NETCF_1_0 return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]"); #elif NETCF_2_0 return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]"); #else return new ArgumentOutOfRangeException(parameterName, actualValue, message); #endif } /// <summary> /// Parse a string into an <see cref="Int32"/> value /// </summary> /// <param name="s">the string to parse</param> /// <param name="val">out param where the parsed value is placed</param> /// <returns><c>true</c> if the string was able to be parsed into an integer</returns> /// <remarks> /// <para> /// Attempts to parse the string into an integer. If the string cannot /// be parsed then this method returns <c>false</c>. The method does not throw an exception. /// </para> /// </remarks> public static bool TryParse(string s, out int val) { #if NETCF val = 0; try { val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); return true; } catch { } return false; #else // Initialise out param val = 0; try { double doubleVal; if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt32(doubleVal); return true; } } catch { // Ignore exception, just return false } return false; #endif } /// <summary> /// Parse a string into an <see cref="Int64"/> value /// </summary> /// <param name="s">the string to parse</param> /// <param name="val">out param where the parsed value is placed</param> /// <returns><c>true</c> if the string was able to be parsed into an integer</returns> /// <remarks> /// <para> /// Attempts to parse the string into an integer. If the string cannot /// be parsed then this method returns <c>false</c>. The method does not throw an exception. /// </para> /// </remarks> public static bool TryParse(string s, out long val) { #if NETCF val = 0; try { val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); return true; } catch { } return false; #else // Initialise out param val = 0; try { double doubleVal; if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt64(doubleVal); return true; } } catch { // Ignore exception, just return false } return false; #endif } /// <summary> /// Parse a string into an <see cref="Int16"/> value /// </summary> /// <param name="s">the string to parse</param> /// <param name="val">out param where the parsed value is placed</param> /// <returns><c>true</c> if the string was able to be parsed into an integer</returns> /// <remarks> /// <para> /// Attempts to parse the string into an integer. If the string cannot /// be parsed then this method returns <c>false</c>. The method does not throw an exception. /// </para> /// </remarks> public static bool TryParse(string s, out short val) { #if NETCF val = 0; try { val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); return true; } catch { } return false; #else // Initialise out param val = 0; try { double doubleVal; if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt16(doubleVal); return true; } } catch { // Ignore exception, just return false } return false; #endif } /// <summary> /// Lookup an application setting /// </summary> /// <param name="key">the application settings key to lookup</param> /// <returns>the value for the key, or <c>null</c></returns> /// <remarks> /// <para> /// Configuration APIs are not supported under the Compact Framework /// </para> /// </remarks> public static string GetAppSetting(string key) { try { #if NETCF // Configuration APIs are not suported under the Compact Framework #elif NET_2_0 return ConfigurationManager.AppSettings[key]; #else return ConfigurationSettings.AppSettings[key]; #endif } catch(Exception ex) { // If an exception is thrown here then it looks like the config file does not parse correctly. LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); } return null; } /// <summary> /// Convert a path into a fully qualified local file path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The fully qualified path.</returns> /// <remarks> /// <para> /// Converts the path specified to a fully /// qualified path. If the path is relative it is /// taken as relative from the application base /// directory. /// </para> /// <para> /// The path specified must be a local file path, a URI is not supported. /// </para> /// </remarks> public static string ConvertToFullPath(string path) { if (path == null) { throw new ArgumentNullException("path"); } string baseDirectory = ""; try { string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; if (applicationBaseDirectory != null) { // applicationBaseDirectory may be a URI not a local file path Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); if (applicationBaseDirectoryUri.IsFile) { baseDirectory = applicationBaseDirectoryUri.LocalPath; } } } catch { // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory } if (baseDirectory != null && baseDirectory.Length > 0) { // Note that Path.Combine will return the second path if it is rooted return Path.GetFullPath(Path.Combine(baseDirectory, path)); } return Path.GetFullPath(path); } /// <summary> /// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity. /// </summary> /// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns> /// <remarks> /// <para> /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. /// </para> /// </remarks> public static Hashtable CreateCaseInsensitiveHashtable() { #if NETCF_1_0 return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); #elif NETCF_2_0 || NET_2_0 || MONO_2_0 return new Hashtable(StringComparer.OrdinalIgnoreCase); #else return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(); #endif } #endregion Public Static Methods #region Private Static Methods #if NETCF private static string NativeEntryAssemblyLocation { get { StringBuilder moduleName = null; IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero); if (moduleHandle != IntPtr.Zero) { moduleName = new StringBuilder(255); if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0) { throw new NotSupportedException(NativeError.GetLastError().ToString()); } } else { throw new NotSupportedException(NativeError.GetLastError().ToString()); } return moduleName.ToString(); } } [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] private static extern IntPtr GetModuleHandle(IntPtr ModuleName); [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] private static extern Int32 GetModuleFileName( IntPtr hModule, StringBuilder ModuleName, Int32 cch); #endif #endregion Private Static Methods #region Public Static Fields /// <summary> /// Gets an empty array of types. /// </summary> /// <remarks> /// <para> /// The <c>Type.EmptyTypes</c> field is not available on /// the .NET Compact Framework 1.0. /// </para> /// </remarks> public static readonly Type[] EmptyTypes = new Type[0]; #endregion Public Static Fields #region Private Static Fields /// <summary> /// The fully qualified type of the SystemInfo class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(SystemInfo); /// <summary> /// Cache the host name for the current machine /// </summary> private static string s_hostName; /// <summary> /// Cache the application friendly name /// </summary> private static string s_appFriendlyName; /// <summary> /// Text to output when a <c>null</c> is encountered. /// </summary> private static string s_nullText; /// <summary> /// Text to output when an unsupported feature is requested. /// </summary> private static string s_notAvailableText; /// <summary> /// Start time for the current process. /// </summary> private static DateTime s_processStartTime = DateTime.Now; #endregion #region Compact Framework Helper Classes #if NETCF_1_0 /// <summary> /// Generate GUIDs on the .NET Compact Framework. /// </summary> public class PocketGuid { // guid variant types private enum GuidVariant { ReservedNCS = 0x00, Standard = 0x02, ReservedMicrosoft = 0x06, ReservedFuture = 0x07 } // guid version types private enum GuidVersion { TimeBased = 0x01, Reserved = 0x02, NameBased = 0x03, Random = 0x04 } // constants that are used in the class private class Const { // number of bytes in guid public const int ByteArraySize = 16; // multiplex variant info public const int VariantByte = 8; public const int VariantByteMask = 0x3f; public const int VariantByteShift = 6; // multiplex version info public const int VersionByte = 7; public const int VersionByteMask = 0x0f; public const int VersionByteShift = 4; } // imports for the crypto api functions private class WinApi { public const uint PROV_RSA_FULL = 1; public const uint CRYPT_VERIFYCONTEXT = 0xf0000000; [DllImport("CoreDll.dll")] public static extern bool CryptAcquireContext( ref IntPtr phProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags); [DllImport("CoreDll.dll")] public static extern bool CryptReleaseContext( IntPtr hProv, uint dwFlags); [DllImport("CoreDll.dll")] public static extern bool CryptGenRandom( IntPtr hProv, int dwLen, byte[] pbBuffer); } // all static methods private PocketGuid() { } /// <summary> /// Return a new System.Guid object. /// </summary> public static Guid NewGuid() { IntPtr hCryptProv = IntPtr.Zero; Guid guid = Guid.Empty; try { // holds random bits for guid byte[] bits = new byte[Const.ByteArraySize]; // get crypto provider handle if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null, WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT)) { throw new SystemException( "Failed to acquire cryptography handle."); } // generate a 128 bit (16 byte) cryptographically random number if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits)) { throw new SystemException( "Failed to generate cryptography random bytes."); } // set the variant bits[Const.VariantByte] &= Const.VariantByteMask; bits[Const.VariantByte] |= ((int)GuidVariant.Standard << Const.VariantByteShift); // set the version bits[Const.VersionByte] &= Const.VersionByteMask; bits[Const.VersionByte] |= ((int)GuidVersion.Random << Const.VersionByteShift); // create the new System.Guid object guid = new Guid(bits); } finally { // release the crypto provider handle if (hCryptProv != IntPtr.Zero) WinApi.CryptReleaseContext(hCryptProv, 0); } return guid; } } #endif #endregion Compact Framework Helper Classes } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; namespace Microsoft.SqlServer.Server { // Utilities for manipulating smi-related metadata. // // Since this class is built on top of SMI, SMI should not have a dependency on this class // // These are all based off of knowing the clr type of the value // as an ExtendedClrTypeCode enum for rapid access. internal class MetaDataUtilsSmi { internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1); internal const long InvalidMaxLength = -2; // Standard type inference map to get SqlDbType when all you know is the value's type (typecode) // This map's index is off by one (add one to typecode locate correct entry) in order // to support ExtendedSqlDbType.Invalid // This array is meant to be accessed from InferSqlDbTypeFromTypeCode. private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = { InvalidSqlDbType, // Invalid extended type code SqlDbType.Bit, // System.Boolean SqlDbType.TinyInt, // System.Byte SqlDbType.NVarChar, // System.Char SqlDbType.DateTime, // System.DateTime InvalidSqlDbType, // System.DBNull doesn't have an inferable SqlDbType SqlDbType.Decimal, // System.Decimal SqlDbType.Float, // System.Double InvalidSqlDbType, // null reference doesn't have an inferable SqlDbType SqlDbType.SmallInt, // System.Int16 SqlDbType.Int, // System.Int32 SqlDbType.BigInt, // System.Int64 InvalidSqlDbType, // System.SByte doesn't have an inferable SqlDbType SqlDbType.Real, // System.Single SqlDbType.NVarChar, // System.String InvalidSqlDbType, // System.UInt16 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt32 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt64 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.Object doesn't have an inferable SqlDbType SqlDbType.VarBinary, // System.ByteArray SqlDbType.NVarChar, // System.CharArray SqlDbType.UniqueIdentifier, // System.Guid SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBinary SqlDbType.Bit, // System.Data.SqlTypes.SqlBoolean SqlDbType.TinyInt, // System.Data.SqlTypes.SqlByte SqlDbType.DateTime, // System.Data.SqlTypes.SqlDateTime SqlDbType.Float, // System.Data.SqlTypes.SqlDouble SqlDbType.UniqueIdentifier, // System.Data.SqlTypes.SqlGuid SqlDbType.SmallInt, // System.Data.SqlTypes.SqlInt16 SqlDbType.Int, // System.Data.SqlTypes.SqlInt32 SqlDbType.BigInt, // System.Data.SqlTypes.SqlInt64 SqlDbType.Money, // System.Data.SqlTypes.SqlMoney SqlDbType.Decimal, // System.Data.SqlTypes.SqlDecimal SqlDbType.Real, // System.Data.SqlTypes.SqlSingle SqlDbType.NVarChar, // System.Data.SqlTypes.SqlString SqlDbType.NVarChar, // System.Data.SqlTypes.SqlChars SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBytes SqlDbType.Xml, // System.Data.SqlTypes.SqlXml SqlDbType.Structured, // System.Collections.IEnumerable, used for TVPs it must return IDataRecord SqlDbType.Structured, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> SqlDbType.Time, // System.TimeSpan SqlDbType.DateTimeOffset, // System.DateTimeOffset }; // Hash table to map from clr type object to ExtendedClrTypeCodeMap enum // this HashTable should only be accessed from DetermineExtendedTypeCode and class ctor for setup. private static readonly Hashtable s_typeToExtendedTypeCodeMap; static MetaDataUtilsSmi() { // Set up type mapping hash table // Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating! Hashtable ht = new Hashtable(42); ht.Add(typeof(System.Boolean), ExtendedClrTypeCode.Boolean); ht.Add(typeof(System.Byte), ExtendedClrTypeCode.Byte); ht.Add(typeof(System.Char), ExtendedClrTypeCode.Char); ht.Add(typeof(System.DateTime), ExtendedClrTypeCode.DateTime); ht.Add(typeof(System.DBNull), ExtendedClrTypeCode.DBNull); ht.Add(typeof(System.Decimal), ExtendedClrTypeCode.Decimal); ht.Add(typeof(System.Double), ExtendedClrTypeCode.Double); // lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty ht.Add(typeof(System.Int16), ExtendedClrTypeCode.Int16); ht.Add(typeof(System.Int32), ExtendedClrTypeCode.Int32); ht.Add(typeof(System.Int64), ExtendedClrTypeCode.Int64); ht.Add(typeof(System.SByte), ExtendedClrTypeCode.SByte); ht.Add(typeof(System.Single), ExtendedClrTypeCode.Single); ht.Add(typeof(System.String), ExtendedClrTypeCode.String); ht.Add(typeof(System.UInt16), ExtendedClrTypeCode.UInt16); ht.Add(typeof(System.UInt32), ExtendedClrTypeCode.UInt32); ht.Add(typeof(System.UInt64), ExtendedClrTypeCode.UInt64); ht.Add(typeof(System.Object), ExtendedClrTypeCode.Object); ht.Add(typeof(System.Byte[]), ExtendedClrTypeCode.ByteArray); ht.Add(typeof(System.Char[]), ExtendedClrTypeCode.CharArray); ht.Add(typeof(System.Guid), ExtendedClrTypeCode.Guid); ht.Add(typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary); ht.Add(typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean); ht.Add(typeof(SqlByte), ExtendedClrTypeCode.SqlByte); ht.Add(typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime); ht.Add(typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble); ht.Add(typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid); ht.Add(typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16); ht.Add(typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32); ht.Add(typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64); ht.Add(typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney); ht.Add(typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal); ht.Add(typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle); ht.Add(typeof(SqlString), ExtendedClrTypeCode.SqlString); ht.Add(typeof(SqlChars), ExtendedClrTypeCode.SqlChars); ht.Add(typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes); ht.Add(typeof(SqlXml), ExtendedClrTypeCode.SqlXml); ht.Add(typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader); ht.Add(typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord); ht.Add(typeof(System.TimeSpan), ExtendedClrTypeCode.TimeSpan); ht.Add(typeof(System.DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset); s_typeToExtendedTypeCodeMap = ht; } internal static bool IsCharOrXmlType(SqlDbType type) { return IsUnicodeType(type) || IsAnsiType(type) || type == SqlDbType.Xml; } internal static bool IsUnicodeType(SqlDbType type) { return type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText; } internal static bool IsAnsiType(SqlDbType type) { return type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text; } internal static bool IsBinaryType(SqlDbType type) { return type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Image; } // Does this type use PLP format values? internal static bool IsPlpFormat(SmiMetaData metaData) { return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator || metaData.SqlDbType == SqlDbType.Image || metaData.SqlDbType == SqlDbType.NText || metaData.SqlDbType == SqlDbType.Text || metaData.SqlDbType == SqlDbType.Udt; } // If we know we're only going to use this object to assign to a specific SqlDbType back end object, // we can save some processing time by only checking for the few valid types that can be assigned to the dbType. // This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a // series of if statements, or using a hash table. // NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to // optimize checks of the form '(xxx.GetType() == typeof( YYY ))'. The JIT team claimed at one point that // this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisions. // Given that there's a known SqlDbType, thus a minimal number of comparisions, it's likely this is faster // than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys // must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for // all but the primitive clr types. internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType( SqlDbType dbType, bool isMultiValued, object value ) { ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid; // fast-track null, which is valid for all types if (null == value) { extendedCode = ExtendedClrTypeCode.Empty; } else if (DBNull.Value == value) { extendedCode = ExtendedClrTypeCode.DBNull; } else { switch (dbType) { case SqlDbType.BigInt: if (value.GetType() == typeof(Int64)) extendedCode = ExtendedClrTypeCode.Int64; else if (value.GetType() == typeof(SqlInt64)) extendedCode = ExtendedClrTypeCode.SqlInt64; break; case SqlDbType.Binary: case SqlDbType.VarBinary: case SqlDbType.Image: case SqlDbType.Timestamp: if (value.GetType() == typeof(byte[])) extendedCode = ExtendedClrTypeCode.ByteArray; else if (value.GetType() == typeof(SqlBinary)) extendedCode = ExtendedClrTypeCode.SqlBinary; else if (value.GetType() == typeof(SqlBytes)) extendedCode = ExtendedClrTypeCode.SqlBytes; else if (value.GetType() == typeof(StreamDataFeed)) extendedCode = ExtendedClrTypeCode.Stream; break; case SqlDbType.Bit: if (value.GetType() == typeof(bool)) extendedCode = ExtendedClrTypeCode.Boolean; else if (value.GetType() == typeof(SqlBoolean)) extendedCode = ExtendedClrTypeCode.SqlBoolean; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.VarChar: if (value.GetType() == typeof(string)) extendedCode = ExtendedClrTypeCode.String; if (value.GetType() == typeof(TextDataFeed)) extendedCode = ExtendedClrTypeCode.TextReader; else if (value.GetType() == typeof(SqlString)) extendedCode = ExtendedClrTypeCode.SqlString; else if (value.GetType() == typeof(char[])) extendedCode = ExtendedClrTypeCode.CharArray; else if (value.GetType() == typeof(SqlChars)) extendedCode = ExtendedClrTypeCode.SqlChars; else if (value.GetType() == typeof(char)) extendedCode = ExtendedClrTypeCode.Char; break; case SqlDbType.Date: case SqlDbType.DateTime2: case SqlDbType.DateTime: case SqlDbType.SmallDateTime: if (value.GetType() == typeof(DateTime)) extendedCode = ExtendedClrTypeCode.DateTime; else if (value.GetType() == typeof(SqlDateTime)) extendedCode = ExtendedClrTypeCode.SqlDateTime; break; case SqlDbType.Decimal: if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; else if (value.GetType() == typeof(SqlDecimal)) extendedCode = ExtendedClrTypeCode.SqlDecimal; break; case SqlDbType.Real: if (value.GetType() == typeof(Single)) extendedCode = ExtendedClrTypeCode.Single; else if (value.GetType() == typeof(SqlSingle)) extendedCode = ExtendedClrTypeCode.SqlSingle; break; case SqlDbType.Int: if (value.GetType() == typeof(Int32)) extendedCode = ExtendedClrTypeCode.Int32; else if (value.GetType() == typeof(SqlInt32)) extendedCode = ExtendedClrTypeCode.SqlInt32; break; case SqlDbType.Money: case SqlDbType.SmallMoney: if (value.GetType() == typeof(SqlMoney)) extendedCode = ExtendedClrTypeCode.SqlMoney; else if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; break; case SqlDbType.Float: if (value.GetType() == typeof(SqlDouble)) extendedCode = ExtendedClrTypeCode.SqlDouble; else if (value.GetType() == typeof(Double)) extendedCode = ExtendedClrTypeCode.Double; break; case SqlDbType.UniqueIdentifier: if (value.GetType() == typeof(SqlGuid)) extendedCode = ExtendedClrTypeCode.SqlGuid; else if (value.GetType() == typeof(Guid)) extendedCode = ExtendedClrTypeCode.Guid; break; case SqlDbType.SmallInt: if (value.GetType() == typeof(Int16)) extendedCode = ExtendedClrTypeCode.Int16; else if (value.GetType() == typeof(SqlInt16)) extendedCode = ExtendedClrTypeCode.SqlInt16; break; case SqlDbType.TinyInt: if (value.GetType() == typeof(Byte)) extendedCode = ExtendedClrTypeCode.Byte; else if (value.GetType() == typeof(SqlByte)) extendedCode = ExtendedClrTypeCode.SqlByte; break; case SqlDbType.Variant: // SqlDbType doesn't help us here, call general-purpose function extendedCode = DetermineExtendedTypeCode(value); // Some types aren't allowed for Variants but are for the general-purpos function. // Match behavior of other types and return invalid in these cases. if (ExtendedClrTypeCode.SqlXml == extendedCode) { extendedCode = ExtendedClrTypeCode.Invalid; } break; case SqlDbType.Udt: throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); case SqlDbType.Time: if (value.GetType() == typeof(TimeSpan)) extendedCode = ExtendedClrTypeCode.TimeSpan; break; case SqlDbType.DateTimeOffset: if (value.GetType() == typeof(DateTimeOffset)) extendedCode = ExtendedClrTypeCode.DateTimeOffset; break; case SqlDbType.Xml: if (value.GetType() == typeof(SqlXml)) extendedCode = ExtendedClrTypeCode.SqlXml; if (value.GetType() == typeof(XmlDataFeed)) extendedCode = ExtendedClrTypeCode.XmlReader; else if (value.GetType() == typeof(System.String)) extendedCode = ExtendedClrTypeCode.String; break; case SqlDbType.Structured: if (isMultiValued) { if (value is IEnumerable<SqlDataRecord>) { extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord; } else if (value is DbDataReader) { extendedCode = ExtendedClrTypeCode.DbDataReader; } } break; default: // Leave as invalid break; } } return extendedCode; } // Method to map from Type to ExtendedTypeCode static internal ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType) { object result = s_typeToExtendedTypeCodeMap[clrType]; ExtendedClrTypeCode resultCode; if (null == result) { resultCode = ExtendedClrTypeCode.Invalid; } else { resultCode = (ExtendedClrTypeCode)result; } return resultCode; } // Returns the ExtendedClrTypeCode that describes the given value static internal ExtendedClrTypeCode DetermineExtendedTypeCode(object value) { ExtendedClrTypeCode resultCode; if (null == value) { resultCode = ExtendedClrTypeCode.Empty; } else { resultCode = DetermineExtendedTypeCodeFromType(value.GetType()); } return resultCode; } // returns a sqldbtype for the given type code static internal SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode) { Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!"); return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1]; } // Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to // infer types should use InferSqlDbTypeFromType_Katmai. static internal SqlDbType InferSqlDbTypeFromType(Type type) { ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type); SqlDbType returnType; if (ExtendedClrTypeCode.Invalid == typeCode) { returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error } else { returnType = InferSqlDbTypeFromTypeCode(typeCode); } return returnType; } // Inference rules changed for Katmai-or-later-only cases. Only features that are guaranteed to be // running against Katmai and don't have backward compat issues should call this code path. // example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2 // when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because // of greater range that can handle all DateTime values. static internal SqlDbType InferSqlDbTypeFromType_Katmai(Type type) { SqlDbType returnType = InferSqlDbTypeFromType(type); if (SqlDbType.DateTime == returnType) { returnType = SqlDbType.DateTime2; } return returnType; } static internal SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source) { if (SqlDbType.Xml == source.SqlDbType) { return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.TypeSpecificNamePart1, source.TypeSpecificNamePart2, source.TypeSpecificNamePart3, true ); } return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, null); } // Convert SqlMetaData instance to an SmiExtendedMetaData instance. internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source) { // now map everything across to the extended metadata object string typeSpecificNamePart1 = null; string typeSpecificNamePart2 = null; string typeSpecificNamePart3 = null; if (SqlDbType.Xml == source.SqlDbType) { typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase; typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema; typeSpecificNamePart3 = source.XmlSchemaCollectionName; } else if (SqlDbType.Udt == source.SqlDbType) { throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); } return new SmiExtendedMetaData(source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.Name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3); } // compare SmiMetaData to SqlMetaData and determine if they are compatible. static internal bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) { return firstMd.SqlDbType == secondMd.SqlDbType && firstMd.MaxLength == secondMd.MaxLength && firstMd.Precision == secondMd.Precision && firstMd.Scale == secondMd.Scale && firstMd.CompareOptions == secondMd.CompareOptions && firstMd.LocaleId == secondMd.LocaleId && firstMd.SqlDbType != SqlDbType.Structured && // SqlMetaData doesn't support Structured types !firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option } // This is a modified version of SmiMetaDataFromSchemaTableRow above // Since CoreCLR doesn't have GetSchema, we need to infer the MetaData from the CLR Type alone static internal SmiExtendedMetaData SmiMetaDataFromType(string colName, Type colType) { // Determine correct SqlDbType. SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType); if (InvalidSqlDbType == colDbType) { // Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise we error out. if (typeof(object) == colType) { colDbType = SqlDbType.VarBinary; } else { throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } } // Determine metadata modifier values per type (maxlength, precision, scale, etc) long maxLength = 0; byte precision = 0; byte scale = 0; switch (colDbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.NText: case SqlDbType.Real: case SqlDbType.UniqueIdentifier: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Text: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: // These types require no metadata modifiers break; case SqlDbType.Binary: case SqlDbType.VarBinary: // source isn't specifying a size, so assume the Maximum if (SqlDbType.Binary == colDbType) { maxLength = SmiMetaData.MaxBinaryLength; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.Char: case SqlDbType.VarChar: // source isn't specifying a size, so assume the Maximum if (SqlDbType.Char == colDbType) { maxLength = SmiMetaData.MaxANSICharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.NChar: case SqlDbType.NVarChar: // source isn't specifying a size, so assume the Maximum if (SqlDbType.NChar == colDbType) { maxLength = SmiMetaData.MaxUnicodeCharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.Decimal: // Decimal requires precision and scale precision = SmiMetaData.DefaultDecimal.Precision; scale = SmiMetaData.DefaultDecimal.Scale; break; case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: // requires scale scale = SmiMetaData.DefaultTime.Scale; break; case SqlDbType.Udt: case SqlDbType.Structured: default: // These types are not supported from SchemaTable throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } return new SmiExtendedMetaData( colDbType, maxLength, precision, scale, Locale.GetCurrentCultureLcid(), SmiMetaData.GetDefaultForType(colDbType).CompareOptions, false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, colName, null, null, null); } } }
using System; using System.Runtime.InteropServices; using WinForms = System.Windows.Forms; // 31/5/03 namespace NBM.Plugin { /// <summary> /// Stores settings in an INI file. /// </summary> public class IniStorage : IStorage { #region Imported INI functions [DllImport("kernel32.dll")] private static unsafe extern bool WritePrivateProfileStruct(string sectionName, string keyName, void* data, uint dataSize, string fileName); [DllImport("kernel32.dll")] private static unsafe extern bool WritePrivateProfileString(string sectionName, string keyName, byte* data, string fileName); [DllImport("kernel32.dll")] private static extern UInt32 GetPrivateProfileInt(string sectionName, string keyName, uint def, string fileName); [DllImport("kernel32.dll")] private static unsafe extern UInt32 GetPrivateProfileString(string sectionName, string keyName, string defString, byte* destination, uint size, string fileName); [DllImport("kernel32.dll")] private static unsafe extern bool GetPrivateProfileStruct(string sectionName, string keyName, byte* data, uint dataSize, string fileName); #endregion private const string lengthPostFix = "Length__"; private const int maxStringSize = 1024; private const string sectionName = "Settings"; private string fileName; public IniStorage(string fileName, bool perUserSettings) { if (fileName.StartsWith(new string(new char[] { System.IO.Path.DirectorySeparatorChar }))) fileName = fileName.Substring(1); if (perUserSettings) { if (fileName[1] != ':') { // its not an absolute path, so put it in the user app data path. fileName = WinForms.Application.UserAppDataPath + fileName; } else { // it is an absolute path, so append the current username to the directory hierarchy. int pos = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar); string path = fileName.Substring(0, pos); string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; int pos2 = username.LastIndexOf(@"\"); if (pos2 > 0) username = username.Substring(pos2+1); path += System.IO.Path.DirectorySeparatorChar + username; System.IO.Directory.CreateDirectory(path); fileName = path + System.IO.Path.DirectorySeparatorChar + fileName.Substring(pos+1); } } else { // bug fix: if the file is not an absolute path, then it'll put it in the windows // directory. Make the file path relative to the common app data path. if (fileName[1] != ':') { fileName = WinForms.Application.CommonAppDataPath + fileName; } } this.fileName = fileName; } private IniStorage(string fileName, string sectionName) { // calculate new filename int pos = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar); string path = fileName.Substring(0, pos); path += System.IO.Path.DirectorySeparatorChar + sectionName; System.IO.Directory.CreateDirectory(path); path += System.IO.Path.DirectorySeparatorChar + fileName.Substring(pos+1); this.fileName = path; } #region Close methods public void Close() { } public void Flush() { } #endregion #region Sub-section methods public IStorage CreateSubSection(string name) { return new IniStorage(this.fileName, name); } #endregion #region Write methods private unsafe void WriteASCIIString(string name, string val) { byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(val); fixed (byte* bp = b) { WritePrivateProfileString(sectionName, name, bp, this.fileName); } } private void WriteUNICODEString(string name, string val) { byte[] b = System.Text.UnicodeEncoding.Unicode.GetBytes(val); // then write the unicode string as a series of bytes Write(name, b); } private unsafe void WriteBytes(string name, byte[] b) { // write length Write(name + lengthPostFix, b.Length); fixed (byte* pos = b) { WritePrivateProfileStruct(sectionName, name, pos, (uint)b.Length, this.fileName); } } public void Write(string name, string val) { WriteUNICODEString(name, val); } public void Write(string name, byte[] val) { WriteBytes(name, val); } public void Write(string name, bool val) { Write(name, val ? 1 : 0); } public void Write(string name, char val) { Write(name, (Int32)val); } public void Write(string name, byte val) { Write(name, (Int32)val); } public void Write(string name, char[] val) { Write(name, new string(val)); } public void Write(string name, Single val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, Double val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, Int16 val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, Int32 val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, Int64 val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, UInt16 val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, UInt32 val) { WriteASCIIString(name, val.ToString()); } public void Write(string name, UInt64 val) { WriteASCIIString(name, val.ToString()); } #endregion #region Read methods private unsafe string ReadASCIIString(string name, string def) { byte[] b = new byte[maxStringSize]; fixed (byte* des = b) { GetPrivateProfileString(sectionName, name, def, des, maxStringSize, this.fileName); } return System.Text.ASCIIEncoding.ASCII.GetString(b); } private unsafe string ReadUNICODEString(string name, string def) { // read length of string from length field uint length = this.ReadUInt32(name + "Length__", maxStringSize); byte[] b = new byte[length]; fixed (byte* des = b) { if (!GetPrivateProfileStruct(sectionName, name, des, length, this.fileName)) return def; } return System.Text.UnicodeEncoding.Unicode.GetString(b); } private unsafe byte[] pReadBytes(string name, byte[] def) { // read length of string from length field uint length = this.ReadUInt32(name + "Length__", maxStringSize); byte[] b = new byte[length]; fixed (byte* des = b) { if (!GetPrivateProfileStruct(sectionName, name, des, length, this.fileName)) return def; } return b; } public bool ReadBool(string name, bool def) { return ReadInt32(name, def ? 1 : 0) == 1; } public char ReadChar(string name, char def) { return (char)ReadInt32(name, (Int32)def); } public byte ReadByte(string name, byte def) { return (byte)ReadInt32(name, (Int32)def); } public string ReadString(string name, string def) { return ReadUNICODEString(name, def); } public byte[] ReadBytes(string name, byte[] def) { return pReadBytes(name, def); } public char[] ReadChars(string name, char[] def) { return ReadUNICODEString(name, new string(def)).ToCharArray(); } public byte[] ReadBytes(string name) { return ReadBytes(name, null); } public char[] ReadChars(string name) { return ReadChars(name, null); } public Single ReadSingle(string name, Single def) { return Single.Parse(ReadASCIIString(name, def.ToString())); } public Double ReadDouble(string name, Double def) { return Double.Parse(ReadASCIIString(name, def.ToString())); } public Int16 ReadInt16(string name, Int16 def) { return Int16.Parse(ReadASCIIString(name, def.ToString())); } public Int32 ReadInt32(string name, Int32 def) { return Int32.Parse(ReadASCIIString(name, def.ToString())); } public Int64 ReadInt64(string name, Int64 def) { return Int64.Parse(ReadASCIIString(name, def.ToString())); } public UInt16 ReadUInt16(string name, UInt16 def) { return UInt16.Parse(ReadASCIIString(name, def.ToString())); } public UInt32 ReadUInt32(string name, UInt32 def) { return UInt32.Parse(ReadASCIIString(name, def.ToString())); } public UInt64 ReadUInt64(string name, UInt64 def) { return UInt64.Parse(ReadASCIIString(name, def.ToString())); } #endregion } }
using System; using System.Collections.Generic; using System.IO; namespace DataTool.ConvertLogic { public class BitOggstream : IDisposable { private readonly BinaryWriter _os; private byte _bitBuffer; private uint _bitsStored; private enum SizeEnum { HeaderBytes = 27, MaxSegments = 255, SegmentSize = 255 } private uint _payloadBytes; private bool _first; private bool _continued; private readonly byte[] _pageBuffer = new byte[(int) SizeEnum.HeaderBytes + (int) SizeEnum.MaxSegments + (int) SizeEnum.SegmentSize * (int) SizeEnum.MaxSegments]; private uint _granule; private uint _seqno; public BitOggstream(BinaryWriter writer) { _os = writer; _bitBuffer = 0; _bitsStored = 0; _payloadBytes = 0; _first = true; _continued = false; _granule = 0; _seqno = 0; } public void PutBit(bool bit) { if (bit) { _bitBuffer |= (byte) (1 << (byte) _bitsStored); } _bitsStored++; if (_bitsStored == 8) { FlushBits(); } } public void SetGranule(uint g) { _granule = g; } public void FlushBits() { if (_bitsStored == 0) return; if (_payloadBytes == (int) SizeEnum.SegmentSize * (int) SizeEnum.MaxSegments) { throw new Exception("ran out of space in an Ogg packet"); // flush_page(true); } _pageBuffer[(int) SizeEnum.HeaderBytes + (int) SizeEnum.MaxSegments + _payloadBytes] = _bitBuffer; _payloadBytes++; _bitsStored = 0; _bitBuffer = 0; } public static byte[] Int2Le(uint data) { byte[] b = new byte[4]; b[0] = (byte) data; b[1] = (byte) ((data >> 8) & 0xFF); b[2] = (byte) ((data >> 16) & 0xFF); b[3] = (byte) ((data >> 24) & 0xFF); return b; } private void Write32Le(IList<byte> bytes, int startIndex, uint val) { byte[] valBytes = Int2Le(val); for (int i = 0; i < 4; i++) { bytes[i + startIndex] = valBytes[i]; // bytes[i + startIndex] = 255; // bytes[i + startIndex] = (byte) (val & 0xFF); // val >>= 8; } } private static readonly uint[] CRCLookup = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; private static uint Checksum(byte[] data, int bytes) { if (data == null) throw new ArgumentNullException(nameof(data)); uint crcReg = 0; int i; for (i = 0; i < bytes; ++i) crcReg = (crcReg << 8) ^ CRCLookup[((crcReg >> 24) & 0xff) ^ data[i]]; return crcReg; } public void FlushPage(bool nextContinued = false, bool last = false) { if (_payloadBytes != (int) SizeEnum.SegmentSize * (int) SizeEnum.MaxSegments) { FlushBits(); } if (_payloadBytes != 0) { uint segments = (_payloadBytes + (int) SizeEnum.SegmentSize) / (int) SizeEnum.SegmentSize; // intentionally round up if (segments == (int) SizeEnum.MaxSegments + 1) { segments = (int) SizeEnum.MaxSegments; // at max eschews the final 0 } // move payload back for (uint i = 0; i < _payloadBytes; i++) { _pageBuffer[(int) SizeEnum.HeaderBytes + segments + i] = _pageBuffer[(int) SizeEnum.HeaderBytes + (int) SizeEnum.MaxSegments + i]; // if ((int) SizeEnum.HeaderBytes + (int) SizeEnum.MaxSegments + i == 4155) { // uint test = (int) SizeEnum.HeaderBytes + segments + i; // Debugger.Break(); // } } _pageBuffer[0] = (byte) 'O'; _pageBuffer[1] = (byte) 'g'; _pageBuffer[2] = (byte) 'g'; _pageBuffer[3] = (byte) 'S'; _pageBuffer[4] = 0; // stream_structure_version _pageBuffer[5] = (byte) ((_continued ? 1 : 0) | (_first ? 2 : 0) | (last ? 4 : 0)); // header_type_flag Write32Le(_pageBuffer, 6, _granule); // granule low bits Write32Le(_pageBuffer, 10, 0); // granule high bits if (_granule == 0xFFFFFFFF) { Write32Le(_pageBuffer, 10, 0xFFFFFFFF); } Write32Le(_pageBuffer, 14, 1); // stream serial number Write32Le(_pageBuffer, 18, _seqno); // page sequence number Write32Le(_pageBuffer, 22, 0); // checksum (0 for now) _pageBuffer[26] = (byte) segments; // segment count // lacing values for (uint i = 0, bytesLeft = _payloadBytes; i < segments; i++) { if (bytesLeft >= (int) SizeEnum.SegmentSize) { bytesLeft -= (int) SizeEnum.SegmentSize; _pageBuffer[27 + i] = (int) SizeEnum.SegmentSize; } else { _pageBuffer[27 + i] = (byte) bytesLeft; } } // checksum Write32Le(_pageBuffer, 22, Checksum(_pageBuffer, (int) ((int) SizeEnum.HeaderBytes + segments + _payloadBytes))); // output to ostream for (uint i = 0; i < (int) SizeEnum.HeaderBytes + segments + _payloadBytes; i++) { _os.Write(_pageBuffer[i]); } _seqno++; _first = false; _continued = nextContinued; _payloadBytes = 0; } } public void Write(BitUint bui) { for (int i = 0; i < bui.BitSize; i++) { // put_bit((bui.Value & (1U << i)) != 0); PutBit((bui.Value & (1U << i)) != 0); } } public void Write(Sound.VorbisPacketHeader vph) { BitUint t = new BitUint(8, vph.m_type); Write(t); for (uint i = 0; i < 6; i++) { BitUint c = new BitUint(8, (byte) Sound.VorbisPacketHeader.VORBIS_STR[i]); Write(c); } } public void Dispose() { FlushPage(); } } public class BitUint { public uint Value; public readonly uint BitSize; public BitUint(uint size) { BitSize = size; Value = 0; } public BitUint(uint size, uint v) { BitSize = size; Value = v; } public static implicit operator uint(BitUint bitUint) { return bitUint.Value; } public int AsInt() { return (int) Value; } } }
using System.Collections.Generic; using NUnit.Framework; using Saltarelle.Compiler.JSModel; using Saltarelle.Compiler.JSModel.Expressions; using Saltarelle.Compiler.JSModel.Statements; namespace Saltarelle.Compiler.Tests.OutputFormatterTests { [TestFixture] public class NonMinifiedOutputTests { private void AssertCorrect(JsExpression expr, string expected) { var actual = OutputFormatter.Format(expr); Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n"))); } private void AssertCorrect(JsStatement stmt, string expected) { var actual = OutputFormatter.Format(stmt); Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n"))); } [Test] public void ArrayLiteralWorks() { AssertCorrect(JsExpression.ArrayLiteral(), "[]"); AssertCorrect(JsExpression.ArrayLiteral(JsExpression.Number(1)), "[1]"); AssertCorrect(JsExpression.ArrayLiteral(JsExpression.Number(1), JsExpression.Number(2)), "[1, 2]"); AssertCorrect(JsExpression.ArrayLiteral(JsExpression.Number(1), null, JsExpression.Number(2), null), "[1, , 2, ]"); } [Test] public void IndexingWorks() { AssertCorrect(JsExpression.Binary(ExpressionNodeType.Index, JsExpression.Binary(ExpressionNodeType.Index, JsExpression.Number(1), JsExpression.Number(2) ), JsExpression.Number(3) ), "1[2][3]"); } [Test] public void StringLiteralsAreCorrectlyEncoded() { AssertCorrect(JsExpression.String("x"), "'x'"); AssertCorrect(JsExpression.String("\""), "'\"'"); AssertCorrect(JsExpression.String("'"), "\"'\""); AssertCorrect(JsExpression.String("\r\n/\\"), "'\\r\\n/\\\\'"); } [Test] public void RegularExpressionLiteralsAreCorrectlyEncoded() { AssertCorrect(JsExpression.Regexp("x"), "/x/"); AssertCorrect(JsExpression.Regexp("\""), "/\"/"); AssertCorrect(JsExpression.Regexp("/"), "/\\//"); AssertCorrect(JsExpression.Regexp("'"), "/'/"); AssertCorrect(JsExpression.Regexp("\""), "/\"/"); AssertCorrect(JsExpression.Regexp("\r\n/\\"), "/\\r\\n\\/\\\\/"); AssertCorrect(JsExpression.Regexp("x", "g"), "/x/g"); } [Test] public void NullLiteralWorks() { AssertCorrect(JsExpression.Null, "null"); } [Test] public void BooleanLiteralsWork() { AssertCorrect(JsExpression.True, "true"); AssertCorrect(JsExpression.False, "false"); } [Test] public void NumbersAreCorrectlyRepresented() { AssertCorrect(JsExpression.Number(1), "1"); AssertCorrect(JsExpression.Number(1.25), "1.25"); AssertCorrect(JsExpression.Number(double.PositiveInfinity), "Infinity"); AssertCorrect(JsExpression.Number(double.NegativeInfinity), "-Infinity"); AssertCorrect(JsExpression.Number(double.NaN), "NaN"); } [Test] public void IdentifierIsOutputCorrectly() { AssertCorrect(JsExpression.Identifier("SomeIdentifier"), "SomeIdentifier"); } [Test] public void ObjectLiteralIsOutputCorrectly() { AssertCorrect(JsExpression.ObjectLiteral(), "{}"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1))), "{ x: 1 }"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1)), new JsObjectLiteralProperty("y", JsExpression.Number(2)), new JsObjectLiteralProperty("z", JsExpression.Number(3))), "{ x: 1, y: 2, z: 3 }"); } [Test] public void ObjectLiteralWithFunctionValuesAreOutputOnMultipleLines() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1)), new JsObjectLiteralProperty("y", JsExpression.FunctionDefinition(new string[0], JsStatement.Return())), new JsObjectLiteralProperty("z", JsExpression.Number(3))), @"{ x: 1, y: function() { return; }, z: 3 }"); } [Test] public void ObjectLiteralWithNumericPropertyWorks() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("1", JsExpression.Number(2))), "{ '1': 2 }"); } [Test] public void ObjectLiteralWithInvalidIdentifierPropertyWorks() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a\\b", JsExpression.Number(1))), "{ 'a\\\\b': 1 }"); } [Test] public void FunctionDefinitionExpressionIsCorrectlyOutput() { AssertCorrect(JsExpression.FunctionDefinition(new string[0], JsStatement.Return(JsExpression.Null)), "function() {\n\treturn null;\n}"); AssertCorrect(JsExpression.FunctionDefinition(new [] { "a", "b" }, JsStatement.Return(JsExpression.Null)), "function(a, b) {\n\treturn null;\n}"); AssertCorrect(JsExpression.FunctionDefinition(new string[0], JsStatement.Return(JsExpression.Null), name: "myFunction"), "function myFunction() {\n\treturn null;\n}"); } [Test] public void UnaryOperatorsAreCorrectlyOutput() { var operators = new Dictionary<ExpressionNodeType, string> { { ExpressionNodeType.TypeOf, "typeof({0})" }, { ExpressionNodeType.LogicalNot, "!{0}" }, { ExpressionNodeType.Negate, "-{0}" }, { ExpressionNodeType.Positive, "+{0}" }, { ExpressionNodeType.PrefixPlusPlus, "++{0}" }, { ExpressionNodeType.PrefixMinusMinus, "--{0}" }, { ExpressionNodeType.PostfixPlusPlus, "{0}++" }, { ExpressionNodeType.PostfixMinusMinus, "{0}--" }, { ExpressionNodeType.Delete, "delete {0}" }, { ExpressionNodeType.Void, "void({0})" }, { ExpressionNodeType.BitwiseNot, "~{0}" }, }; for (var oper = ExpressionNodeType.UnaryFirst; oper <= ExpressionNodeType.UnaryLast; oper++) { Assert.That(operators.ContainsKey(oper), string.Format("Unexpected operator {0}", oper)); var expr = JsExpression.Unary(oper, JsExpression.Identifier("a")); AssertCorrect(expr, string.Format(operators[oper], "a")); } } [Test] public void BinaryOperatorssAreCorrectlyOutput() { var operators = new Dictionary<ExpressionNodeType, string> { { ExpressionNodeType.LogicalAnd, "{0} && {1}" }, { ExpressionNodeType.LogicalOr, "{0} || {1}" }, { ExpressionNodeType.NotEqual, "{0} != {1}" }, { ExpressionNodeType.LesserOrEqual, "{0} <= {1}" }, { ExpressionNodeType.GreaterOrEqual, "{0} >= {1}" }, { ExpressionNodeType.Lesser, "{0} < {1}" }, { ExpressionNodeType.Greater, "{0} > {1}" }, { ExpressionNodeType.Equal, "{0} == {1}" }, { ExpressionNodeType.Subtract, "{0} - {1}" }, { ExpressionNodeType.Add, "{0} + {1}" }, { ExpressionNodeType.Modulo, "{0} % {1}" }, { ExpressionNodeType.Divide, "{0} / {1}" }, { ExpressionNodeType.Multiply, "{0} * {1}" }, { ExpressionNodeType.BitwiseAnd, "{0} & {1}" }, { ExpressionNodeType.BitwiseOr, "{0} | {1}" }, { ExpressionNodeType.BitwiseXor, "{0} ^ {1}" }, { ExpressionNodeType.Same, "{0} === {1}" }, { ExpressionNodeType.NotSame, "{0} !== {1}" }, { ExpressionNodeType.LeftShift, "{0} << {1}" }, { ExpressionNodeType.RightShiftSigned, "{0} >> {1}" }, { ExpressionNodeType.RightShiftUnsigned, "{0} >>> {1}" }, { ExpressionNodeType.InstanceOf, "{0} instanceof {1}" }, { ExpressionNodeType.In, "{0} in {1}" }, { ExpressionNodeType.Index, "{0}[{1}]" }, { ExpressionNodeType.Assign, "{0} = {1}" }, { ExpressionNodeType.MultiplyAssign, "{0} *= {1}" }, { ExpressionNodeType.DivideAssign, "{0} /= {1}" }, { ExpressionNodeType.ModuloAssign, "{0} %= {1}" }, { ExpressionNodeType.AddAssign, "{0} += {1}" }, { ExpressionNodeType.SubtractAssign, "{0} -= {1}" }, { ExpressionNodeType.LeftShiftAssign, "{0} <<= {1}" }, { ExpressionNodeType.RightShiftSignedAssign, "{0} >>= {1}" }, { ExpressionNodeType.RightShiftUnsignedAssign, "{0} >>>= {1}" }, { ExpressionNodeType.BitwiseAndAssign, "{0} &= {1}" }, { ExpressionNodeType.BitwiseOrAssign, "{0} |= {1}" }, { ExpressionNodeType.BitwiseXorAssign, "{0} ^= {1}" }, }; for (var oper = ExpressionNodeType.BinaryFirst; oper <= ExpressionNodeType.BinaryLast; oper++) { Assert.That(operators.ContainsKey(oper), string.Format("Unexpected operator {0}", oper)); var expr = JsExpression.Binary(oper, JsExpression.Identifier("a"), JsExpression.Identifier("b")); AssertCorrect(expr, string.Format(operators[oper], "a", "b")); } } [Test] public void ThisIsCorrectlyOutput() { AssertCorrect(JsExpression.This, "this"); } [Test] public void CommentsAreCorrectlyOutput() { AssertCorrect(JsStatement.Comment("Line 1"), "//Line 1\n"); AssertCorrect(JsStatement.Comment(" With spaces "), "// With spaces \n"); AssertCorrect(JsStatement.Comment(" With\n Multiple\n Lines"), "// With\n// Multiple\n// Lines\n"); } [Test] public void BlockStatementsAreCorrectlyOutput() { AssertCorrect(JsStatement.Block(new JsStatement[0]), "{\n}\n"); AssertCorrect(JsStatement.Block(new[] { JsStatement.Comment("X") }), "{\n\t//X\n}\n"); AssertCorrect(JsStatement.Block(new[] { JsStatement.Comment("X"), JsStatement.Comment("Y") }), "{\n\t//X\n\t//Y\n}\n"); } [Test] public void VariableDeclarationStatementsAreCorrectlyOutput() { AssertCorrect(JsStatement.Var(new[] { JsStatement.Declaration("i", null) }), "var i;\n"); AssertCorrect(JsStatement.Var(new[] { JsStatement.Declaration("i", null), JsStatement.Declaration("j", null) }), "var i, j;\n"); AssertCorrect(JsStatement.Var(new[] { JsStatement.Declaration("i", JsExpression.Number(0)) }), "var i = 0;\n"); AssertCorrect(JsStatement.Var(new[] { JsStatement.Declaration("i", JsExpression.Number(0)), JsStatement.Declaration("j", JsExpression.Number(1)) }), "var i = 0, j = 1;\n"); AssertCorrect(JsStatement.Var(new[] { JsStatement.Declaration("i", JsExpression.Number(0)), JsStatement.Declaration("j", null) }), "var i = 0, j;\n"); } [Test] public void ExpressionStatementsAreCorrectlyOutput() { AssertCorrect((JsStatement)JsExpression.This, "this;\n"); } [Test] public void ForStatementsAreCorrectlyOutput() { AssertCorrect(JsStatement.For(JsStatement.Var(JsStatement.Declaration("i", JsExpression.Number(0))), JsExpression.Lesser(JsExpression.Identifier("i"), JsExpression.Number(10)), JsExpression.PostfixPlusPlus(JsExpression.Identifier("i")), JsStatement.EmptyBlock), "for (var i = 0; i < 10; i++) {\n}\n"); AssertCorrect(JsStatement.For(JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(0)), JsExpression.Lesser(JsExpression.Identifier("i"), JsExpression.Number(10)), JsExpression.PostfixPlusPlus(JsExpression.Identifier("i")), JsStatement.EmptyBlock), "for (i = 0; i < 10; i++) {\n}\n"); AssertCorrect(JsStatement.For(JsStatement.Var(JsStatement.Declaration("i", JsExpression.Number(0)), JsStatement.Declaration("j", JsExpression.Number(1))), JsExpression.Lesser(JsExpression.Identifier("i"), JsExpression.Number(10)), JsExpression.Comma(JsExpression.PostfixPlusPlus(JsExpression.Identifier("i")), JsExpression.PostfixPlusPlus(JsExpression.Identifier("j"))), JsStatement.EmptyBlock), "for (var i = 0, j = 1; i < 10; i++, j++) {\n}\n"); AssertCorrect(JsStatement.For(JsStatement.Empty, null, null, JsStatement.EmptyBlock), "for (;;) {\n}\n"); } [Test] public void ForInStatementsAreCorrectlyOutput() { AssertCorrect(JsStatement.ForIn("x", JsExpression.Identifier("o"), JsStatement.EmptyBlock, true), "for (var x in o) {\n}\n"); AssertCorrect(JsStatement.ForIn("x", JsExpression.Identifier("o"), JsStatement.EmptyBlock, false), "for (x in o) {\n}\n"); } [Test] public void EmptyStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Empty, ";\n"); } [Test] public void IfStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.If(JsExpression.True, JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(0)), null), "if (true) {\n\ti = 0;\n}\n"); AssertCorrect(JsStatement.If(JsExpression.True, JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(0)), JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(1))), "if (true) {\n\ti = 0;\n}\nelse {\n\ti = 1;\n}\n"); } [Test] public void IfAndElseIfStatementsAreChained() { AssertCorrect(JsStatement.If(JsExpression.True, JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(0)), null), "if (true) {\n\ti = 0;\n}\n"); AssertCorrect(JsStatement.If(JsExpression.Identifier("a"), JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(0)), JsStatement.If(JsExpression.Identifier("b"), JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(1)), JsStatement.If(JsExpression.Identifier("c"), JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(2)), JsExpression.Assign(JsExpression.Identifier("i"), JsExpression.Number(3))))), @"if (a) { i = 0; } else if (b) { i = 1; } else if (c) { i = 2; } else { i = 3; } "); } [Test] public void BreakStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Break(), "break;\n"); AssertCorrect(JsStatement.Break("someLabel"), "break someLabel;\n"); } [Test] public void ContinueStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Continue(), "continue;\n"); AssertCorrect(JsStatement.Continue("someLabel"), "continue someLabel;\n"); } [Test] public void DoWhileStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.DoWhile(JsExpression.True, JsStatement.Block(JsStatement.Var("x", JsExpression.Number(0)))), "do {\n\tvar x = 0;\n} while (true);\n"); } [Test] public void WhileStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.While(JsExpression.True, JsStatement.Block(JsStatement.Var("x", JsExpression.Number(0)))), "while (true) {\n\tvar x = 0;\n}\n"); } [Test] public void ReturnStatementWithOrWithoutExpressionIsCorrectlyOutput() { AssertCorrect(JsStatement.Return(null), "return;\n"); AssertCorrect(JsStatement.Return(JsExpression.Identifier("x")), "return x;\n"); } [Test] public void TryCatchFinallyStatementWithCatchOrFinallyOrBothIsCorrectlyOutput() { AssertCorrect(JsStatement.Try(JsExpression.Identifier("x"), JsStatement.Catch("e", JsExpression.Identifier("y")), JsExpression.Identifier("z")), "try {\n\tx;\n}\ncatch (e) {\n\ty;\n}\nfinally {\n\tz;\n}\n"); AssertCorrect(JsStatement.Try(JsExpression.Identifier("x"), JsStatement.Catch("e", JsExpression.Identifier("y")), null), "try {\n\tx;\n}\ncatch (e) {\n\ty;\n}\n"); AssertCorrect(JsStatement.Try(JsExpression.Identifier("x"), null, JsExpression.Identifier("z")), "try {\n\tx;\n}\nfinally {\n\tz;\n}\n"); } [Test] public void ThrowStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Throw(JsExpression.Identifier("x")), "throw x;\n"); } [Test] public void SwitchStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Switch(JsExpression.Identifier("x"), JsStatement.SwitchSection(new[] { JsExpression.Number(0) }, JsExpression.Identifier("a")), JsStatement.SwitchSection(new[] { JsExpression.Number(1), JsExpression.Number(2) }, JsExpression.Identifier("b")), JsStatement.SwitchSection(new[] { null, JsExpression.Number(3) }, JsExpression.Identifier("c")) ), @"switch (x) { case 0: { a; } case 1: case 2: { b; } default: case 3: { c; } } "); } [Test] public void FunctionDefinitionStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Function("f", new[] { "a", "b", "c" }, JsExpression.Identifier("x")), "function f(a, b, c) {\n\tx;\n}\n"); } [Test] public void WithStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.With(JsExpression.Identifier("o"), JsStatement.EmptyBlock), "with (o) {\n}\n"); } [Test] public void LabelledStatementIsCorrectlyOutput() { AssertCorrect(JsStatement.Block(JsStatement.Label("lbl", JsExpression.Identifier("X"))), "{\n\tlbl:\n\tX;\n}\n"); } } }
/*=================================\ * PlotterControl\Form_serialmonitor.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:04:46 *=================================*/ using System; using System.Windows.Forms; using CWA.DTP; using System.Text; using System.Linq; using System.IO.Ports; using CWA.Connection; using System.Threading; using System.Collections.Generic; namespace CnC_WFA { public partial class Form_SerialMonitor : Form { public Form_SerialMonitor() { InitializeComponent(); } private void checkBox_size_CheckedChanged(object sender, System.EventArgs e) { textBox_size_b1.Enabled = checkBox_size.Checked; textBox_size_b2.Enabled = checkBox_size.Checked; } private void checkBox_hash_CheckedChanged(object sender, System.EventArgs e) { textBox_hash_b1.Enabled = checkBox_hash.Checked; textBox_hash_b2.Enabled = checkBox_hash.Checked; } private void Form_SerialMonitor_Load(object sender, System.EventArgs e) { foreach (var item in Enum.GetValues(typeof(CommandType))) { var name = Enum.GetName(typeof(CommandType), item); UInt32 itemI = (UInt32)item; comboBox_command.Items.Add(string.Format("{0} - 0x{1}", name, itemI.ToString("X").Trim())); } foreach (var item in Enum.GetValues(typeof(CWA.DTP.Plotter.CommandType))) { var name = Enum.GetName(typeof(CWA.DTP.Plotter.CommandType), item); UInt32 itemI = (UInt32)item; comboBox_command.Items.Add(string.Format("{0} - 0x{1}", name, itemI.ToString("X").Trim())); } comboBox_command.SelectedIndex = 1; comboBox_sender.Items.AddRange(Enum.GetNames(typeof(SenderType))); comboBox_sender.SelectedIndex = 0; comboBox_conv.Items.AddRange(new string[] { "UInt16 To Bytes", "Int16 To Bytes", "UInt32 To Bytes", "Int32 To Bytes", "UInt64 To Bytes", "Int64 To Bytes", "Float To Bytes", "Double To Bytes", "String To Bytes", }); comboBox_port.Items.Clear(); comboBox_port.Items.AddRange(SerialPort.GetPortNames()); comboBox_bd.Items.AddRange(BdRate.GetNamesStrings()); } private string Convert(string Input, int index) { byte[] bytes = new byte[0]; try { switch (index) { case (0): bytes = BitConverter.GetBytes(UInt16.Parse(Input)); break; case (1): bytes = BitConverter.GetBytes(Int16.Parse(Input)); break; case (2): bytes = BitConverter.GetBytes(UInt32.Parse(Input)); break; case (3): bytes = BitConverter.GetBytes(Int32.Parse(Input)); break; case (4): bytes = BitConverter.GetBytes(UInt64.Parse(Input)); break; case (5): bytes = BitConverter.GetBytes(UInt64.Parse(Input)); break; case (6): bytes = BitConverter.GetBytes(Single.Parse(Input)); break; case (7): bytes = BitConverter.GetBytes(Double.Parse(Input)); break; case (8): bytes = Encoding.Default.GetBytes(Input); break; default: break; } return string.Join(",", bytes); } catch(Exception e) { MessageBox.Show( string.Format( TB.L.Phrase["Form_PrintMaster.ErrorText"], e.GetType().FullName, e.StackTrace, e.Message), TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return ""; } } private void comboBox_command_SelectedIndexChanged(object sender, EventArgs e) { byte[] bytes = new byte[0]; try { bytes = BitConverter.GetBytes((UInt16)(CommandType)Enum.Parse(typeof(CommandType), comboBox_command.Text.Split('-')[0])); } catch(ArgumentException) { bytes = BitConverter.GetBytes((UInt16)(CWA.DTP.Plotter.CommandType)Enum.Parse(typeof(CWA.DTP.Plotter.CommandType), comboBox_command.Text.Split('-')[0])); } finally { textBox_command_b1.Text = bytes[0].ToString(); textBox_command_b2.Text = bytes[1].ToString(); } } private void comboBox_sender_SelectedIndexChanged(object sender, EventArgs e) { if(comboBox_sender.Text == SenderType.SevenByteName.ToString()) { textBox_sender_b1.Text = ((UInt16)SenderType.SevenByteName).ToString(); textBox_fill.Enabled = true; } else { textBox_sender_b1.Text = ((UInt16)SenderType.UnNamedByteMask).ToString(); textBox_fill.Enabled = false; } } private void button_fill_Click(object sender, EventArgs e) { if (textBox_fill.Text.Length != 7) { MessageBox.Show( TB.L.Phrase["Connection.Enter7CharString"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } textBox_sender_b2.Text = ((byte)textBox_fill.Text[0]).ToString(); textBox_sender_b3.Text = ((byte)textBox_fill.Text[1]).ToString(); textBox_sender_b4.Text = ((byte)textBox_fill.Text[2]).ToString(); textBox_sender_b5.Text = ((byte)textBox_fill.Text[3]).ToString(); textBox_sender_b6.Text = ((byte)textBox_fill.Text[4]).ToString(); textBox_sender_b7.Text = ((byte)textBox_fill.Text[5]).ToString(); textBox_sender_b8.Text = ((byte)textBox_fill.Text[6]).ToString(); } private void button1_Click(object sender, EventArgs e) { textBox_conv_output.Text = Convert(textBox_conv_input.Text, comboBox_conv.SelectedIndex); } private void TryToCoputeLenghAndHash(bool action = false) { UInt16 Command; byte[] Sender; byte[] DataBytes = new byte[0]; try { Command = BitConverter.ToUInt16(new byte[] { byte.Parse(textBox_command_b1.Text), byte.Parse(textBox_command_b2.Text) }, 0); } catch { label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Command"]; return; } try { Sender = new byte[8] { byte.Parse(textBox_sender_b1.Text), byte.Parse(textBox_sender_b2.Text), byte.Parse(textBox_sender_b3.Text), byte.Parse(textBox_sender_b4.Text), byte.Parse(textBox_sender_b5.Text), byte.Parse(textBox_sender_b6.Text), byte.Parse(textBox_sender_b7.Text), byte.Parse(textBox_sender_b8.Text), }; } catch { label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.SenderBytes"]; return; } if (textBox_data.Text != "") try { DataBytes = textBox_data.Text.Split(',').Select(p => byte.Parse(p)).ToArray(); } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Data"]; return; } UInt16 Length = (UInt16)(DataBytes.Length + 14 + 255); byte[] lengthBytes; try { lengthBytes = checkBox_size.Checked ? new byte[] { byte.Parse(textBox_size_b1.Text), byte.Parse(textBox_size_b2.Text) } : BitConverter.GetBytes(Length); } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Size"]; ; return; } if (!checkBox_size.Checked) { textBox_size_b1.Text = lengthBytes[0].ToString(); textBox_size_b2.Text = lengthBytes[1].ToString(); } byte[] crc; if (!checkBox_hash.Checked) { var crcH = new CrCHandler(); crc = crcH.ComputeChecksumBytes(DataBytes); textBox_hash_b1.Text = crc[0].ToString(); textBox_hash_b2.Text = crc[1].ToString(); } else { try { crc = new byte[] { byte.Parse(textBox_hash_b1.Text), byte.Parse(textBox_hash_b2.Text) }; } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Hash"]; return; } } if (action) { byte[] totalBytes = new byte[DataBytes.Length + 14]; Buffer.BlockCopy(lengthBytes, 0, totalBytes, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes(Command), 0, totalBytes, 2, 2); Buffer.BlockCopy(Sender, 0, totalBytes, 4, 8); Buffer.BlockCopy(DataBytes, 0, totalBytes, 12, DataBytes.Length); Buffer.BlockCopy(crc, 0, totalBytes, 12 + DataBytes.Length, 2); Requests.Add(new Packet() { Command = Command, Data = DataBytes, Sender = new Sender(Sender), TotalData = totalBytes, Size = (Int16)(Length - 255) }); listBox.Items.Add($"R{Requests.Count}. ${TB.L.Phrase["Connection.Error.Command"]}: ({textBox_command_b1.Text}, {textBox_command_b2.Text})"); try { Answers.Add(GetResult(totalBytes)); listBox.Items.Add($"A{Answers.Count}. ${TB.L.Phrase["Connection.Status"]}: {Answers.Last().Status}. ${TB.L.Phrase["Connection.AnswerTo"]}: {Answers.Last().Command}"); } catch (Exception e) { label_err.Text = TB.L.Phrase["Connection.Error.SendingError"]; MessageBox.Show( string.Format( TB.L.Phrase["Form_PrintMaster.ErrorText"], e.GetType().FullName, e.StackTrace, e.Message), TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } label_err.Text = "Sended"; return; } label_err.Text = "Ok"; } private List<PacketAnswer> Answers = new List<PacketAnswer>(); private List<Packet> Requests = new List<Packet>(); private void textBox_command_b1_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_command_b2_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b1_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b2_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b3_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b4_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b5_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b6_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b7_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_sender_b8_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void textBox_data_TextChanged(object sender, EventArgs e) => TryToCoputeLenghAndHash(); private void button_exit_Click(object sender, EventArgs e) { Close(); } private void comboBox_port_SelectedIndexChanged(object sender, EventArgs e) { comboBox_port.Items.Clear(); comboBox_port.Items.AddRange(SerialPort.GetPortNames()); } private SerialPort port; private PacketListener Listener; protected PacketAnswer GetResult(byte[] bytes) { return Listener.SendAndListenPacket(new Packet() { TotalData = bytes }, true); } private void button_conn_Click(object sender, EventArgs e) { if(button_conn.Text != TB.L.Phrase["Connection.Disconnect"]) try { port = new SerialPort(comboBox_port.Text, int.Parse(comboBox_bd.Text.Remove(0, 2))); port.Open(); Listener = new PacketListener(new SerialPacketReader(port, 3000), new SerialPacketWriter(port)); button_conn.Text = TB.L.Phrase["Connection.Disconnect"]; button_send.Enabled = true; comboBox_bd.Enabled = false; comboBox_port.Enabled = false; } catch (Exception ex) { MessageBox.Show( string.Format( TB.L.Phrase["Form_PrintMaster.ErrorText"], ex.GetType().FullName, ex.StackTrace, ex.Message), TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { port.Close(); button_send.Enabled = false; button_conn.Text = TB.L.Phrase["Connection.Connect"]; comboBox_bd.Enabled = true; comboBox_port.Enabled = true; } } private void button_send_Click(object sender, EventArgs e) { TryToCoputeLenghAndHash(true); } private void listBox_MouseDoubleClick(object sender, MouseEventArgs e) { int index = listBox.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) { string name = (string)listBox.Items[index]; var prefix = name.Split('.')[0]; int listIndex = int.Parse(prefix.Remove(0, 1)); if (prefix[0] == 'A') ShowInfoAboutAnswer(listIndex); else ShowInfoAboutRequest(listIndex); } } private void ShowInfoAboutAnswer(int index) { var ob = Answers[index-1]; string s = $"${TB.L.Phrase["Connection.Sender"]}: {ob.Sender.ToString()}\n${TB.L.Phrase["Connection.AnswStatus"]}: {ob.Status}\n${TB.L.Phrase["Connection.AnswCommand"]}: {ob.Command}\n\n${TB.L.Phrase["Connection.AnswerDataType"]}: {ob.DataType}\n"; if (ob.DataType == AnswerDataType.CODE) s += $" ${TB.L.Phrase["Connection.AnswerCode"]}: {ob.Code}"; else if(ob.DataType == AnswerDataType.DATA) { s += $" ${TB.L.Phrase["Connection.AnswerData"]}: {string.Join(",", ob.Data)}\n"; s += $" ${TB.L.Phrase["Connection.Or"]}: {string.Join("", ob.Data.Select(p=>(char)p))}"; } MessageBox.Show(s, TB.L.Phrase["Connectio.AnswerData"], MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ShowInfoAboutRequest(int index) { var ob = Requests[index - 1]; MessageBox.Show($"${TB.L.Phrase["Connection.PacketSender"]}: {ob.Sender.ToString()}\n${TB.L.Phrase["Connection.PacketCommand"]}: {ob.Command}\n${TB.L.Phrase["Connection.PacketData"]}: {string.Join(",", ob.Data)}", TB.L.Phrase["Connection.PacketInfo"], MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class MulInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "Mul"; private MulInstruction() { } private sealed class MulInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left * (int)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((long)left * (long)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((uint)left * (uint)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulSingle : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)((float)left * (float)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulDouble : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)((double)left * (double)right); } frame.StackIndex = index - 1; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new MulInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new MulInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new MulInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); case TypeCode.Single: return s_Single ?? (s_Single = new MulSingle()); case TypeCode.Double: return s_Double ?? (s_Double = new MulDouble()); default: throw ContractUtils.Unreachable; } } } internal abstract class MulOvfInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "MulOvf"; private MulOvfInstruction() { } private sealed class MulOvfInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left * (int)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((long)left * (long)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((uint)left * (uint)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new MulOvfInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new MulOvfInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new MulOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); default: return MulInstruction.Create(type); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexMatchTests : RemoteExecutorTestBase { public static IEnumerable<object[]> Match_Basic_TestData() { // Testing octal sequence matches: "\\060(\\061)?\\061" // Octal \061 is ASCII 49 ('1') yield return new object[] { @"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011" }; // Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)" // Hex \x31 is ASCII 49 ('1') yield return new object[] { @"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012" }; // Testing control character escapes???: "2", "(\u0032)" yield return new object[] { "(\u0034)", "4", RegexOptions.None, 0, 1, true, "4", }; // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" }; // Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)" yield return new object[] { @"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" }; // \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)" yield return new object[] { @"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars" }; // \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)" yield return new object[] { @"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30" }; // Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+" yield return new object[] { @"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty }; // Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def" yield return new object[] { @"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef" }; // Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def" yield return new object[] { @"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef" }; // Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3" // The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched // for it to be a success. For a correct match, remove the last character, '3' from the pattern yield return new object[] { "[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.None, 0, 17, true, "aaaasdfajsdlfjzzz" }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty }; // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return new object[] { @"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3" }; // Using beginning/end of string chars ^: Actual - "^b" yield return new object[] { "^b", "ab", RegexOptions.None, 0, 2, false, string.Empty }; // Actual - "(?<char>\\w)\\<char>" yield return new object[] { @"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa" }; // Actual - "(?<43>\\w)\\43" yield return new object[] { @"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa" }; // Actual - "abc(?(1)111|222)" yield return new object[] { "(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty }; // "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x" yield return new object[] { " ((.)+) ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc" }; // "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x" yield return new object[] { "\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc " }; // Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb" if ("i".ToUpper() == "I") { yield return new object[] { "aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb" }; } // Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i" yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb" }; // Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i" yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty }; // Actual - "aaa(?#ignore this completely)bbb" yield return new object[] { "aaa(?#ignore this completely)bbb", "aaabbb", RegexOptions.None, 0, 6, true, "aaabbb" }; // Trying empty string: Actual "[a-z0-9]+", "" yield return new object[] { "[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty }; // Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})" yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111" }; yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty }; // Not naming pattern slots at all: "^(cat|chat)" yield return new object[] { "^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat" }; yield return new object[] { "abc", "abc", RegexOptions.None, 0, 3, true, "abc" }; yield return new object[] { "abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { "abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc" }; // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" }; // RightToLeft yield return new object[] { @"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12" }; yield return new object[] { @"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty }; yield return new object[] { "aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty }; // IgnoreCase yield return new object[] { "AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa" }; yield return new object[] { @"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" }; yield return new object[] { @"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty }; // "\D+" yield return new object[] { @"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty }; // Groups yield return new object[] { "(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" }; // "^b" yield return new object[] { "^b", "abc", RegexOptions.None, 0, 3, false, string.Empty }; // RightToLeft yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890" }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890" }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4" }; // Trim leading and trailing whitespace yield return new object[] { @"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World " }; // < in group yield return new object[] { @"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty }; // Atomic Zero-Width Assertions \A \Z \z \G \b \B yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty }; yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty }; yield return new object[] { @"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty }; yield return new object[] { @"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty }; yield return new object[] { @"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty }; yield return new object[] { @"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty }; yield return new object[] { @"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty }; yield return new object[] { @"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty }; // Lazy operator Backtracking yield return new object[] { @"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty }; // Grouping Constructs Invalid Regular Expressions yield return new object[] { "(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty }; yield return new object[] { "(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty }; // Alternation construct yield return new object[] { "(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty }; yield return new object[] { "(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2" }; yield return new object[] { "(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2" }; yield return new object[] { "(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty }; yield return new object[] { "(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { "(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty }; yield return new object[] { "(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty }; // No Negation yield return new object[] { "[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { "[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { "[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { "[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { "[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { @"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { @"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // MixedNegation yield return new object[] { @"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // No Negation yield return new object[] { @"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // All Negation yield return new object[] { @"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // MixedNegation yield return new object[] { @"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; yield return new object[] { @"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty }; // Character Class Substraction yield return new object[] { @"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty }; yield return new object[] { @"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty }; } [Theory] [MemberData(nameof(Match_Basic_TestData))] public void Match(string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length); if (options == RegexOptions.None) { if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string) VerifyMatch(new Regex(pattern).Match(input), expectedSuccess, expectedValue); VerifyMatch(Regex.Match(input, pattern), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input)); Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern).Match(input, beginning), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input, beginning)); } // Use Match(string, int, int) VerifyMatch(new Regex(pattern).Match(input, beginning, length), expectedSuccess, expectedValue); } if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(new Regex(pattern, options).Match(input), expectedSuccess, expectedValue); VerifyMatch(Regex.Match(input, pattern, options), expectedSuccess, expectedValue); Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern, options)); } if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning), expectedSuccess, expectedValue); } // Use Match(string, int, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), expectedSuccess, expectedValue); } public static void VerifyMatch(Match match, bool expectedSuccess, string expectedValue) { Assert.Equal(expectedSuccess, match.Success); Assert.Equal(expectedValue, match.Value); // Groups can never be empty Assert.True(match.Groups.Count >= 1); Assert.Equal(expectedSuccess, match.Groups[0].Success); Assert.Equal(expectedValue, match.Groups[0].Value); } [Fact] public void Match_Timeout() { Regex regex = new Regex(@"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1)); Match match = regex.Match("abc"); Assert.True(match.Success); Assert.Equal("a", match.Value); } public static IEnumerable<object[]> Match_Advanced_TestData() { // \B special character escape: ".*\\B(SUCCESS)\\B.*" yield return new object[] { @".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22, new CaptureData[] { new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22), new CaptureData("SUCCESS", 7, 7) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Using greedy quantifiers: Actual - "(a+)(b*)(c?)" yield return new object[] { "(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbc", 0, 7), new CaptureData("aaa", 0, 3), new CaptureData("bbb", 3, 3), new CaptureData("c", 6, 1) } }; // Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)" // Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier yield return new object[] { "(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("d", 0, 1), new CaptureData("d", 0, 1), new CaptureData(string.Empty, 1, 0), new CaptureData(string.Empty, 1, 0) } }; // Noncapturing group : Actual - "(a+)(?:b*)(ccc)" yield return new object[] { "(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbccc", 0, 9), new CaptureData("aaa", 0, 3), new CaptureData("ccc", 6, 3), } }; // Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" yield return new object[] { @"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("abcXXXdef", 0, 9) } }; // Backreferences : Actual - "(\\w)\\1" yield return new object[] { @"(\w)\1", "aa", RegexOptions.None, 0, 2, new CaptureData[] { new CaptureData("aa", 0, 2), new CaptureData("a", 0, 1), } }; // Alternation constructs: Actual - "(111|aaa)" yield return new object[] { "(111|aaa)", "aaa", RegexOptions.None, 0, 3, new CaptureData[] { new CaptureData("aaa", 0, 3), new CaptureData("aaa", 0, 3) } }; // Actual - "(?<1>\\d+)abc(?(1)222|111)" yield return new object[] { @"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("111abc222", 0, 9), new CaptureData("111", 0, 3) } }; // Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" yield return new object[] { @"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11, new CaptureData[] { new CaptureData("200 dollars", 0, 11), new CaptureData("dollars", 4, 7) } }; // Single line mode "s". Includes new line character: Actual - "([^/]+)","s" yield return new object[] { "(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7, new CaptureData[] { new CaptureData("abc\nsfc", 0, 7), new CaptureData("abc\nsfc", 0, 7), } }; // "([0-9]+(\\.[0-9]+){3})" yield return new object[] { @"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12, new CaptureData[] { new CaptureData("209.25.0.111", 0, 12), new CaptureData("209.25.0.111", 0, 12), new CaptureData(".111", 8, 4, new CaptureData[] { new CaptureData(".25", 3, 3), new CaptureData(".0", 6, 2), new CaptureData(".111", 8, 4), }), } }; // Groups and captures yield return new object[] { @"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; yield return new object[] { @"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Actual - ".*\\b(\\w+)\\b" yield return new object[] { @".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24, new CaptureData[] { new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24), new CaptureData("SUCCESS", 17, 7) } }; // Mutliline yield return new object[] { "(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Mutliline yield return new object[] { "(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Mutliline yield return new object[] { "(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Mutliline yield return new object[] { "(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Mutliline yield return new object[] { "(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // RightToLeft yield return new object[] { "aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; } [Theory] [MemberData(nameof(Match_Advanced_TestData))] public void Match(string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length); if (options == RegexOptions.None) { if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string) VerifyMatch(new Regex(pattern).Match(input), true, expected); VerifyMatch(Regex.Match(input, pattern), true, expected); Assert.True(new Regex(pattern).IsMatch(input)); Assert.True(Regex.IsMatch(input, pattern)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern).Match(input, beginning), true, expected); Assert.True(new Regex(pattern).IsMatch(input, beginning)); } else { // Use Match(string, int, int) VerifyMatch(new Regex(pattern).Match(input, beginning, length), true, expected); } } if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(new Regex(pattern, options).Match(input), true, expected); VerifyMatch(Regex.Match(input, pattern, options), true, expected); Assert.True(Regex.IsMatch(input, pattern, options)); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning), true, expected); } if ((options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int, int) VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), true, expected); } } public static void VerifyMatch(Match match, bool expectedSuccess, CaptureData[] expected) { Assert.Equal(expectedSuccess, match.Success); Assert.Equal(expected[0].Value, match.Value); Assert.Equal(expected[0].Index, match.Index); Assert.Equal(expected[0].Length, match.Length); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected[0].Value, match.Captures[0].Value); Assert.Equal(expected[0].Index, match.Captures[0].Index); Assert.Equal(expected[0].Length, match.Captures[0].Length); Assert.Equal(expected.Length, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.Equal(expectedSuccess, match.Groups[i].Success); Assert.Equal(expected[i].Value, match.Groups[i].Value); Assert.Equal(expected[i].Index, match.Groups[i].Index); Assert.Equal(expected[i].Length, match.Groups[i].Length); Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { Assert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j].Value); Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); } } } [Theory] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")] [InlineData("abc", "abc", "abc", "abc")] public void Result(string pattern, string input, string replacement, string expected) { Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement)); } [Fact] public void Result_Invalid() { Match match = Regex.Match("foo", "foo"); AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null)); Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any")); } [Fact] public void Match_SpecialUnicodeCharacters() { RemoteInvoke(() => { CultureInfo.CurrentCulture = new CultureInfo("en-US"); Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); return SuccessExitCode; }).Dispose(); } [Fact] public void Match_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6, 0)); // Length is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, 6)); } [Theory] [InlineData(")")] [InlineData("())")] [InlineData("[a-z-[aeiuo]")] [InlineData("[a-z-[aeiuo")] [InlineData("[a-z-[b]")] [InlineData("[a-z-[b")] [InlineData("[b-a]")] [InlineData(@"[a-c]{2,1}")] [InlineData(@"\d{2147483648}")] [InlineData("[a-z-[b][")] [InlineData(@"\")] [InlineData("(?()|||||)")] public void Match_InvalidPattern(string pattern) { AssertExtensions.Throws<ArgumentException>(null, () => Regex.Match("input", pattern)); } [Fact] public void IsMatch_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", 6)); } } }
/*=============================================================================================== Real-time stitching example Copyright (c), Firelight Technologies Pty, Ltd 2004-2011. This example shows how you can create your own multi-subsound stream, then in realtime replace each the subsound as it plays them. Using a looping sentence, it will seamlessly stich between 2 subsounds in this example, and each time it switches to a new sound, it will replace the old one with another sound in our list. These sounds can go on forever as long as they are the same bitdepth (when decoded) and number of channels (ie mono / stereo). The reason for this is the hardware channel cannot change formats mid sentence, and using different hardware channels would mean it wouldn't be gapless. ===============================================================================================*/ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; namespace realtimestitching { public class Form1 : System.Windows.Forms.Form { private const int NUMSOUNDS = 32; private FMOD.System system = null; private FMOD.Sound sound = null; private FMOD.Sound[] subsound = new FMOD.Sound[2]; private FMOD.Channel channel = null; private int subsoundid = 0, sentenceid = 0; private string[] soundname = { "../../../../../examples/media/e.ogg", /* Ma- */ "../../../../../examples/media/d.ogg", /* ry */ "../../../../../examples/media/c.ogg", /* had */ "../../../../../examples/media/d.ogg", /* a */ "../../../../../examples/media/e.ogg", /* lit- */ "../../../../../examples/media/e.ogg", /* tle */ "../../../../../examples/media/e.ogg", /* lamb, */ "../../../../../examples/media/e.ogg", /* ..... */ "../../../../../examples/media/d.ogg", /* lit- */ "../../../../../examples/media/d.ogg", /* tle */ "../../../../../examples/media/d.ogg", /* lamb, */ "../../../../../examples/media/d.ogg", /* ..... */ "../../../../../examples/media/e.ogg", /* lit- */ "../../../../../examples/media/e.ogg", /* tle */ "../../../../../examples/media/e.ogg", /* lamb, */ "../../../../../examples/media/e.ogg", /* ..... */ "../../../../../examples/media/e.ogg", /* Ma- */ "../../../../../examples/media/d.ogg", /* ry */ "../../../../../examples/media/c.ogg", /* had */ "../../../../../examples/media/d.ogg", /* a */ "../../../../../examples/media/e.ogg", /* lit- */ "../../../../../examples/media/e.ogg", /* tle */ "../../../../../examples/media/e.ogg", /* lamb, */ "../../../../../examples/media/e.ogg", /* its */ "../../../../../examples/media/d.ogg", /* fleece */ "../../../../../examples/media/d.ogg", /* was */ "../../../../../examples/media/e.ogg", /* white */ "../../../../../examples/media/d.ogg", /* as */ "../../../../../examples/media/c.ogg", /* snow. */ "../../../../../examples/media/c.ogg", /* ..... */ "../../../../../examples/media/c.ogg", /* ..... */ "../../../../../examples/media/c.ogg" /* ..... */ }; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.Button pauseButton; private System.Windows.Forms.Button exit_button; private System.Windows.Forms.Label label; private System.Windows.Forms.Timer timer; private System.ComponentModel.IContainer components; public Form1() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { FMOD.RESULT result; /* Shut down */ if (sound != null) { result = sound.release(); ERRCHECK(result); } if (system != null) { result = system.close(); ERRCHECK(result); result = system.release(); ERRCHECK(result); } if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.statusBar = new System.Windows.Forms.StatusBar(); this.pauseButton = new System.Windows.Forms.Button(); this.exit_button = new System.Windows.Forms.Button(); this.label = new System.Windows.Forms.Label(); this.timer = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 91); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(292, 24); this.statusBar.TabIndex = 17; // // pauseButton // this.pauseButton.Location = new System.Drawing.Point(8, 48); this.pauseButton.Name = "pauseButton"; this.pauseButton.Size = new System.Drawing.Size(160, 32); this.pauseButton.TabIndex = 21; this.pauseButton.Text = "Pause/Resume"; this.pauseButton.Click += new System.EventHandler(this.pauseButton_Click); // // exit_button // this.exit_button.Location = new System.Drawing.Point(176, 48); this.exit_button.Name = "exit_button"; this.exit_button.Size = new System.Drawing.Size(104, 32); this.exit_button.TabIndex = 22; this.exit_button.Text = "Exit"; this.exit_button.Click += new System.EventHandler(this.exit_button_Click); // // label // this.label.Location = new System.Drawing.Point(14, 8); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(264, 32); this.label.TabIndex = 23; this.label.Text = "Copyright (c) Firelight Technologies 2004/2010"; this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // timer // this.timer.Enabled = true; this.timer.Interval = 10; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 115); this.Controls.Add(this.label); this.Controls.Add(this.exit_button); this.Controls.Add(this.pauseButton); this.Controls.Add(this.statusBar); this.Name = "Form1"; this.Text = "Real-time Stitching Example"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO(); FMOD.RESULT result; uint version = 0; /* Create a System object and initialize. */ result = FMOD.Factory.System_Create(ref system); ERRCHECK(result); result = system.getVersion(ref version); ERRCHECK(result); if (version < FMOD.VERSION.number) { MessageBox.Show("Error! You are using an old version of FMOD " + version.ToString("X") + ". This program requires " + FMOD.VERSION.number.ToString("X") + "."); Application.Exit(); } result = system.init(1, FMOD.INITFLAGS.NORMAL, (IntPtr)null); ERRCHECK(result); /* Set up the FMOD_CREATESOUNDEXINFO structure for the user stream with room for 2 subsounds. (our subsound double buffer) */ exinfo.cbsize = Marshal.SizeOf(exinfo); exinfo.defaultfrequency = 44100; exinfo.numsubsounds = 2; exinfo.numchannels = 1; exinfo.format = FMOD.SOUND_FORMAT.PCM16; /* Create the 'parent' stream that contains the substreams. Set it to loop so that it loops between subsound 0 and 1. */ result = system.createStream("", FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER, ref exinfo, ref sound); ERRCHECK(result); /* Add 2 of our streams as children of the parent. They should be the same format (ie mono/stereo and bitdepth) as the parent sound. When subsound 0 has finished and it is playing subsound 1, we will swap subsound 0 with a new sound, and the same for when subsound 1 has finished, causing a continual double buffered flip, which means continuous sound. */ result = system.createStream(soundname[0], FMOD.MODE.DEFAULT, ref subsound[0]); ERRCHECK(result); result = system.createStream(soundname[1], FMOD.MODE.DEFAULT, ref subsound[1]); ERRCHECK(result); result = sound.setSubSound(0, subsound[0]); ERRCHECK(result); result = sound.setSubSound(1, subsound[1]); ERRCHECK(result); /* Set up the gapless sentence to contain these first 2 streams. */ { int[] soundlist = { 0, 1 }; result = sound.setSubSoundSentence(soundlist, 2); ERRCHECK(result); } subsoundid = 0; sentenceid = 2; /* The next sound to be appeneded to the stream. */ /* Play the sound. */ result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel); ERRCHECK(result); } private void pauseButton_Click(object sender, System.EventArgs e) { FMOD.RESULT result; bool paused = false; if (channel != null) { result = channel.getPaused(ref paused); ERRCHECK(result); result = channel.setPaused(!paused); ERRCHECK(result); } } private void exit_button_Click(object sender, System.EventArgs e) { Application.Exit(); } private void timer_Tick(object sender, System.EventArgs e) { FMOD.RESULT result; /* Replace the subsound that just finished with a new subsound, to create endless seamless stitching! Note that this polls the currently playing subsound using the FMOD_TIMEUNIT_BUFFERED flag. Remember streams are decoded / buffered ahead in advance! Don't use the 'audible time' which is FMOD_TIMEUNIT_SENTENCE_SUBSOUND by itself. When streaming, sound is processed ahead of time, and things like stream buffer / sentence manipulation (as done below) is required to be in 'buffered time', or else there will be synchronization problems and you might end up releasing a sub-sound that is still playing! */ if (channel != null) { uint currentsubsoundid = 0; result = channel.getPosition(ref currentsubsoundid, FMOD.TIMEUNIT.SENTENCE_SUBSOUND | FMOD.TIMEUNIT.BUFFERED); ERRCHECK(result); if (currentsubsoundid != subsoundid) { /* Release the sound that isn't playing any more. */ result = subsound[subsoundid].release(); ERRCHECK(result); /* Replace it with a new sound in our list. */ result = system.createStream(soundname[sentenceid], FMOD.MODE.DEFAULT, ref subsound[subsoundid]); ERRCHECK(result); result = sound.setSubSound(subsoundid, subsound[subsoundid]); ERRCHECK(result); statusBar.Text = "Replacing subsound " + subsoundid+ " / 2 with sound " + sentenceid + " / " + NUMSOUNDS; sentenceid++; if (sentenceid >= NUMSOUNDS) { sentenceid = 0; } subsoundid = (int)currentsubsoundid; } } if (system != null) { result = system.update(); ERRCHECK(result); } } private void ERRCHECK(FMOD.RESULT result) { if (result != FMOD.RESULT.OK) { timer.Stop(); MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result)); Environment.Exit(-1); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Highway.Data.OData { internal static class MethodProvider { private static readonly MethodInfo InnerContainsMethod; private static readonly MethodInfo InnerIndexOfMethod; private static readonly MethodInfo EndsWithMethod1; private static readonly MethodInfo InnerStartsWithMethod; private static readonly PropertyInfo InnerLengthProperty; private static readonly MethodInfo InnerSubstringMethod; private static readonly MethodInfo InnerToLowerMethod; private static readonly MethodInfo InnerToUpperMethod; private static readonly MethodInfo InnerTrimMethod; private static readonly PropertyInfo InnerDayProperty; private static readonly PropertyInfo InnerHourProperty; private static readonly PropertyInfo InnerMinuteProperty; private static readonly PropertyInfo InnerSecondProperty; private static readonly PropertyInfo InnerMonthProperty; private static readonly PropertyInfo InnerYearProperty; private static readonly MethodInfo InnerDoubleRoundMethod; private static readonly MethodInfo InnerDecimalRoundMethod; private static readonly MethodInfo InnerDoubleFloorMethod; private static readonly MethodInfo InnerDecimalFloorMethod; private static readonly MethodInfo InnerDoubleCeilingMethod; private static readonly MethodInfo InnerDecimalCeilingMethod; static MethodProvider() { var stringType = typeof (string); var datetimeType = typeof (DateTime); var mathType = typeof (Math); InnerContainsMethod = stringType.GetMethod("Contains", new[] {stringType}); InnerIndexOfMethod = stringType.GetMethod("IndexOf", new[] {stringType}); EndsWithMethod1 = stringType.GetMethod("EndsWith", new[] {stringType}); InnerStartsWithMethod = stringType.GetMethod("StartsWith", new[] {stringType}); InnerLengthProperty = stringType.GetProperty("Length", Type.EmptyTypes); InnerSubstringMethod = stringType.GetMethod("Substring", new[] {typeof (int)}); InnerToLowerMethod = stringType.GetMethod("ToLower", Type.EmptyTypes); InnerToUpperMethod = stringType.GetMethod("ToUpper", Type.EmptyTypes); InnerTrimMethod = stringType.GetMethod("Trim", Type.EmptyTypes); InnerDayProperty = datetimeType.GetProperty("Day", Type.EmptyTypes); InnerHourProperty = datetimeType.GetProperty("Hour", Type.EmptyTypes); InnerMinuteProperty = datetimeType.GetProperty("Minute", Type.EmptyTypes); InnerSecondProperty = datetimeType.GetProperty("Second", Type.EmptyTypes); InnerMonthProperty = datetimeType.GetProperty("Month", Type.EmptyTypes); InnerYearProperty = datetimeType.GetProperty("Year", Type.EmptyTypes); InnerDoubleRoundMethod = mathType.GetMethod("Round", new[] {typeof (double)}); InnerDecimalRoundMethod = mathType.GetMethod("Round", new[] {typeof (decimal)}); InnerDoubleFloorMethod = mathType.GetMethod("Floor", new[] {typeof (double)}); InnerDecimalFloorMethod = mathType.GetMethod("Floor", new[] {typeof (decimal)}); InnerDoubleCeilingMethod = mathType.GetMethod("Ceiling", new[] {typeof (double)}); InnerDecimalCeilingMethod = mathType.GetMethod("Ceiling", new[] {typeof (decimal)}); } public static MethodInfo IndexOfMethod { get { return InnerIndexOfMethod; } } public static MethodInfo ContainsMethod { get { return InnerContainsMethod; } } public static MethodInfo EndsWithMethod { get { return EndsWithMethod1; } } public static MethodInfo StartsWithMethod { get { return InnerStartsWithMethod; } } public static PropertyInfo LengthProperty { get { return InnerLengthProperty; } } public static MethodInfo SubstringMethod { get { return InnerSubstringMethod; } } public static MethodInfo ToLowerMethod { get { return InnerToLowerMethod; } } public static MethodInfo ToUpperMethod { get { return InnerToUpperMethod; } } public static MethodInfo TrimMethod { get { return InnerTrimMethod; } } public static PropertyInfo DayProperty { get { return InnerDayProperty; } } public static PropertyInfo HourProperty { get { return InnerHourProperty; } } public static PropertyInfo MinuteProperty { get { return InnerMinuteProperty; } } public static PropertyInfo SecondProperty { get { return InnerSecondProperty; } } public static PropertyInfo MonthProperty { get { return InnerMonthProperty; } } public static PropertyInfo YearProperty { get { return InnerYearProperty; } } public static MethodInfo DoubleRoundMethod { get { return InnerDoubleRoundMethod; } } public static MethodInfo DecimalRoundMethod { get { return InnerDecimalRoundMethod; } } public static MethodInfo DoubleFloorMethod { get { return InnerDoubleFloorMethod; } } public static MethodInfo DecimalFloorMethod { get { return InnerDecimalFloorMethod; } } public static MethodInfo DoubleCeilingMethod { get { return InnerDoubleCeilingMethod; } } public static MethodInfo DecimalCeilingMethod { get { return InnerDecimalCeilingMethod; } } public static MethodInfo GetAnyAllMethod(string name, Type collectionType) { var implementationType = GetIEnumerableImpl(collectionType); var elemType = implementationType.GetGenericArguments()[0]; var predType = typeof (Func<,>).MakeGenericType(elemType, typeof (bool)); return (MethodInfo) GetGenericMethod(typeof (Enumerable), name, new[] {elemType}, new[] {implementationType, predType}, BindingFlags.Static); } public static Type GetIEnumerableImpl(Type type) { // Get IEnumerable implementation. Either type is IEnumerable<T> for some T, // or it implements IEnumerable<T> for some T. We need to find the interface. if (IsIEnumerable(type)) { return type; } var interfaces = type.FindInterfaces((m, o) => IsIEnumerable(m), null); return interfaces.First(); } private static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs, Type[] argTypes, BindingFlags flags) { var typeArity = typeArgs.Length; var methods = type.GetMethods() .Where(m => m.Name == name) .Where(m => m.GetGenericArguments().Length == typeArity) .Select(m => m.MakeGenericMethod(typeArgs)); return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null); } private static bool IsIEnumerable(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.IO; using System.Reflection; using System.Net; using System.Text; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nwc.XmlRpc; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Login { public class LLLoginHandlers { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ILoginService m_LocalService; private bool m_Proxy; public LLLoginHandlers(ILoginService service, bool hasProxy) { m_LocalService = service; m_Proxy = hasProxy; } public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; if (m_Proxy && request.Params[3] != null) { IPEndPoint ep = Util.GetClientIPFromXFF((string)request.Params[3]); if (ep != null) // Bang! remoteClient = ep; } if (requestData != null) { // Debug code to show exactly what login parameters the viewer is sending us. // TODO: Extract into a method that can be generally applied if one doesn't already exist. // foreach (string key in requestData.Keys) // { // object value = requestData[key]; // Console.WriteLine("{0}:{1}", key, value); // if (value is ArrayList) // { // ICollection col = value as ICollection; // foreach (object item in col) // Console.WriteLine(" {0}", item); // } // } if (requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null && ( (requestData.ContainsKey("passwd") && requestData["passwd"] != null) || (!requestData.ContainsKey("passwd") && requestData.ContainsKey("web_login_key") && requestData["web_login_key"] != null && requestData["web_login_key"].ToString() != UUID.Zero.ToString()) )) { string first = requestData["first"].ToString(); string last = requestData["last"].ToString(); string passwd = null; if (requestData.ContainsKey("passwd")) { passwd = requestData["passwd"].ToString(); } else if (requestData.ContainsKey("web_login_key")) { passwd = "$1$" + requestData["web_login_key"].ToString(); m_log.InfoFormat("[LOGIN]: XMLRPC Login Req key {0}", passwd); } string startLocation = string.Empty; UUID scopeID = UUID.Zero; if (requestData["scope_id"] != null) scopeID = new UUID(requestData["scope_id"].ToString()); if (requestData.ContainsKey("start")) startLocation = requestData["start"].ToString(); string clientVersion = "Unknown"; if (requestData.Contains("version") && requestData["version"] != null) clientVersion = requestData["version"].ToString(); // We should do something interesting with the client version... string channel = "Unknown"; if (requestData.Contains("channel") && requestData["channel"] != null) channel = requestData["channel"].ToString(); string mac = "Unknown"; if (requestData.Contains("mac") && requestData["mac"] != null) mac = requestData["mac"].ToString(); string id0 = "Unknown"; if (requestData.Contains("id0") && requestData["id0"] != null) id0 = requestData["id0"].ToString(); //m_log.InfoFormat("[LOGIN]: XMLRPC Login Requested for {0} {1}, starting in {2}, using {3}", first, last, startLocation, clientVersion); LoginResponse reply = null; reply = m_LocalService.Login(first, last, passwd, startLocation, scopeID, clientVersion, channel, mac, id0, remoteClient); XmlRpcResponse response = new XmlRpcResponse(); response.Value = reply.ToHashtable(); return response; } } return FailedXMLRPCResponse(); } public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; if (requestData != null) { if (requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null && requestData.ContainsKey("level") && requestData["level"] != null && requestData.ContainsKey("passwd") && requestData["passwd"] != null) { string first = requestData["first"].ToString(); string last = requestData["last"].ToString(); string passwd = requestData["passwd"].ToString(); int level = Int32.Parse(requestData["level"].ToString()); m_log.InfoFormat("[LOGIN]: XMLRPC Set Level to {2} Requested by {0} {1}", first, last, level); Hashtable reply = m_LocalService.SetLevel(first, last, passwd, level, remoteClient); XmlRpcResponse response = new XmlRpcResponse(); response.Value = reply; return response; } } XmlRpcResponse failResponse = new XmlRpcResponse(); Hashtable failHash = new Hashtable(); failHash["success"] = "false"; failResponse.Value = failHash; return failResponse; } public OSD HandleLLSDLogin(OSD request, IPEndPoint remoteClient) { if (request.Type == OSDType.Map) { OSDMap map = (OSDMap)request; if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) { string startLocation = string.Empty; if (map.ContainsKey("start")) startLocation = map["start"].AsString(); UUID scopeID = UUID.Zero; if (map.ContainsKey("scope_id")) scopeID = new UUID(map["scope_id"].AsString()); m_log.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation); LoginResponse reply = null; reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, scopeID, map["version"].AsString(), map["channel"].AsString(), map["mac"].AsString(), map["id0"].AsString(), remoteClient); return reply.ToOSDMap(); } } return FailedOSDResponse(); } private XmlRpcResponse FailedXMLRPCResponse() { Hashtable hash = new Hashtable(); hash["reason"] = "key"; hash["message"] = "Incomplete login credentials. Check your username and password."; hash["login"] = "false"; XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } private OSD FailedOSDResponse() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("key"); map["message"] = OSD.FromString("Invalid login credentials. Check your username and passwd."); map["login"] = OSD.FromString("false"); return map; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using hw.DebugFormatter; using JetBrains.Annotations; // ReSharper disable CheckNamespace namespace hw.Helper; [PublicAPI] public static class LinqExtension { public enum SeparatorTreatmentForSplit { Drop, BeginOfSubList, EndOfSubList } public static bool AddDistinct<T>(this IList<T> a, IEnumerable<T> b, Func<T, T, bool> isEqual) => InternalAddDistinct(a, b, isEqual); public static bool AddDistinct<T>(this IList<T> a, IEnumerable<T> b, Func<T, T, T> combine) where T : class => InternalAddDistinct(a, b, combine); public static IEnumerable<IEnumerable<T>> Separate<T>(this IEnumerable<T> target, Func<T, bool> isHead) { var subResult = new List<T>(); foreach(var xx in target) { if(isHead(xx)) if(subResult.Count > 0) { yield return subResult.ToArray(); subResult = new(); } subResult.Add(xx); } if(subResult.Count > 0) yield return subResult.ToArray(); } [CanBeNull] public static T Aggregate<T>(this IEnumerable<T> target, Func<T> getDefault = null) where T : class, IAggregateable<T> { var xx = target.ToArray(); if(!xx.Any()) return getDefault?.Invoke(); var result = xx[0]; for(var i = 1; i < xx.Length; i++) result = result.Aggregate(xx[i]); return result; } public static string Dump<T>(this IEnumerable<T> target) => Tracer.Dump(target); public static string DumpLines<T>(this IEnumerable<T> target) where T : Dumpable { var i = 0; return target.Aggregate("", (a, xx) => a + "[" + i++ + "] " + xx.Dump() + "\n"); } public static string Stringify<T>(this IEnumerable<T> target, string separator, bool showNumbers = false) { var result = new StringBuilder(); var i = 0; var isNext = false; foreach(var element in target) { if(isNext) result.Append(separator); if(showNumbers) result.Append("[" + i + "] "); isNext = true; result.Append(element); i++; } return result.ToString(); } public static TimeSpan Sum<T>(this IEnumerable<T> target, Func<T, TimeSpan> selector) { var result = new TimeSpan(); return target.Aggregate(result, (current, element) => current + selector(element)); } /// <summary> /// Returns index list of all elements, that have no other element, with "isInRelation(element, other)" is true /// For example if relation is "element ;&lt; other" will return the maximal element /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="isInRelation"></param> /// <returns></returns> public static IEnumerable<int> FrameIndexList<T>(this IEnumerable<T> list, Func<T, T, bool> isInRelation) { var listArray = list.ToArray(); return listArray.Select((item, index) => new Tuple<T, int>(item, index)) .Where(element => !listArray.Any(other => isInRelation(element.Item1, other))) .Select(element => element.Item2); } /// <summary> /// Returns list of all elements, that have no other element, with "isInRelation(element, other)" is true /// For example if relation is "element &lt; other" will return the maximal element /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="isInRelation"></param> /// <returns></returns> public static IEnumerable<T> FrameElementList<T>(this IEnumerable<T> list, Func<T, T, bool> isInRelation) { var listArray = list.ToArray(); return listArray.FrameIndexList(isInRelation).Select(index => listArray[index]); } public static IEnumerable<int> MaxIndexList<T>(this IEnumerable<T> list) where T : IComparable<T> => list.FrameIndexList((a, b) => a.CompareTo(b) < 0); public static IEnumerable<int> MinIndexList<T>(this IEnumerable<T> list) where T : IComparable<T> => list.FrameIndexList((a, b) => a.CompareTo(b) > 0); /// <summary> /// Checks if object starts with given object. /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="target"> The target. </param> /// <param name="y"> The y. </param> /// <returns> </returns> public static bool StartsWith<T>(this IList<T> target, IList<T> y) { if(target.Count < y.Count) return false; return !y.Where((t, i) => !Equals(target[i], t)).Any(); } /// <summary> /// Checks if object starts with given object and is longer. /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="target"> The target. </param> /// <param name="y"> The y. </param> /// <returns> </returns> public static bool StartsWithAndNotEqual<T>(this IList<T> target, IList<T> y) => target.Count != y.Count && target.StartsWith(y); public static TResult CheckedApply<T, TResult>(this T target, Func<T, TResult> function) where T : class where TResult : class => target == default(T)? default : function(target); public static TResult AssertValue<TResult>(this TResult? target) where TResult : struct { (target != null).Assert(); return target.Value; } public static TResult AssertNotNull<TResult>(this TResult target) where TResult : class { (target != null).Assert(); return target; } [NotNull] public static IEnumerable<int> Select(this int count) { for(var i = 0; i < count; i++) yield return i; } [NotNull] public static IEnumerable<long> Select(this long count) { for(long i = 0; i < count; i++) yield return i; } [NotNull] public static IEnumerable<int> Where(Func<int, bool> getValue) { for(var i = 0; getValue(i); i++) yield return i; } [NotNull] public static IEnumerable<T> Select<T>(this int count, Func<int, T> getValue) { for(var i = 0; i < count; i++) yield return getValue(i); } [NotNull] public static IEnumerable<T> Select<T>(this long count, Func<long, T> getValue) { for(long i = 0; i < count; i++) yield return getValue(i); } public static IEnumerable<Tuple<TKey, TLeft, TRight>> Merge<TKey, TLeft, TRight> ( this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> getLeftKey, Func<TRight, TKey> getRightKey ) where TLeft : class where TRight : class { var leftCommon = left.Select (l => new Tuple<TKey, TLeft, TRight>(getLeftKey(l), l, null)); var rightCommon = right.Select (r => new Tuple<TKey, TLeft, TRight>(getRightKey(r), null, r)); return leftCommon.Union(rightCommon) .GroupBy(t => t.Item1) .Select (Merge); } public static IEnumerable<Tuple<TKey, T, T>> Merge<TKey, T> (this IEnumerable<T> left, IEnumerable<T> right, Func<T, TKey> getKey) where T : class => Merge(left, right, getKey, getKey); public static Tuple<TKey, TLeft, TRight> Merge<TKey, TLeft, TRight> (IGrouping<TKey, Tuple<TKey, TLeft, TRight>> grouping) where TLeft : class where TRight : class { var list = grouping.ToArray(); switch(list.Length) { case 1: return list[0]; case 2: if(list[0].Item2 == null && list[1].Item3 == null) return new(grouping.Key, list[1].Item2, list[0].Item3); if(list[1].Item2 == null && list[0].Item3 == null) return new(grouping.Key, list[0].Item2, list[1].Item3); break; } throw new DuplicateKeyException(); } public static FunctionCache<TKey, IEnumerable<T>> ToDictionaryEx<TKey, T> (this IEnumerable<T> list, Func<T, TKey> selector) => new(key => list.Where(item => Equals(selector(item), key))); public static void AddRange<TKey, TValue> ( this IDictionary<TKey, TValue> target, IEnumerable<KeyValuePair<TKey, TValue>> newEntries ) { foreach(var item in newEntries.Where(entry => !target.ContainsKey(entry.Key))) target.Add(item); } /// <summary>Finds the index of the first item matching an expression in an enumerable.</summary> /// <param name="items">The enumerable to search.</param> /// <param name="predicate">The expression to test the items against.</param> /// <returns>The index of the first matching item, or null if no items match.</returns> public static int? IndexWhere<T>(this IEnumerable<T> items, Func<T, bool> predicate) { if(items == null) throw new ArgumentNullException(nameof(items)); if(predicate == null) throw new ArgumentNullException(nameof(predicate)); var result = 0; foreach(var item in items) { if(predicate(item)) return result; result++; } return null; } public static IEnumerable<T> Chain<T>(this T current, Func<T, T> getNext) where T : class { while(current != null) { yield return current; current = getNext(current); } } public static bool In<T>(this T a, params T[] b) => b.Contains(a); public static IEnumerable<TType> Sort<TType> (this IEnumerable<TType> target, Func<TType, IEnumerable<TType>> immediateParents) { var xx = target.ToArray(); xx.IsCircuitFree(immediateParents).Assert(); return null; } public static IEnumerable<TType> Closure<TType> (this IEnumerable<TType> target, Func<TType, IEnumerable<TType>> immediateParents) { var types = target.ToArray(); var targets = types; while(true) { targets = targets.SelectMany(immediateParents).Except(types).ToArray(); if(!targets.Any()) return types; types = types.Union(targets).ToArray(); } } public static bool IsCircuitFree<TType>(this TType target, Func<TType, IEnumerable<TType>> immediateParents) => immediateParents(target).Closure(immediateParents).All(item => !item.Equals(target)); public static bool IsCircuitFree<TType> (this IEnumerable<TType> target, Func<TType, IEnumerable<TType>> immediateParents) => target.All(item => item.IsCircuitFree(immediateParents)); public static IEnumerable<TType> Circuits<TType> (this IEnumerable<TType> target, Func<TType, IEnumerable<TType>> immediateParents) => target.Where(item => !item.IsCircuitFree(immediateParents)); public static IEnumerable<T> NullableToArray<T>(this T target) where T : class => target == null? new T[0] : new[] { target }; public static IEnumerable<T> NullableToArray<T>(this T? target) where T : struct => target == null? new T[0] : new[] { target.Value }; public static TTarget Top<TTarget> ( this IEnumerable<TTarget> target, Func<TTarget, bool> selector = null, Func<Exception> emptyException = null, Func<IEnumerable<TTarget>, Exception> multipleException = null, bool enableEmpty = true, bool enableMultiple = true ) { if(selector != null) target = target.Where(selector); using(var enumerator = target.GetEnumerator()) { if(!enumerator.MoveNext()) { if(emptyException != null) throw emptyException(); return enableEmpty? default : target.Single(); } var result = enumerator.Current; if(!enumerator.MoveNext()) return result; if(multipleException != null) throw multipleException(target); return enableMultiple? result : target.Single(); } } /// <summary> /// Splits an enumeration at positions where <see cref="isSeparator" /> returns true. /// The resulting enumeration of enumerations may contain the the separator item /// depending of <see cref="separatorTreatment" /> parameter /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <param name="isSeparator"></param> /// <param name="separatorTreatment"></param> /// <returns> /// Enumeration of arrays of <see cref="target" /> items /// split at points where <see cref="isSeparator" /> returns true. /// </returns> public static IEnumerable<IEnumerable<T>> Split<T> ( this IEnumerable<T> target, Func<T, bool> isSeparator , SeparatorTreatmentForSplit separatorTreatment = SeparatorTreatmentForSplit.Drop ) { var part = new List<T>(); foreach(var item in target) if(isSeparator(item)) { if(separatorTreatment == SeparatorTreatmentForSplit.EndOfSubList) part.Add(item); if(part.Any()) yield return part.ToArray(); part = new(); if(separatorTreatment == SeparatorTreatmentForSplit.BeginOfSubList) part.Add(item); } else part.Add(item); if(part.Any()) yield return part.ToArray(); } public static int? MaxEx(this IEnumerable<int> values) { if(values == null) throw new ArgumentNullException(nameof(values)); int? result = null; foreach(var value in values) if(result == null) result = value; else if(value > result) result = value; return result; } public static int? MinEx(this IEnumerable<int> values) { if(values == null) throw new ArgumentNullException(nameof(values)); int? result = null; foreach(var value in values) if(result == null) result = value; else if(value < result) result = value; return result; } public static IEnumerable<T> SelectHierarchical<T>(this T root, Func<T, IEnumerable<T>> getChildren) { yield return root; foreach(var item in getChildren(root).SelectMany(i => i.SelectHierarchical(getChildren))) yield return item; } static bool InternalAddDistinct<T>(ICollection<T> a, IEnumerable<T> b, Func<T, T, bool> isEqual) { var result = false; // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach(var bi in b) if(AddDistinct(a, bi, isEqual)) result = true; return result; } static bool InternalAddDistinct<T>(IList<T> a, IEnumerable<T> b, Func<T, T, T> combine) where T : class { var result = false; // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach(var bi in b) if(AddDistinct(a, bi, combine)) result = true; return result; } static bool AddDistinct<T>(ICollection<T> a, T bi, Func<T, T, bool> isEqual) { if(a.Any(ai => isEqual(ai, bi))) return false; a.Add(bi); return true; } static bool AddDistinct<T>(IList<T> a, T bi, Func<T, T, T> combine) where T : class { for(var i = 0; i < a.Count; i++) { var ab = combine(a[i], bi); if(ab != null) { a[i] = ab; return false; } } a.Add(bi); return true; } public static IEnumerable<T> ConcatMany<T>(this IEnumerable<IEnumerable<T>> target) => target .Where(i => i != null) .SelectMany(i => i); } // ReSharper disable once IdentifierTypo public interface IAggregateable<T> { T Aggregate(T other); } sealed class DuplicateKeyException : Exception { }
using System; using System.Linq; namespace Conejo { public enum ExchangeType { Direct, Fanout, Headers, Topic } public class ChannelConfiguration { public static ChannelConfiguration Create(Action<ChannelConfigurationDsl> config) { var configuration = new ChannelConfiguration(); config(new ChannelConfigurationDsl(configuration)); return configuration; } public Action<Exception> ExceptionHandler { get; set; } public string ExchangeName { get; set; } public ExchangeType ExchangeType { get; set; } public bool ExchangeDurable { get; set; } public bool ExchangeAutoDelete { get; set; } public string QueueName { get; set; } public Func<object, string> ExchangeRoutingKey { get; set; } public string QueueRoutingKey { get; set; } public bool QueueDurable { get; set; } public bool QueueExclusive { get; set; } public bool QueueAutoDelete { get; set; } public bool QueueAcknowledgeReciept { get; set; } } public class ChannelConfigurationDsl { private readonly ChannelConfiguration _configuration; public ChannelConfigurationDsl(ChannelConfiguration configuration) { _configuration = configuration; } public ChannelConfigurationDsl WithExceptionHandler(Action<Exception> handler) { _configuration.ExceptionHandler = handler; return this; } public FanoutExchangeConfigurationDsl ThroughRandomFanoutExchange() { return ThroughFanoutExchange(Guid.NewGuid().ToString()); } public FanoutExchangeConfigurationDsl ThroughFanoutExchange(string name) { _configuration.ExchangeName = name; _configuration.ExchangeType = ExchangeType.Fanout; return new FanoutExchangeConfigurationDsl(_configuration); } public DirectExchangeConfigurationDsl ThroughDefaultDirectExchange() { return ThroughDirectExchange(""); } public DirectExchangeConfigurationDsl ThroughRandomDirectExchange() { return ThroughDirectExchange(Guid.NewGuid().ToString()); } public DirectExchangeConfigurationDsl ThroughDirectExchange(string name) { _configuration.ExchangeName = name; _configuration.ExchangeType = ExchangeType.Direct; return new DirectExchangeConfigurationDsl(_configuration); } public TopicExchangeConfigurationDsl ThroughRandomTopicExchange() { return ThroughTopicExchange(Guid.NewGuid().ToString()); } public TopicExchangeConfigurationDsl ThroughTopicExchange(string name) { _configuration.ExchangeName = name; _configuration.ExchangeType = ExchangeType.Topic; return new TopicExchangeConfigurationDsl(_configuration); } } public class FanoutExchangeConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public FanoutExchangeConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public FanoutExchangeConfigurationDsl ThatsDurable() { _channelConfiguration.ExchangeDurable = true; return this; } public FanoutExchangeConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.ExchangeAutoDelete = true; return this; } public FanoutQueueConfigurationDsl InRandomQueue() { return InQueue(Guid.NewGuid().ToString()); } public FanoutQueueConfigurationDsl InQueue(string name) { _channelConfiguration.QueueName = name; return new FanoutQueueConfigurationDsl(_channelConfiguration); } } public class FanoutQueueConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public FanoutQueueConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public FanoutQueueConfigurationDsl ThatsDurable() { _channelConfiguration.QueueDurable = true; return this; } public FanoutQueueConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.QueueAutoDelete = true; return this; } public FanoutQueueConfigurationDsl ThatsExclusive() { _channelConfiguration.QueueExclusive = true; return this; } public FanoutQueueConfigurationDsl ThatAcknowledgesReciept() { _channelConfiguration.QueueAcknowledgeReciept = true; return this; } } public class DirectExchangeConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public DirectExchangeConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public DirectExchangeConfigurationDsl ThatsDurable() { _channelConfiguration.ExchangeDurable = true; return this; } public DirectExchangeConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.ExchangeAutoDelete = true; return this; } public DirectExchangeConfigurationDsl WithRoutingKey(string routingKey) { _channelConfiguration.ExchangeRoutingKey = message => routingKey; return this; } public DirectQueueConfigurationDsl InRandomQueue() { return InQueue(Guid.NewGuid().ToString()); } public DirectQueueConfigurationDsl InQueue(string name) { _channelConfiguration.QueueName = name; return new DirectQueueConfigurationDsl(_channelConfiguration); } } public class DirectQueueConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public DirectQueueConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public DirectQueueConfigurationDsl ThatsDurable() { _channelConfiguration.QueueDurable = true; return this; } public DirectQueueConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.QueueAutoDelete = true; return this; } public DirectQueueConfigurationDsl ThatsExclusive() { _channelConfiguration.QueueExclusive = true; return this; } public DirectQueueConfigurationDsl ThatAcknowledgesReciept() { _channelConfiguration.QueueAcknowledgeReciept = true; return this; } public DirectQueueConfigurationDsl WithRoutingKey(string routingKey) { _channelConfiguration.QueueRoutingKey = routingKey; return this; } public DirectQueueConfigurationDsl WithRoutingKeyAsQueueName() { _channelConfiguration.QueueRoutingKey = _channelConfiguration.QueueName; return this; } } public class TopicExchangeConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public TopicExchangeConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public TopicExchangeConfigurationDsl ThatsDurable() { _channelConfiguration.ExchangeDurable = true; return this; } public TopicExchangeConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.ExchangeAutoDelete = true; return this; } public TopicExchangeConfigurationDsl WithTopic(string topic) { _channelConfiguration.ExchangeRoutingKey = message => topic; return this; } public TopicExchangeConfigurationDsl WithTopic<TMessage>(params Func<TMessage, string>[] topic) { _channelConfiguration.ExchangeRoutingKey = message => topic.Select(x => x((TMessage)message)).Aggregate((a, i) => a + "." + i); return this; } public TopicQueueConfigurationDsl InRandomQueue() { return InQueue(Guid.NewGuid().ToString()); } public TopicQueueConfigurationDsl InQueue(string name) { _channelConfiguration.QueueName = name; return new TopicQueueConfigurationDsl(_channelConfiguration); } } public class TopicQueueConfigurationDsl { private readonly ChannelConfiguration _channelConfiguration; public TopicQueueConfigurationDsl(ChannelConfiguration channelConfiguration) { _channelConfiguration = channelConfiguration; } public TopicQueueConfigurationDsl ThatsDurable() { _channelConfiguration.QueueDurable = true; return this; } public TopicQueueConfigurationDsl ThatsAutoDeleted() { _channelConfiguration.QueueAutoDelete = true; return this; } public TopicQueueConfigurationDsl ThatsExclusive() { _channelConfiguration.QueueExclusive = true; return this; } public TopicQueueConfigurationDsl ThatAcknowledgesReciept() { _channelConfiguration.QueueAcknowledgeReciept = true; return this; } public TopicQueueConfigurationDsl WithTopic(string topic) { _channelConfiguration.QueueRoutingKey = topic; return this; } } }
// // TableViewBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // 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); col.CellSetCellData (Widget.Model, iter, false, false); Gdk.Rectangle column_cell_area = Widget.GetCellArea (path, col); CellRenderer[] renderers = col.GetCellRenderers(); for (int i = 0; i < renderers.Length; i++) { var cr = renderers [i]; if (cr == cra) { int position_x, width, height; int position_y = column_cell_area.Y; col.CellGetPosition (cr, out position_x, out width); if (i == renderers.Length - 1) { #if XWT_GTK3 // Gtk3 allocates all available space to the last cell in the column width = column_cell_area.Width - position_x; #else // Gtk2 sets the cell_area size to fit the largest cell in the inner column (row-wise) // since we would have to scan the tree for the largest cell at this (horizontal) cell position // we return the width of the current cell. int padding_x, padding_y; var cell_area = new Gdk.Rectangle(column_cell_area.X + position_x, position_y, width, column_cell_area.Height); cr.GetSize (col.TreeView, ref cell_area, out padding_x, out padding_y, out width, out height); position_x += padding_x; // and add some padding at the end if it would not exceed column bounds if (position_x + width + 2 <= column_cell_area.Width) width += 2; #endif } else { int position_x_next, width_next; col.CellGetPosition (renderers [i + 1], out position_x_next, out width_next); width = position_x_next - position_x; } position_x += column_cell_area.X; height = column_cell_area.Height; Widget.ConvertBinWindowToWidgetCoords (position_x, position_y, out position_x, out position_y); return new Rectangle (position_x, position_y, width, height); } } return Rectangle.Zero; } Rectangle ICellRendererTarget.GetCellBackgroundBounds (object target, Gtk.CellRenderer cra, Gtk.TreeIter iter) { var col = (TreeViewColumn)target; var path = Widget.Model.GetPath (iter); col.CellSetCellData (Widget.Model, iter, false, false); Gdk.Rectangle column_cell_area = Widget.GetCellArea (path, col); Gdk.Rectangle column_cell_bg_area = Widget.GetBackgroundArea (path, col); CellRenderer[] renderers = col.Cells; foreach (var cr in renderers) { if (cr == cra) { int position_x, width; col.CellGetPosition (cr, out position_x, out width); // Gtk aligns the bg area of a renderer to the cell area and not the bg area // so we add the cell area offset to the position here position_x += column_cell_bg_area.X + (column_cell_area.X - column_cell_bg_area.X); // last widget gets the rest if (cr == renderers[renderers.Length - 1]) width = column_cell_bg_area.Width - (position_x - column_cell_bg_area.X); var cell_bg_bounds = new Gdk.Rectangle (position_x, column_cell_bg_area.Y, width, column_cell_bg_area.Height); Widget.ConvertBinWindowToWidgetCoords (cell_bg_bounds.X, cell_bg_bounds.Y, out cell_bg_bounds.X, out cell_bg_bounds.Y); return new Rectangle (cell_bg_bounds.X, cell_bg_bounds.Y, cell_bg_bounds.Width, cell_bg_bounds.Height); } } return Rectangle.Zero; } protected Rectangle GetRowBounds (Gtk.TreeIter iter) { var rect = Rectangle.Zero; foreach (var col in Widget.Columns) { foreach (var cr in col.GetCellRenderers()) { Rectangle cell_rect = ((ICellRendererTarget)this).GetCellBounds (col, cr, iter); if (rect == Rectangle.Zero) rect = new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height); else rect = rect.Union (new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height)); } } return rect; } protected Rectangle GetRowBackgroundBounds (Gtk.TreeIter iter) { var path = Widget.Model.GetPath (iter); var rect = Rectangle.Zero; foreach (var col in Widget.Columns) { Gdk.Rectangle cell_rect = Widget.GetBackgroundArea (path, col); Widget.ConvertBinWindowToWidgetCoords (cell_rect.X, cell_rect.Y, out cell_rect.X, out cell_rect.Y); if (rect == Rectangle.Zero) rect = new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height); else rect = rect.Union (new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height)); } return rect; } protected Gtk.TreePath GetPathAtPosition (Point p) { Gtk.TreePath path; int x, y; Widget.ConvertWidgetToBinWindowCoords ((int)p.X, (int)p.Y, out x, out y); if (Widget.GetPathAtPos (x, y, out path)) return path; return null; } protected override ButtonEventArgs GetButtonPressEventArgs (ButtonPressEventArgs args) { int x, y; Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y); var xwt_args = base.GetButtonPressEventArgs (args); xwt_args.X = x; xwt_args.Y = y; return xwt_args; } protected override ButtonEventArgs GetButtonReleaseEventArgs (ButtonReleaseEventArgs args) { int x, y; Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y); var xwt_args = base.GetButtonReleaseEventArgs (args); xwt_args.X = x; xwt_args.Y = y; return xwt_args; } protected override MouseMovedEventArgs GetMouseMovedEventArgs (MotionNotifyEventArgs args) { int x, y; Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y); return new MouseMovedEventArgs ((long) args.Event.Time, x, y); } 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 (); } } }
// 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; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal class ExprVisitorBase { public EXPR Visit(EXPR pExpr) { if (pExpr == null) { return null; } EXPR pResult; if (IsCachedExpr(pExpr, out pResult)) { return pResult; } if (pExpr.isSTMT()) { return CacheExprMapping(pExpr, DispatchStatementList(pExpr.asSTMT())); } return CacheExprMapping(pExpr, Dispatch(pExpr)); } ///////////////////////////////////////////////////////////////////////////////// protected EXPRSTMT DispatchStatementList(EXPRSTMT expr) { Debug.Assert(expr != null); EXPRSTMT first = expr; EXPRSTMT pexpr = first; while (pexpr != null) { // If the processor replaces the statement -- potentially with // null, another statement, or a list of statements -- then we // make sure that the statement list is hooked together correctly. EXPRSTMT next = pexpr.GetOptionalNextStatement(); EXPRSTMT old = pexpr; // Unhook the next one. pexpr.SetOptionalNextStatement(null); EXPR result = Dispatch(pexpr); Debug.Assert(result == null || result.isSTMT()); if (pexpr == first) { first = (result == null) ? null : result.asSTMT(); } else { pexpr.SetOptionalNextStatement((result == null) ? null : result.asSTMT()); } // A transformation may return back a list of statements (or // if the statements have been determined to be unnecessary, // perhaps it has simply returned null.) // // Skip visiting the new list, then hook the tail of the old list // up to the end of the new list. while (pexpr.GetOptionalNextStatement() != null) { pexpr = pexpr.GetOptionalNextStatement(); } // Re-hook the next pointer. pexpr.SetOptionalNextStatement(next); } return first; } ///////////////////////////////////////////////////////////////////////////////// protected bool IsCachedExpr(EXPR pExpr, out EXPR pTransformedExpr) { pTransformedExpr = null; return false; } ///////////////////////////////////////////////////////////////////////////////// protected EXPR CacheExprMapping(EXPR pExpr, EXPR pTransformedExpr) { return pTransformedExpr; } protected virtual EXPR Dispatch(EXPR pExpr) { switch (pExpr.kind) { case ExpressionKind.EK_BLOCK: return VisitBLOCK(pExpr as EXPRBLOCK); case ExpressionKind.EK_RETURN: return VisitRETURN(pExpr as EXPRRETURN); case ExpressionKind.EK_BINOP: return VisitBINOP(pExpr as EXPRBINOP); case ExpressionKind.EK_UNARYOP: return VisitUNARYOP(pExpr as EXPRUNARYOP); case ExpressionKind.EK_ASSIGNMENT: return VisitASSIGNMENT(pExpr as EXPRASSIGNMENT); case ExpressionKind.EK_LIST: return VisitLIST(pExpr as EXPRLIST); case ExpressionKind.EK_QUESTIONMARK: return VisitQUESTIONMARK(pExpr as EXPRQUESTIONMARK); case ExpressionKind.EK_ARRAYINDEX: return VisitARRAYINDEX(pExpr as EXPRARRAYINDEX); case ExpressionKind.EK_ARRAYLENGTH: return VisitARRAYLENGTH(pExpr as EXPRARRAYLENGTH); case ExpressionKind.EK_CALL: return VisitCALL(pExpr as EXPRCALL); case ExpressionKind.EK_EVENT: return VisitEVENT(pExpr as EXPREVENT); case ExpressionKind.EK_FIELD: return VisitFIELD(pExpr as EXPRFIELD); case ExpressionKind.EK_LOCAL: return VisitLOCAL(pExpr as EXPRLOCAL); case ExpressionKind.EK_THISPOINTER: return VisitTHISPOINTER(pExpr as EXPRTHISPOINTER); case ExpressionKind.EK_CONSTANT: return VisitCONSTANT(pExpr as EXPRCONSTANT); case ExpressionKind.EK_TYPEARGUMENTS: return VisitTYPEARGUMENTS(pExpr as EXPRTYPEARGUMENTS); case ExpressionKind.EK_TYPEORNAMESPACE: return VisitTYPEORNAMESPACE(pExpr as EXPRTYPEORNAMESPACE); case ExpressionKind.EK_CLASS: return VisitCLASS(pExpr as EXPRCLASS); case ExpressionKind.EK_FUNCPTR: return VisitFUNCPTR(pExpr as EXPRFUNCPTR); case ExpressionKind.EK_PROP: return VisitPROP(pExpr as EXPRPROP); case ExpressionKind.EK_MULTI: return VisitMULTI(pExpr as EXPRMULTI); case ExpressionKind.EK_MULTIGET: return VisitMULTIGET(pExpr as EXPRMULTIGET); case ExpressionKind.EK_WRAP: return VisitWRAP(pExpr as EXPRWRAP); case ExpressionKind.EK_CONCAT: return VisitCONCAT(pExpr as EXPRCONCAT); case ExpressionKind.EK_ARRINIT: return VisitARRINIT(pExpr as EXPRARRINIT); case ExpressionKind.EK_CAST: return VisitCAST(pExpr as EXPRCAST); case ExpressionKind.EK_USERDEFINEDCONVERSION: return VisitUSERDEFINEDCONVERSION(pExpr as EXPRUSERDEFINEDCONVERSION); case ExpressionKind.EK_TYPEOF: return VisitTYPEOF(pExpr as EXPRTYPEOF); case ExpressionKind.EK_ZEROINIT: return VisitZEROINIT(pExpr as EXPRZEROINIT); case ExpressionKind.EK_USERLOGOP: return VisitUSERLOGOP(pExpr as EXPRUSERLOGOP); case ExpressionKind.EK_MEMGRP: return VisitMEMGRP(pExpr as EXPRMEMGRP); case ExpressionKind.EK_BOUNDLAMBDA: return VisitBOUNDLAMBDA(pExpr as EXPRBOUNDLAMBDA); case ExpressionKind.EK_UNBOUNDLAMBDA: return VisitUNBOUNDLAMBDA(pExpr as EXPRUNBOUNDLAMBDA); case ExpressionKind.EK_HOISTEDLOCALEXPR: return VisitHOISTEDLOCALEXPR(pExpr as EXPRHOISTEDLOCALEXPR); case ExpressionKind.EK_FIELDINFO: return VisitFIELDINFO(pExpr as EXPRFIELDINFO); case ExpressionKind.EK_METHODINFO: return VisitMETHODINFO(pExpr as EXPRMETHODINFO); // Binary operators case ExpressionKind.EK_EQUALS: return VisitEQUALS(pExpr.asBIN()); case ExpressionKind.EK_COMPARE: return VisitCOMPARE(pExpr.asBIN()); case ExpressionKind.EK_NE: return VisitNE(pExpr.asBIN()); case ExpressionKind.EK_LT: return VisitLT(pExpr.asBIN()); case ExpressionKind.EK_LE: return VisitLE(pExpr.asBIN()); case ExpressionKind.EK_GT: return VisitGT(pExpr.asBIN()); case ExpressionKind.EK_GE: return VisitGE(pExpr.asBIN()); case ExpressionKind.EK_ADD: return VisitADD(pExpr.asBIN()); case ExpressionKind.EK_SUB: return VisitSUB(pExpr.asBIN()); case ExpressionKind.EK_MUL: return VisitMUL(pExpr.asBIN()); case ExpressionKind.EK_DIV: return VisitDIV(pExpr.asBIN()); case ExpressionKind.EK_MOD: return VisitMOD(pExpr.asBIN()); case ExpressionKind.EK_BITAND: return VisitBITAND(pExpr.asBIN()); case ExpressionKind.EK_BITOR: return VisitBITOR(pExpr.asBIN()); case ExpressionKind.EK_BITXOR: return VisitBITXOR(pExpr.asBIN()); case ExpressionKind.EK_LSHIFT: return VisitLSHIFT(pExpr.asBIN()); case ExpressionKind.EK_RSHIFT: return VisitRSHIFT(pExpr.asBIN()); case ExpressionKind.EK_LOGAND: return VisitLOGAND(pExpr.asBIN()); case ExpressionKind.EK_LOGOR: return VisitLOGOR(pExpr.asBIN()); case ExpressionKind.EK_SEQUENCE: return VisitSEQUENCE(pExpr.asBIN()); case ExpressionKind.EK_SEQREV: return VisitSEQREV(pExpr.asBIN()); case ExpressionKind.EK_SAVE: return VisitSAVE(pExpr.asBIN()); case ExpressionKind.EK_SWAP: return VisitSWAP(pExpr.asBIN()); case ExpressionKind.EK_INDIR: return VisitINDIR(pExpr.asBIN()); case ExpressionKind.EK_STRINGEQ: return VisitSTRINGEQ(pExpr.asBIN()); case ExpressionKind.EK_STRINGNE: return VisitSTRINGNE(pExpr.asBIN()); case ExpressionKind.EK_DELEGATEEQ: return VisitDELEGATEEQ(pExpr.asBIN()); case ExpressionKind.EK_DELEGATENE: return VisitDELEGATENE(pExpr.asBIN()); case ExpressionKind.EK_DELEGATEADD: return VisitDELEGATEADD(pExpr.asBIN()); case ExpressionKind.EK_DELEGATESUB: return VisitDELEGATESUB(pExpr.asBIN()); case ExpressionKind.EK_EQ: return VisitEQ(pExpr.asBIN()); // Unary operators case ExpressionKind.EK_TRUE: return VisitTRUE(pExpr.asUnaryOperator()); case ExpressionKind.EK_FALSE: return VisitFALSE(pExpr.asUnaryOperator()); case ExpressionKind.EK_INC: return VisitINC(pExpr.asUnaryOperator()); case ExpressionKind.EK_DEC: return VisitDEC(pExpr.asUnaryOperator()); case ExpressionKind.EK_LOGNOT: return VisitLOGNOT(pExpr.asUnaryOperator()); case ExpressionKind.EK_NEG: return VisitNEG(pExpr.asUnaryOperator()); case ExpressionKind.EK_UPLUS: return VisitUPLUS(pExpr.asUnaryOperator()); case ExpressionKind.EK_BITNOT: return VisitBITNOT(pExpr.asUnaryOperator()); case ExpressionKind.EK_ADDR: return VisitADDR(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALNEG: return VisitDECIMALNEG(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALINC: return VisitDECIMALINC(pExpr.asUnaryOperator()); case ExpressionKind.EK_DECIMALDEC: return VisitDECIMALDEC(pExpr.asUnaryOperator()); default: throw Error.InternalCompilerError(); } } protected void VisitChildren(EXPR pExpr) { Debug.Assert(pExpr != null); EXPR exprRet = null; // Lists are a special case. We treat a list not as a // binary node but rather as a node with n children. if (pExpr.isLIST()) { EXPRLIST list = pExpr.asLIST(); while (true) { list.SetOptionalElement(Visit(list.GetOptionalElement())); if (list.GetOptionalNextListNode() == null) { return; } if (!list.GetOptionalNextListNode().isLIST()) { list.SetOptionalNextListNode(Visit(list.GetOptionalNextListNode())); return; } list = list.GetOptionalNextListNode().asLIST(); } } switch (pExpr.kind) { default: if (pExpr.isUnaryOperator()) { goto VISIT_EXPRUNARYOP; } Debug.Assert(pExpr.isBIN()); goto VISIT_EXPRBINOP; VISIT_EXPR: break; VISIT_BASE_EXPRSTMT: goto VISIT_EXPR; VISIT_EXPRSTMT: goto VISIT_BASE_EXPRSTMT; case ExpressionKind.EK_BINOP: goto VISIT_EXPRBINOP; VISIT_BASE_EXPRBINOP: goto VISIT_EXPR; VISIT_EXPRBINOP: exprRet = Visit((pExpr as EXPRBINOP).GetOptionalLeftChild()); (pExpr as EXPRBINOP).SetOptionalLeftChild(exprRet as EXPR); exprRet = Visit((pExpr as EXPRBINOP).GetOptionalRightChild()); (pExpr as EXPRBINOP).SetOptionalRightChild(exprRet as EXPR); goto VISIT_BASE_EXPRBINOP; case ExpressionKind.EK_LIST: goto VISIT_EXPRLIST; VISIT_BASE_EXPRLIST: goto VISIT_EXPR; VISIT_EXPRLIST: exprRet = Visit((pExpr as EXPRLIST).GetOptionalElement()); (pExpr as EXPRLIST).SetOptionalElement(exprRet as EXPR); exprRet = Visit((pExpr as EXPRLIST).GetOptionalNextListNode()); (pExpr as EXPRLIST).SetOptionalNextListNode(exprRet as EXPR); goto VISIT_BASE_EXPRLIST; case ExpressionKind.EK_ASSIGNMENT: goto VISIT_EXPRASSIGNMENT; VISIT_BASE_EXPRASSIGNMENT: goto VISIT_EXPR; VISIT_EXPRASSIGNMENT: exprRet = Visit((pExpr as EXPRASSIGNMENT).GetLHS()); Debug.Assert(exprRet != null); (pExpr as EXPRASSIGNMENT).SetLHS(exprRet as EXPR); exprRet = Visit((pExpr as EXPRASSIGNMENT).GetRHS()); Debug.Assert(exprRet != null); (pExpr as EXPRASSIGNMENT).SetRHS(exprRet as EXPR); goto VISIT_BASE_EXPRASSIGNMENT; case ExpressionKind.EK_QUESTIONMARK: goto VISIT_EXPRQUESTIONMARK; VISIT_BASE_EXPRQUESTIONMARK: goto VISIT_EXPR; VISIT_EXPRQUESTIONMARK: exprRet = Visit((pExpr as EXPRQUESTIONMARK).GetTestExpression()); Debug.Assert(exprRet != null); (pExpr as EXPRQUESTIONMARK).SetTestExpression(exprRet as EXPR); exprRet = Visit((pExpr as EXPRQUESTIONMARK).GetConsequence()); Debug.Assert(exprRet != null); (pExpr as EXPRQUESTIONMARK).SetConsequence(exprRet as EXPRBINOP); goto VISIT_BASE_EXPRQUESTIONMARK; case ExpressionKind.EK_ARRAYINDEX: goto VISIT_EXPRARRAYINDEX; VISIT_BASE_EXPRARRAYINDEX: goto VISIT_EXPR; VISIT_EXPRARRAYINDEX: exprRet = Visit((pExpr as EXPRARRAYINDEX).GetArray()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYINDEX).SetArray(exprRet as EXPR); exprRet = Visit((pExpr as EXPRARRAYINDEX).GetIndex()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYINDEX).SetIndex(exprRet as EXPR); goto VISIT_BASE_EXPRARRAYINDEX; case ExpressionKind.EK_ARRAYLENGTH: goto VISIT_EXPRARRAYLENGTH; VISIT_BASE_EXPRARRAYLENGTH: goto VISIT_EXPR; VISIT_EXPRARRAYLENGTH: exprRet = Visit((pExpr as EXPRARRAYLENGTH).GetArray()); Debug.Assert(exprRet != null); (pExpr as EXPRARRAYLENGTH).SetArray(exprRet as EXPR); goto VISIT_BASE_EXPRARRAYLENGTH; case ExpressionKind.EK_UNARYOP: goto VISIT_EXPRUNARYOP; VISIT_BASE_EXPRUNARYOP: goto VISIT_EXPR; VISIT_EXPRUNARYOP: exprRet = Visit((pExpr as EXPRUNARYOP).Child); Debug.Assert(exprRet != null); (pExpr as EXPRUNARYOP).Child = exprRet as EXPR; goto VISIT_BASE_EXPRUNARYOP; case ExpressionKind.EK_USERLOGOP: goto VISIT_EXPRUSERLOGOP; VISIT_BASE_EXPRUSERLOGOP: goto VISIT_EXPR; VISIT_EXPRUSERLOGOP: exprRet = Visit((pExpr as EXPRUSERLOGOP).TrueFalseCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).TrueFalseCall = exprRet as EXPR; exprRet = Visit((pExpr as EXPRUSERLOGOP).OperatorCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).OperatorCall = exprRet as EXPRCALL; exprRet = Visit((pExpr as EXPRUSERLOGOP).FirstOperandToExamine); Debug.Assert(exprRet != null); (pExpr as EXPRUSERLOGOP).FirstOperandToExamine = exprRet as EXPR; goto VISIT_BASE_EXPRUSERLOGOP; case ExpressionKind.EK_TYPEOF: goto VISIT_EXPRTYPEOF; VISIT_BASE_EXPRTYPEOF: goto VISIT_EXPR; VISIT_EXPRTYPEOF: exprRet = Visit((pExpr as EXPRTYPEOF).GetSourceType()); (pExpr as EXPRTYPEOF).SetSourceType(exprRet as EXPRTYPEORNAMESPACE); goto VISIT_BASE_EXPRTYPEOF; case ExpressionKind.EK_CAST: goto VISIT_EXPRCAST; VISIT_BASE_EXPRCAST: goto VISIT_EXPR; VISIT_EXPRCAST: exprRet = Visit((pExpr as EXPRCAST).GetArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCAST).SetArgument(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCAST).GetDestinationType()); (pExpr as EXPRCAST).SetDestinationType(exprRet as EXPRTYPEORNAMESPACE); goto VISIT_BASE_EXPRCAST; case ExpressionKind.EK_USERDEFINEDCONVERSION: goto VISIT_EXPRUSERDEFINEDCONVERSION; VISIT_BASE_EXPRUSERDEFINEDCONVERSION: goto VISIT_EXPR; VISIT_EXPRUSERDEFINEDCONVERSION: exprRet = Visit((pExpr as EXPRUSERDEFINEDCONVERSION).UserDefinedCall); Debug.Assert(exprRet != null); (pExpr as EXPRUSERDEFINEDCONVERSION).UserDefinedCall = exprRet as EXPR; goto VISIT_BASE_EXPRUSERDEFINEDCONVERSION; case ExpressionKind.EK_ZEROINIT: goto VISIT_EXPRZEROINIT; VISIT_BASE_EXPRZEROINIT: goto VISIT_EXPR; VISIT_EXPRZEROINIT: exprRet = Visit((pExpr as EXPRZEROINIT).OptionalArgument); (pExpr as EXPRZEROINIT).OptionalArgument = exprRet as EXPR; // Used for when we zeroinit 0 parameter constructors for structs/enums. exprRet = Visit((pExpr as EXPRZEROINIT).OptionalConstructorCall); (pExpr as EXPRZEROINIT).OptionalConstructorCall = exprRet as EXPR; goto VISIT_BASE_EXPRZEROINIT; case ExpressionKind.EK_BLOCK: goto VISIT_EXPRBLOCK; VISIT_BASE_EXPRBLOCK: goto VISIT_EXPRSTMT; VISIT_EXPRBLOCK: exprRet = Visit((pExpr as EXPRBLOCK).GetOptionalStatements()); (pExpr as EXPRBLOCK).SetOptionalStatements(exprRet as EXPRSTMT); goto VISIT_BASE_EXPRBLOCK; case ExpressionKind.EK_MEMGRP: goto VISIT_EXPRMEMGRP; VISIT_BASE_EXPRMEMGRP: goto VISIT_EXPR; VISIT_EXPRMEMGRP: // The object expression. NULL for a static invocation. exprRet = Visit((pExpr as EXPRMEMGRP).GetOptionalObject()); (pExpr as EXPRMEMGRP).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRMEMGRP; case ExpressionKind.EK_CALL: goto VISIT_EXPRCALL; VISIT_BASE_EXPRCALL: goto VISIT_EXPR; VISIT_EXPRCALL: exprRet = Visit((pExpr as EXPRCALL).GetOptionalArguments()); (pExpr as EXPRCALL).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCALL).GetMemberGroup()); Debug.Assert(exprRet != null); (pExpr as EXPRCALL).SetMemberGroup(exprRet as EXPRMEMGRP); goto VISIT_BASE_EXPRCALL; case ExpressionKind.EK_PROP: goto VISIT_EXPRPROP; VISIT_BASE_EXPRPROP: goto VISIT_EXPR; VISIT_EXPRPROP: exprRet = Visit((pExpr as EXPRPROP).GetOptionalArguments()); (pExpr as EXPRPROP).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRPROP).GetMemberGroup()); Debug.Assert(exprRet != null); (pExpr as EXPRPROP).SetMemberGroup(exprRet as EXPRMEMGRP); goto VISIT_BASE_EXPRPROP; case ExpressionKind.EK_FIELD: goto VISIT_EXPRFIELD; VISIT_BASE_EXPRFIELD: goto VISIT_EXPR; VISIT_EXPRFIELD: exprRet = Visit((pExpr as EXPRFIELD).GetOptionalObject()); (pExpr as EXPRFIELD).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRFIELD; case ExpressionKind.EK_EVENT: goto VISIT_EXPREVENT; VISIT_BASE_EXPREVENT: goto VISIT_EXPR; VISIT_EXPREVENT: exprRet = Visit((pExpr as EXPREVENT).OptionalObject); (pExpr as EXPREVENT).OptionalObject = exprRet as EXPR; goto VISIT_BASE_EXPREVENT; case ExpressionKind.EK_LOCAL: goto VISIT_EXPRLOCAL; VISIT_BASE_EXPRLOCAL: goto VISIT_EXPR; VISIT_EXPRLOCAL: goto VISIT_BASE_EXPRLOCAL; case ExpressionKind.EK_THISPOINTER: goto VISIT_EXPRTHISPOINTER; VISIT_BASE_EXPRTHISPOINTER: goto VISIT_EXPRLOCAL; VISIT_EXPRTHISPOINTER: goto VISIT_BASE_EXPRTHISPOINTER; case ExpressionKind.EK_RETURN: goto VISIT_EXPRRETURN; VISIT_BASE_EXPRRETURN: goto VISIT_EXPRSTMT; VISIT_EXPRRETURN: exprRet = Visit((pExpr as EXPRRETURN).GetOptionalObject()); (pExpr as EXPRRETURN).SetOptionalObject(exprRet as EXPR); goto VISIT_BASE_EXPRRETURN; case ExpressionKind.EK_CONSTANT: goto VISIT_EXPRCONSTANT; VISIT_BASE_EXPRCONSTANT: goto VISIT_EXPR; VISIT_EXPRCONSTANT: // Used for when we zeroinit 0 parameter constructors for structs/enums. exprRet = Visit((pExpr as EXPRCONSTANT).GetOptionalConstructorCall()); (pExpr as EXPRCONSTANT).SetOptionalConstructorCall(exprRet as EXPR); goto VISIT_BASE_EXPRCONSTANT; /************************************************************************************************* TYPEEXPRs defined: The following exprs are used to represent the results of type binding, and are defined as follows: TYPEARGUMENTS - This wraps the type arguments for a class. It contains the TypeArray* which is associated with the AggregateType for the instantiation of the class. TYPEORNAMESPACE - This is the base class for this set of EXPRs. When binding a type, the result must be a type or a namespace. This EXPR encapsulates that fact. The lhs member is the EXPR tree that was bound to resolve the type or namespace. TYPEORNAMESPACEERROR - This is the error class for the type or namespace exprs when we dont know what to bind it to. The following three exprs all have a TYPEORNAMESPACE child, which is their fundamental type: POINTERTYPE - This wraps the sym for the pointer type. NULLABLETYPE - This wraps the sym for the nullable type. CLASS - This represents an instantiation of a class. NSPACE - This represents a namespace, which is the intermediate step when attempting to bind a qualified name. ALIAS - This represents an alias *************************************************************************************************/ case ExpressionKind.EK_TYPEARGUMENTS: goto VISIT_EXPRTYPEARGUMENTS; VISIT_BASE_EXPRTYPEARGUMENTS: goto VISIT_EXPR; VISIT_EXPRTYPEARGUMENTS: exprRet = Visit((pExpr as EXPRTYPEARGUMENTS).GetOptionalElements()); (pExpr as EXPRTYPEARGUMENTS).SetOptionalElements(exprRet as EXPR); goto VISIT_BASE_EXPRTYPEARGUMENTS; case ExpressionKind.EK_TYPEORNAMESPACE: goto VISIT_EXPRTYPEORNAMESPACE; VISIT_BASE_EXPRTYPEORNAMESPACE: goto VISIT_EXPR; VISIT_EXPRTYPEORNAMESPACE: goto VISIT_BASE_EXPRTYPEORNAMESPACE; case ExpressionKind.EK_CLASS: goto VISIT_EXPRCLASS; VISIT_BASE_EXPRCLASS: goto VISIT_EXPRTYPEORNAMESPACE; VISIT_EXPRCLASS: goto VISIT_BASE_EXPRCLASS; case ExpressionKind.EK_FUNCPTR: goto VISIT_EXPRFUNCPTR; VISIT_BASE_EXPRFUNCPTR: goto VISIT_EXPR; VISIT_EXPRFUNCPTR: goto VISIT_BASE_EXPRFUNCPTR; case ExpressionKind.EK_MULTIGET: goto VISIT_EXPRMULTIGET; VISIT_BASE_EXPRMULTIGET: goto VISIT_EXPR; VISIT_EXPRMULTIGET: goto VISIT_BASE_EXPRMULTIGET; case ExpressionKind.EK_MULTI: goto VISIT_EXPRMULTI; VISIT_BASE_EXPRMULTI: goto VISIT_EXPR; VISIT_EXPRMULTI: exprRet = Visit((pExpr as EXPRMULTI).GetLeft()); Debug.Assert(exprRet != null); (pExpr as EXPRMULTI).SetLeft(exprRet as EXPR); exprRet = Visit((pExpr as EXPRMULTI).GetOperator()); Debug.Assert(exprRet != null); (pExpr as EXPRMULTI).SetOperator(exprRet as EXPR); goto VISIT_BASE_EXPRMULTI; case ExpressionKind.EK_WRAP: goto VISIT_EXPRWRAP; VISIT_BASE_EXPRWRAP: goto VISIT_EXPR; VISIT_EXPRWRAP: goto VISIT_BASE_EXPRWRAP; case ExpressionKind.EK_CONCAT: goto VISIT_EXPRCONCAT; VISIT_BASE_EXPRCONCAT: goto VISIT_EXPR; VISIT_EXPRCONCAT: exprRet = Visit((pExpr as EXPRCONCAT).GetFirstArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCONCAT).SetFirstArgument(exprRet as EXPR); exprRet = Visit((pExpr as EXPRCONCAT).GetSecondArgument()); Debug.Assert(exprRet != null); (pExpr as EXPRCONCAT).SetSecondArgument(exprRet as EXPR); goto VISIT_BASE_EXPRCONCAT; case ExpressionKind.EK_ARRINIT: goto VISIT_EXPRARRINIT; VISIT_BASE_EXPRARRINIT: goto VISIT_EXPR; VISIT_EXPRARRINIT: exprRet = Visit((pExpr as EXPRARRINIT).GetOptionalArguments()); (pExpr as EXPRARRINIT).SetOptionalArguments(exprRet as EXPR); exprRet = Visit((pExpr as EXPRARRINIT).GetOptionalArgumentDimensions()); (pExpr as EXPRARRINIT).SetOptionalArgumentDimensions(exprRet as EXPR); goto VISIT_BASE_EXPRARRINIT; case ExpressionKind.EK_NOOP: goto VISIT_EXPRNOOP; VISIT_BASE_EXPRNOOP: goto VISIT_EXPRSTMT; VISIT_EXPRNOOP: goto VISIT_BASE_EXPRNOOP; case ExpressionKind.EK_BOUNDLAMBDA: goto VISIT_EXPRBOUNDLAMBDA; VISIT_BASE_EXPRBOUNDLAMBDA: goto VISIT_EXPR; VISIT_EXPRBOUNDLAMBDA: exprRet = Visit((pExpr as EXPRBOUNDLAMBDA).OptionalBody); (pExpr as EXPRBOUNDLAMBDA).OptionalBody = exprRet as EXPRBLOCK; goto VISIT_BASE_EXPRBOUNDLAMBDA; case ExpressionKind.EK_UNBOUNDLAMBDA: goto VISIT_EXPRUNBOUNDLAMBDA; VISIT_BASE_EXPRUNBOUNDLAMBDA: goto VISIT_EXPR; VISIT_EXPRUNBOUNDLAMBDA: goto VISIT_BASE_EXPRUNBOUNDLAMBDA; case ExpressionKind.EK_HOISTEDLOCALEXPR: goto VISIT_EXPRHOISTEDLOCALEXPR; VISIT_BASE_EXPRHOISTEDLOCALEXPR: goto VISIT_EXPR; VISIT_EXPRHOISTEDLOCALEXPR: goto VISIT_BASE_EXPRHOISTEDLOCALEXPR; case ExpressionKind.EK_FIELDINFO: goto VISIT_EXPRFIELDINFO; VISIT_BASE_EXPRFIELDINFO: goto VISIT_EXPR; VISIT_EXPRFIELDINFO: goto VISIT_BASE_EXPRFIELDINFO; case ExpressionKind.EK_METHODINFO: goto VISIT_EXPRMETHODINFO; VISIT_BASE_EXPRMETHODINFO: goto VISIT_EXPR; VISIT_EXPRMETHODINFO: goto VISIT_BASE_EXPRMETHODINFO; } } protected virtual EXPR VisitEXPR(EXPR pExpr) { VisitChildren(pExpr); return pExpr; } protected virtual EXPR VisitBLOCK(EXPRBLOCK pExpr) { return VisitSTMT(pExpr); } protected virtual EXPR VisitTHISPOINTER(EXPRTHISPOINTER pExpr) { return VisitLOCAL(pExpr); } protected virtual EXPR VisitRETURN(EXPRRETURN pExpr) { return VisitSTMT(pExpr); } protected virtual EXPR VisitCLASS(EXPRCLASS pExpr) { return VisitTYPEORNAMESPACE(pExpr); } protected virtual EXPR VisitSTMT(EXPRSTMT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitBINOP(EXPRBINOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitLIST(EXPRLIST pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitASSIGNMENT(EXPRASSIGNMENT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitQUESTIONMARK(EXPRQUESTIONMARK pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRAYINDEX(EXPRARRAYINDEX pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRAYLENGTH(EXPRARRAYLENGTH pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUNARYOP(EXPRUNARYOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUSERLOGOP(EXPRUSERLOGOP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEOF(EXPRTYPEOF pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCAST(EXPRCAST pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUSERDEFINEDCONVERSION(EXPRUSERDEFINEDCONVERSION pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitZEROINIT(EXPRZEROINIT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMEMGRP(EXPRMEMGRP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCALL(EXPRCALL pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitPROP(EXPRPROP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFIELD(EXPRFIELD pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitEVENT(EXPREVENT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitLOCAL(EXPRLOCAL pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCONSTANT(EXPRCONSTANT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEARGUMENTS(EXPRTYPEARGUMENTS pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitTYPEORNAMESPACE(EXPRTYPEORNAMESPACE pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFUNCPTR(EXPRFUNCPTR pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMULTIGET(EXPRMULTIGET pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMULTI(EXPRMULTI pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitWRAP(EXPRWRAP pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitCONCAT(EXPRCONCAT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitARRINIT(EXPRARRINIT pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitBOUNDLAMBDA(EXPRBOUNDLAMBDA pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitUNBOUNDLAMBDA(EXPRUNBOUNDLAMBDA pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitHOISTEDLOCALEXPR(EXPRHOISTEDLOCALEXPR pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitFIELDINFO(EXPRFIELDINFO pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitMETHODINFO(EXPRMETHODINFO pExpr) { return VisitEXPR(pExpr); } protected virtual EXPR VisitEQUALS(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitCOMPARE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitNE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitGE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitADD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSUB(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDIV(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITAND(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLSHIFT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLOGAND(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSEQUENCE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSAVE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitINDIR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSTRINGEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATEEQ(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATEADD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitRANGE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitMUL(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitBITXOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitRSHIFT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitLOGOR(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSEQREV(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSTRINGNE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATENE(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitGT(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitMOD(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitSWAP(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitDELEGATESUB(EXPRBINOP pExpr) { return VisitBINOP(pExpr); } protected virtual EXPR VisitTRUE(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitINC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitLOGNOT(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitNEG(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitBITNOT(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitADDR(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALNEG(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALDEC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitFALSE(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDEC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitUPLUS(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } protected virtual EXPR VisitDECIMALINC(EXPRUNARYOP pExpr) { return VisitUNARYOP(pExpr); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects user account data (creating new users, looking up existing /// users) to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianUserAccountServiceConnector")] public class SimianUserAccountServiceConnector : IUserAccountService, ISharedRegionModule { private const double CACHE_EXPIRATION_SECONDS = 120.0; private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private ExpiringCache<UUID, UserAccount> m_accountCache = new ExpiringCache<UUID, UserAccount>(); private bool m_Enabled; private string m_serverUrl = String.Empty; #region ISharedRegionModule public SimianUserAccountServiceConnector() { } public string Name { get { return "SimianUserAccountServiceConnector"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IUserAccountService>(this); } } public void Close() { } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserAccountService>(this); } } #endregion ISharedRegionModule public SimianUserAccountServiceConnector(IConfigSource source) { CommonInit(source); } public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "Name", firstName + ' ' + lastName } }; return GetUser(requestArgs); } public UserAccount GetUserAccount(UUID scopeID, string email) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "Email", email } }; return GetUser(requestArgs); } public UserAccount GetUserAccount(UUID scopeID, UUID userID) { // Cache check UserAccount account; if (m_accountCache.TryGetValue(userID, out account)) return account; NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; account = GetUser(requestArgs); if (account == null) { // Store null responses too, to avoid repeated lookups for missing accounts m_accountCache.AddOrUpdate(userID, null, CACHE_EXPIRATION_SECONDS); } return account; } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { List<UserAccount> accounts = new List<UserAccount>(); // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUsers" }, { "NameQuery", query } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDArray array = response["Users"] as OSDArray; if (array != null && array.Count > 0) { for (int i = 0; i < array.Count; i++) { UserAccount account = ResponseToUserAccount(array[i] as OSDMap); if (account != null) accounts.Add(account); } } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format"); } } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query); } return accounts; } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("UserAccountServices", ""); if (name == Name) CommonInit(source); } } public void InvalidateCache(UUID userID) { m_accountCache.Remove(userID); } public bool StoreUserAccount(UserAccount data) { // m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUser" }, { "UserID", data.PrincipalID.ToString() }, { "Name", data.Name }, { "Email", data.Email }, { "AccessLevel", data.UserLevel.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name); requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", data.PrincipalID.ToString() }, { "CreationDate", data.Created.ToString() }, { "UserFlags", data.UserFlags.ToString() }, { "UserTitle", data.UserTitle } }; response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (success) { // Cache the user account info m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS); } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString()); } return success; } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString()); } return false; } /// <summary> /// Convert a name with a single space in it to a first and last name /// </summary> /// <param name="name">A full name such as "John Doe"</param> /// <param name="firstName">First name</param> /// <param name="lastName">Last name (surname)</param> private static void GetFirstLastName(string name, out string firstName, out string lastName) { if (String.IsNullOrEmpty(name)) { firstName = String.Empty; lastName = String.Empty; } else { string[] names = name.Split(' '); if (names.Length == 2) { firstName = names[0]; lastName = names[1]; } else { firstName = String.Empty; lastName = name; } } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["UserAccountService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("UserAccountServerURI"); 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 ACCOUNT CONNECTOR]: No UserAccountServerURI specified, disabling connector"); } /// <summary> /// Helper method for the various ways of retrieving a user account /// </summary> /// <param name="requestArgs">Service query parameters</param> /// <returns>A UserAccount object on success, null on failure</returns> private UserAccount GetUser(NameValueCollection requestArgs) { string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)"; // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue); OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap user = response["User"] as OSDMap; if (user != null) return ResponseToUserAccount(user); else m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format"); } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue); } return null; } /// <summary> /// Convert a User object in LLSD format to a UserAccount /// </summary> /// <param name="response">LLSD containing user account data</param> /// <returns>A UserAccount object on success, null on failure</returns> private UserAccount ResponseToUserAccount(OSDMap response) { if (response == null) return null; UserAccount account = new UserAccount(); account.PrincipalID = response["UserID"].AsUUID(); account.Created = response["CreationDate"].AsInteger(); account.Email = response["Email"].AsString(); account.ServiceURLs = new Dictionary<string, object>(0); account.UserFlags = response["UserFlags"].AsInteger(); account.UserLevel = response["AccessLevel"].AsInteger(); account.UserTitle = response["UserTitle"].AsString(); account.LocalToGrid = true; if (response.ContainsKey("LocalToGrid")) account.LocalToGrid = (response["LocalToGrid"].AsString() == "true" ? true : false); GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName); // Cache the user account info m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS); return account; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.ComponentModel; namespace DSL.POS.Report.Setup { public class ReportSetupInfo { //Methord For Branch Information public DataSet getBranchInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptBranchInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "BranchInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Member Information public DataSet getMemberInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptAllMemberInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "MemberInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Supplier Information public DataSet getSupplierInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptSupplierInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "SupplierInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Product Information public DataSet getProductInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptAllProductInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "AllProductInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Product Category Information public DataSet getProductCategoryInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptProductCategoryInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "ProductCategoryInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Product Sub Category Information public DataSet getProductSubCategoryInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptProductSubCategoryInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "ProductSubCategoryInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Product Unit Information public DataSet getProductUnitInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptProductUnitInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "ProductUnitInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } //Methord For Booth Information public DataSet getBoothInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptBoothInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "BoothInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } public DataSet getProductSummaryInfo(int ReportMode) { SqlConnection sc = new SqlConnection(); sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString(); SqlDataAdapter da = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand(); try { cmd.Connection = sc; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "RptProductSummaryInfo"; cmd.Parameters.Add(new SqlParameter("@ReportMode", SqlDbType.SmallInt, 2)); if (ReportMode == 0) { cmd.Parameters["@ReportMode"].Value = null; } else { cmd.Parameters["@ReportMode"].Value = ReportMode; } da.SelectCommand = cmd; sc.Open(); DataSet ds = new DataSet(); da.Fill(ds, "ProductSummaryInfo"); return ds; } catch (Exception exp) { throw exp; } finally { sc.Close(); } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ // #define SHOW_DK2_VARIABLES // Use the Unity new GUI with Unity 4.6 or above. #if UNITY_4_6 || UNITY_5_0 #define USE_NEW_GUI #endif using System; using System.Collections; using UnityEngine; #if USE_NEW_GUI using UnityEngine.UI; # endif //------------------------------------------------------------------------------------- // ***** OVRMainMenu // /// <summary> /// OVRMainMenu is used to control the loading of different scenes. It also renders out /// a menu that allows a user to modify various Rift settings, and allow for storing /// these settings for recall later. /// /// A user of this component can add as many scenes that they would like to be able to /// have access to. /// /// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience, /// but can safely removed from it and added to another GameObject that is used for general /// Unity logic. /// /// </summary> public class OVRMainMenu : MonoBehaviour { /// <summary> /// The amount of time in seconds that it takes for the menu to fade in. /// </summary> public float FadeInTime = 2.0f; /// <summary> /// An optional texture that appears before the menu fades in. /// </summary> public UnityEngine.Texture FadeInTexture = null; /// <summary> /// An optional font that replaces Unity's default Arial. /// </summary> public Font FontReplace = null; /// <summary> /// The key that toggles the menu. /// </summary> public KeyCode MenuKey = KeyCode.Space; /// <summary> /// The key that quits the application. /// </summary> public KeyCode QuitKey = KeyCode.Escape; /// <summary> /// Scene names to show on-screen for each of the scenes in Scenes. /// </summary> public string[] SceneNames; /// <summary> /// The set of scenes that the user can jump to. /// </summary> public string[] Scenes; private bool ScenesVisible = false; // Spacing for scenes menu private int StartX = 490; private int StartY = 250; private int WidthX = 300; private int WidthY = 23; // Spacing for variables that users can change private int VRVarsSX = 553; private int VRVarsSY = 250; private int VRVarsWidthX = 175; private int VRVarsWidthY = 23; private int StepY = 25; // Handle to OVRCameraRig private OVRCameraRig CameraController = null; // Handle to OVRPlayerController private OVRPlayerController PlayerController = null; // Controller buttons private bool PrevStartDown; private bool PrevHatDown; private bool PrevHatUp; private bool ShowVRVars; private bool OldSpaceHit; // FPS private float UpdateInterval = 0.5f; private float Accum = 0; private int Frames = 0; private float TimeLeft = 0; private string strFPS = "FPS: 0"; private string strIPD = "IPD: 0.000"; /// <summary> /// Prediction (in ms) /// </summary> public float PredictionIncrement = 0.001f; // 1 ms private string strPrediction = "Pred: OFF"; private string strFOV = "FOV: 0.0f"; private string strHeight = "Height: 0.0f"; /// <summary> /// Controls how quickly the player's speed and rotation change based on input. /// </summary> public float SpeedRotationIncrement = 0.05f; private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f"; private bool LoadingLevel = false; private float AlphaFadeValue = 1.0f; private int CurrentLevel = 0; // Rift detection private bool HMDPresent = false; private float RiftPresentTimeout = 0.0f; private string strRiftPresent = ""; // Replace the GUI with our own texture and 3D plane that // is attached to the rendder camera for true 3D placement private OVRGUI GuiHelper = new OVRGUI (); private GameObject GUIRenderObject = null; private RenderTexture GUIRenderTexture = null; // We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI // Enable the UsingNewGUI option in the editor, // if you want to use new GUI and Unity version is higher than 4.6 #if USE_NEW_GUI private GameObject NewGUIObject = null; private GameObject RiftPresentGUIObject = null; #endif /// <summary> /// We can set the layer to be anything we want to, this allows /// a specific camera to render it. /// </summary> public string LayerName = "Default"; /// <summary> /// Crosshair rendered onto 3D plane. /// </summary> public UnityEngine.Texture CrosshairImage = null; private OVRCrosshair Crosshair = new OVRCrosshair (); // Resolution Eye Texture private string strResolutionEyeTexture = "Resolution: 0 x 0"; // Latency values private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f"; // Vision mode on/off private bool VisionMode = true; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube GridCube = null; // We want to hold onto the VisionGuide so we can share // the menu RenderTarget OVRVisionGuide VisionGuide = null; #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake () { // Find camera controller OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig> (); if (CameraControllers.Length == 0) Debug.LogWarning ("OVRMainMenu: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning ("OVRMainMenu: More then 1 OVRCameraRig attached."); else { CameraController = CameraControllers [0]; #if USE_NEW_GUI OVRUGUI.CameraController = CameraController; #endif } // Find player controller OVRPlayerController[] PlayerControllers; PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController> (); if (PlayerControllers.Length == 0) Debug.LogWarning ("OVRMainMenu: No OVRPlayerController attached."); else if (PlayerControllers.Length > 1) Debug.LogWarning ("OVRMainMenu: More then 1 OVRPlayerController attached."); else { PlayerController = PlayerControllers [0]; #if USE_NEW_GUI OVRUGUI.PlayerController = PlayerController; #endif } #if USE_NEW_GUI // Create canvas for using new GUI NewGUIObject = new GameObject(); NewGUIObject.name = "OVRGUIMain"; NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = NewGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localScale = new Vector3(0.001f, 0.001f, 0.001f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; Canvas c = NewGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.WorldSpace; c.pixelPerfect = false; #endif } /// <summary> /// Start this instance. /// </summary> void Start () { AlphaFadeValue = 1.0f; CurrentLevel = 0; PrevStartDown = false; PrevHatDown = false; PrevHatUp = false; ShowVRVars = false; OldSpaceHit = false; strFPS = "FPS: 0"; LoadingLevel = false; ScenesVisible = false; // Set the GUI target GUIRenderObject = GameObject.Instantiate (Resources.Load ("OVRGUIObjectMain")) as GameObject; if (GUIRenderObject != null) { // Chnge the layer GUIRenderObject.layer = LayerMask.NameToLayer (LayerName); if (GUIRenderTexture == null) { int w = Screen.width; int h = Screen.height; // We don't need a depth buffer on this texture GUIRenderTexture = new RenderTexture (w, h, 0); GuiHelper.SetPixelResolution (w, h); // NOTE: All GUI elements are being written with pixel values based // from DK1 (1280x800). These should change to normalized locations so // that we can scale more cleanly with varying resolutions GuiHelper.SetDisplayResolution (1280.0f, 800.0f); } } // Attach GUI texture to GUI object and GUI object to Camera if (GUIRenderTexture != null && GUIRenderObject != null) { GUIRenderObject.GetComponent<Renderer> ().material.mainTexture = GUIRenderTexture; if (CameraController != null) { // Grab transform of GUI object Vector3 ls = GUIRenderObject.transform.localScale; Vector3 lp = GUIRenderObject.transform.localPosition; Quaternion lr = GUIRenderObject.transform.localRotation; // Attach the GUI object to the camera GUIRenderObject.transform.parent = CameraController.centerEyeAnchor; // Reset the transform values (we will be maintaining state of the GUI object // in local state) GUIRenderObject.transform.localScale = ls; GUIRenderObject.transform.localPosition = lp; GUIRenderObject.transform.localRotation = lr; // Deactivate object until we have completed the fade-in // Also, we may want to deactive the render object if there is nothing being rendered // into the UI GUIRenderObject.SetActive (false); } } // Make sure to hide cursor if (Application.isEditor == false) { #if UNITY_5_0 Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; #else Screen.showCursor = false; Screen.lockCursor = true; #endif } // CameraController updates if (CameraController != null) { // Add a GridCube component to this object GridCube = gameObject.AddComponent<OVRGridCube> (); GridCube.SetOVRCameraController (ref CameraController); // Add a VisionGuide component to this object VisionGuide = gameObject.AddComponent<OVRVisionGuide> (); VisionGuide.SetOVRCameraController (ref CameraController); VisionGuide.SetFadeTexture (ref FadeInTexture); VisionGuide.SetVisionGuideLayer (ref LayerName); } // Crosshair functionality Crosshair.Init (); Crosshair.SetCrosshairTexture (ref CrosshairImage); Crosshair.SetOVRCameraController (ref CameraController); Crosshair.SetOVRPlayerController (ref PlayerController); // Check for HMD and sensor CheckIfRiftPresent (); #if USE_NEW_GUI if (!string.IsNullOrEmpty(strRiftPresent)){ ShowRiftPresentGUI(); } #endif } /// <summary> /// Update this instance. /// </summary> void Update () { if (LoadingLevel == true) return; // Main update UpdateFPS (); // CameraController updates if (CameraController != null) { UpdateIPD (); UpdateRecenterPose (); UpdateVisionMode (); UpdateFOV (); UpdateEyeHeightOffset (); UpdateResolutionEyeTexture (); UpdateLatencyValues (); } // PlayerController updates if (PlayerController != null) { UpdateSpeedAndRotationScaleMultiplier (); UpdatePlayerControllerMovement (); } // MainMenu updates UpdateSelectCurrentLevel (); // Device updates UpdateDeviceDetection (); // Crosshair functionality Crosshair.UpdateCrosshair (); #if USE_NEW_GUI if (ShowVRVars && RiftPresentTimeout <= 0.0f) { NewGUIObject.SetActive(true); UpdateNewGUIVars(); OVRUGUI.UpdateGUI(); } else { NewGUIObject.SetActive(false); } #endif // Toggle Fullscreen if (Input.GetKeyDown (KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown (KeyCode.M)) OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode; // Escape Application if (Input.GetKeyDown (QuitKey)) Application.Quit (); } /// <summary> /// Updates Variables for new GUI. /// </summary> #if USE_NEW_GUI void UpdateNewGUIVars() { #if SHOW_DK2_VARIABLES // Print out Vision Mode OVRUGUI.strVisionMode = strVisionMode; #endif // Print out FPS OVRUGUI.strFPS = strFPS; // Don't draw these vars if CameraController is not present if (CameraController != null) { OVRUGUI.strPrediction = strPrediction; OVRUGUI.strIPD = strIPD; OVRUGUI.strFOV = strFOV; OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture; OVRUGUI.strLatencies = strLatencies; } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { OVRUGUI.strHeight = strHeight; OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler; } OVRUGUI.strRiftPresent = strRiftPresent; } #endif void OnGUI () { // Important to keep from skipping render events if (Event.current.type != EventType.Repaint) return; #if !USE_NEW_GUI // Fade in screen if (AlphaFadeValue > 0.0f) { AlphaFadeValue -= Mathf.Clamp01 (Time.deltaTime / FadeInTime); if (AlphaFadeValue < 0.0f) { AlphaFadeValue = 0.0f; } else { GUI.color = new Color (0, 0, 0, AlphaFadeValue); GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), FadeInTexture); return; } } #endif // We can turn on the render object so we can render the on-screen menu if (GUIRenderObject != null) { if (ScenesVisible || ShowVRVars || Crosshair.IsCrosshairVisible () || RiftPresentTimeout > 0.0f || VisionGuide.GetFadeAlphaValue () > 0.0f) { GUIRenderObject.SetActive (true); } else { GUIRenderObject.SetActive (false); } } //*** // Set the GUI matrix to deal with portrait mode Vector3 scale = Vector3.one; Matrix4x4 svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, scale); // Cache current active render texture RenderTexture previousActive = RenderTexture.active; // if set, we will render to this texture if (GUIRenderTexture != null && GUIRenderObject.activeSelf) { RenderTexture.active = GUIRenderTexture; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); } // Update OVRGUI functions (will be deprecated eventually when 2D renderingc // is removed from GUI) GuiHelper.SetFontReplace (FontReplace); // If true, we are displaying information about the Rift not being detected // So do not show anything else if (GUIShowRiftDetected () != true) { GUIShowLevels (); GUIShowVRVariables (); } // The cross-hair may need to go away at some point, unless someone finds it // useful Crosshair.OnGUICrosshair (); // Since we want to draw into the main GUI that is shared within the MainMenu, // we call the OVRVisionGuide GUI function here VisionGuide.OnGUIVisionGuide (); // Restore active render texture if (GUIRenderObject.activeSelf) { RenderTexture.active = previousActive; } // *** // Restore previous GUI matrix GUI.matrix = svMat; } #endregion #region Internal State Management Functions /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS () { TimeLeft -= Time.deltaTime; Accum += Time.timeScale / Time.deltaTime; ++Frames; // Interval ended - update GUI text and start new interval if (TimeLeft <= 0.0) { // display two fractional digits (f2 format) float fps = Accum / Frames; if (ShowVRVars == true)// limit gc strFPS = System.String.Format ("FPS: {0:F2}", fps); TimeLeft += UpdateInterval; Accum = 0.0f; Frames = 0; } } /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD () { if (ShowVRVars == true) { // limit gc strIPD = System.String.Format ("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } } void UpdateRecenterPose () { if (Input.GetKeyDown (KeyCode.R)) { OVRManager.display.RecenterPose (); } } /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode () { if (Input.GetKeyDown (KeyCode.F2)) { VisionMode = !VisionMode; OVRManager.tracker.isEnabled = VisionMode; #if SHOW_DK2_VARIABLES strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF"; #endif } } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV () { if (ShowVRVars == true) {// limit gc OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc (OVREye.Left); strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y); } } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture () { if (ShowVRVars == true) { // limit gc OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc (OVREye.Left); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc (OVREye.Right); float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max (leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format ("Resolution : {0} x {1}", w, h); } } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues () { #if !UNITY_ANDROID || UNITY_EDITOR if (ShowVRVars == true) { // limit gc OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format ("Ren : N/A TWrp: N/A PostPresent: N/A"); else strLatencies = System.String.Format ("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}", latency.render, latency.timeWarp, latency.postPresent); } #endif } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset () { if (ShowVRVars == true) {// limit gc float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight); } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier () { float moveScaleMultiplier = 0.0f; PlayerController.GetMoveScaleMultiplier (ref moveScaleMultiplier); if (Input.GetKeyDown (KeyCode.Alpha7)) moveScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown (KeyCode.Alpha8)) moveScaleMultiplier += SpeedRotationIncrement; PlayerController.SetMoveScaleMultiplier (moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; PlayerController.GetRotationScaleMultiplier (ref rotationScaleMultiplier); if (Input.GetKeyDown (KeyCode.Alpha9)) rotationScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown (KeyCode.Alpha0)) rotationScaleMultiplier += SpeedRotationIncrement; PlayerController.SetRotationScaleMultiplier (rotationScaleMultiplier); if (ShowVRVars == true)// limit gc strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}", moveScaleMultiplier, rotationScaleMultiplier); } /// <summary> /// Updates the player controller movement. /// </summary> void UpdatePlayerControllerMovement () { if (PlayerController != null) PlayerController.SetHaltUpdateMovement (ScenesVisible); } /// <summary> /// Updates the select current level. /// </summary> void UpdateSelectCurrentLevel () { ShowLevels (); if (!ScenesVisible) return; CurrentLevel = GetCurrentLevel (); if (Scenes.Length != 0 && (OVRGamepadController.GPC_GetButton (OVRGamepadController.Button.A) || Input.GetKeyDown (KeyCode.Return))) { LoadingLevel = true; Application.LoadLevelAsync (Scenes [CurrentLevel]); } } /// <summary> /// Shows the levels. /// </summary> /// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns> bool ShowLevels () { if (Scenes.Length == 0) { ScenesVisible = false; return ScenesVisible; } bool curStartDown = OVRGamepadController.GPC_GetButton (OVRGamepadController.Button.Start); bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown (KeyCode.RightShift); PrevStartDown = curStartDown; if (startPressed) { ScenesVisible = !ScenesVisible; } return ScenesVisible; } /// <summary> /// Gets the current level. /// </summary> /// <returns>The current level.</returns> int GetCurrentLevel () { bool curHatDown = false; if (OVRGamepadController.GPC_GetButton (OVRGamepadController.Button.Down) == true) curHatDown = true; bool curHatUp = false; if (OVRGamepadController.GPC_GetButton (OVRGamepadController.Button.Down) == true) curHatUp = true; if ((PrevHatDown == false) && (curHatDown == true) || Input.GetKeyDown (KeyCode.DownArrow)) { CurrentLevel = (CurrentLevel + 1) % SceneNames.Length; } else if ((PrevHatUp == false) && (curHatUp == true) || Input.GetKeyDown (KeyCode.UpArrow)) { CurrentLevel--; if (CurrentLevel < 0) CurrentLevel = SceneNames.Length - 1; } PrevHatDown = curHatDown; PrevHatUp = curHatUp; return CurrentLevel; } #endregion #region Internal GUI Functions /// <summary> /// Show the GUI levels. /// </summary> void GUIShowLevels () { if (ScenesVisible == true) { // Darken the background by rendering fade texture GUI.color = new Color (0, 0, 0, 0.5f); GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), FadeInTexture); GUI.color = Color.white; if (LoadingLevel == true) { string loading = "LOADING..."; GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow); return; } for (int i = 0; i < SceneNames.Length; i++) { Color c; if (i == CurrentLevel) c = Color.yellow; else c = Color.black; int y = StartY + (i * StepY); GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames [i], c); } } } /// <summary> /// Show the VR variables. /// </summary> void GUIShowVRVariables () { bool SpaceHit = Input.GetKey (MenuKey); if ((OldSpaceHit == false) && (SpaceHit == true)) { if (ShowVRVars == true) { ShowVRVars = false; } else { ShowVRVars = true; #if USE_NEW_GUI OVRUGUI.InitUIComponent = ShowVRVars; #endif } } OldSpaceHit = SpaceHit; // Do not render if we are not showing if (ShowVRVars == false) return; #if !USE_NEW_GUI int y = VRVarsSY; #if SHOW_DK2_VARIABLES // Print out Vision Mode GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strVisionMode, Color.green); #endif // Draw FPS GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFPS, Color.green); // Don't draw these vars if CameraController is not present if (CameraController != null) { GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strPrediction, Color.white); GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strIPD, Color.yellow); GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFOV, Color.white); GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strResolutionEyeTexture, Color.white); GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strLatencies, Color.white); } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strHeight, Color.yellow); GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strSpeedRotationMultipler, Color.white); } #endif } // RIFT DETECTION /// <summary> /// Checks to see if HMD and / or sensor is available, and displays a /// message if it is not. /// </summary> void CheckIfRiftPresent () { HMDPresent = OVRManager.display.isPresent; if (!HMDPresent) { RiftPresentTimeout = 15.0f; if (!HMDPresent) strRiftPresent = "NO HMD DETECTED"; #if USE_NEW_GUI OVRUGUI.strRiftPresent = strRiftPresent; #endif } } /// <summary> /// Show if Rift is detected. /// </summary> /// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns> bool GUIShowRiftDetected () { #if !USE_NEW_GUI if (RiftPresentTimeout > 0.0f) { GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref strRiftPresent, Color.white); return true; } #else if(RiftPresentTimeout < 0.0f) DestroyImmediate(RiftPresentGUIObject); #endif return false; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection () { if (RiftPresentTimeout > 0.0f) RiftPresentTimeout -= Time.deltaTime; } /// <summary> /// Show rift present GUI with new GUI /// </summary> void ShowRiftPresentGUI () { #if USE_NEW_GUI RiftPresentGUIObject = new GameObject(); RiftPresentGUIObject.name = "RiftPresentGUIMain"; RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; r.localScale = new Vector3(0.001f, 0.001f, 0.001f); Canvas c = RiftPresentGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.WorldSpace; c.pixelPerfect = false; OVRUGUI.RiftPresentGUI(RiftPresentGUIObject); #endif } #endregion }
namespace ZetaResourceEditor.RuntimeBusinessLogic.Translation.Bing { using FileGroups; using Properties; using Runtime; using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; using System.Web.Services.Protocols; using System.Xml; using Zeta.VoyagerLibrary.Logging; public class BingSoapTranslationEngine : ITranslationEngine { // http://msdn.microsoft.com/en-us/library/hh454950.aspx // Client ID: ZetaResourceEditor // Client secret: ==> See external text file. //private SoapService _ws; private TranslationLanguageInfo[] _names; //private SoapService createWebService() //{ // if (_ws == null) // { // _ws = new SoapService(); // WebServiceManager.Current.ApplyProxy(_ws); // } // return _ws; //} public bool Has2AppIDs => true; public string AppID1Name => Resources.BingSoapTranslationEngine_AppID1Name_Client_ID; public string AppID2Name => Resources.BingSoapTranslationEngine_AppID2Name_Client_secret; public bool IsUserSelectable => true; public bool IsDefault => false; public string UniqueInternalName => @"b5c87f9c-e3cd-4963-a3a2-559d3e69e961"; public string UserReadableName => Resources.BingSoapTranslationEngine_UserReadableName_Microsoft_Translator__Bing_; public TranslationLanguageInfo[] GetSourceLanguages(string appID, string appID2) { if (_names == null) { try { protectWSCall( delegate { var at = BingTranslationHelper.GetAccessToken(appID, appID2); var names = BingTranslationHelper.GetLanguagesForTranslate(at); var result = new List<TranslationLanguageInfo>(); // ReSharper disable LoopCanBeConvertedToQuery foreach (var iso6391Code in names) // ReSharper restore LoopCanBeConvertedToQuery { var ci = IntelligentGetCultureInfo(iso6391Code); if (ci != null) { result.Add( new TranslationLanguageInfo { LanguageCode = iso6391Code, UserReadableName = ci.DisplayName, }); } } _names = result.ToArray(); }); } catch (WebException x) { LogCentral.Current.LogError(@"Error while getting source languages. Ignoring.", x); return new TranslationLanguageInfo[] { }; } } return _names; } public TranslationLanguageInfo[] GetDestinationLanguages(string appID, string appID2) { return GetSourceLanguages(appID, appID2); } internal static CultureInfo IntelligentGetCultureInfo(string iso6391Code) { // ReSharper disable LoopCanBeConvertedToQuery foreach (var cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures)) // ReSharper restore LoopCanBeConvertedToQuery { if (string.Compare(iso6391Code, cultureInfo.TwoLetterISOLanguageName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(iso6391Code, cultureInfo.Name, StringComparison.OrdinalIgnoreCase) == 0) { return cultureInfo; } } return null; } private delegate void ActionToProtect(); public bool SupportsArrayTranslation => true; public int MaxArraySize => 25; public string AppIDLink => @"https://zeta.li/zre-translation-appid-bing"; public string[] TranslateArray( string appID, string appID2, string[] texts, string sourceLanguageCode, string destinationLanguageCode, string[] wordsToProtect, string[] wordsToRemove) { if (texts == null || texts.Length <= 0) { return texts; } else { var result = new List<string>(); protectWSCall( delegate { var at = BingTranslationHelper.GetAccessToken(appID, appID2); var raw = BingTranslationHelper.TranslateArray( at, sourceLanguageCode, destinationLanguageCode, TranslationHelper.ProtectWords( TranslationHelper.RemoveWords( texts, wordsToRemove), wordsToProtect)); foreach (var response in raw) { if (StringExtensionMethods.IsNullOrWhiteSpace(response.Error)) { result.Add(TranslationHelper.UnprotectWords(response.Translation, wordsToProtect)); } else { result.Add(FileGroup.DefaultTranslationErrorPrefix + @" " + response.Error); } } }); return result.ToArray(); } } public bool IsSourceLanguageSupported(string appID, string appID2, string languageCode) { return TranslationHelper.IsSupportedLanguage(languageCode, GetSourceLanguages(appID, appID2)); } public bool IsDestinationLanguageSupported(string appID, string appID2, string languageCode) { return TranslationHelper.IsSupportedLanguage(languageCode, GetDestinationLanguages(appID, appID2)); } public string Translate( string appID, string appID2, string text, string sourceLanguageCode, string destinationLanguageCode, string[] wordsToProtect, string[] wordsToRemove) { if (StringExtensionMethods.IsNullOrWhiteSpace(text)) { return text; } else { var result = string.Empty; protectWSCall( delegate { var at = BingTranslationHelper.GetAccessToken(appID, appID2); result = TranslationHelper.UnprotectWords( BingTranslationHelper.Translate( at, sourceLanguageCode, destinationLanguageCode, TranslationHelper.ProtectWords( TranslationHelper.RemoveWords( text, wordsToRemove), wordsToProtect)).Translation, wordsToProtect); }); return result; } } private static void protectWSCall(ActionToProtect action) { // http://msdn.microsoft.com/en-us/library/dd877917.aspx try { action(); } catch (SoapException ex) { var msg = displayErrors(ex, ex.Detail); throw new Exception(msg, ex); } } private static string displayErrors(Exception x, XmlNode errorDetails) { var sb = new StringBuilder(); sb.Append(x.Message); sb.Append(@" "); if (errorDetails?.OwnerDocument != null) { // Add the default namespace to the namespace manager. var nsmgr = new XmlNamespaceManager( errorDetails.OwnerDocument.NameTable); nsmgr.AddNamespace( @"api", @"http://schemas.microsoft.com/LiveSearch/2008/03/Search"); var errors = errorDetails.SelectNodes( @"./api:Errors/api:Error", nsmgr); if (errors != null) { // Iterate over the list of errors and display error details. foreach (XmlNode error in errors) { foreach (XmlNode detail in error.ChildNodes) { sb.Append(detail.Name + @": " + detail.InnerText); sb.Append(@" "); } } } } return sb.ToString().Trim(); } public string MapCultureToSourceLanguageCode(string appID, string appID2, CultureInfo cultureInfo) { return TranslationHelper.DoMapCultureToLanguageCode(GetSourceLanguages(appID, appID2), cultureInfo); } public string MapCultureToDestinationLanguageCode(string appID, string appID2, CultureInfo cultureInfo) { return TranslationHelper.DoMapCultureToLanguageCode(GetDestinationLanguages(appID, appID2), cultureInfo); } public bool AreAppIDsSyntacticallyValid(string appID, string appID2) { return !string.IsNullOrEmpty(appID) && !string.IsNullOrEmpty(appID2); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using Autodesk.Revit; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Mechanical; using GXYZ = Autodesk.Revit.DB.XYZ ; namespace Revit.SDK.Samples.AutoRoute.CS { /// <summary> /// route a set of ducts and fittings between a base air supply equipment and 2 terminals. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class Command : IExternalCommand { /// <summary> /// The revit application /// </summary> private static Application m_application; /// <summary> /// The current document of the application /// </summary> private static Document m_document; /// <summary> /// The mechanical system that will be created /// </summary> private MechanicalSystem m_mechanicalSystem; /// <summary> /// The type of the ducts in the system /// </summary> DuctType dtRectangle; /// <summary> /// Minimum length of a fitting /// </summary> private const double min1FittingLength = 1; /// <summary> /// Minimum length of a duct /// </summary> private const double minDuctLength = 0.5; /// <summary> /// The vertical offset of the highest connector to the trunk ducts /// </summary> private const double verticalTrunkOffset = 15; /// <summary> /// Optional distance from trunk to the boundary of system bounding box /// used when failed to lay out ducts in the region of bounding box /// </summary> private const double horizontalOptionalTrunkOffset = 5; /// <summary> /// Minimum length of 2 fittings /// </summary> private const double min2FittingsLength = min1FittingLength * 2; /// <summary> /// The minimum length of 1 duct with 2 fittings /// </summary> private const double min1Duct2FittingsLength = min1FittingLength * 2 + minDuctLength; #region IExternalCommand Members /// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // set out default result to Failed. Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed; m_application = commandData.Application.Application; m_document = commandData.Application.ActiveUIDocument.Document; Trace.Listeners.Clear(); Trace.AutoFlush = true; string outputFileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "AutoRoute.log"); if (File.Exists(outputFileName)) { File.Delete(outputFileName); } TextWriterTraceListener listener = new TextWriterTraceListener(outputFileName); Trace.Listeners.Add(listener); Transaction transaction = new Transaction(m_document, "Sample_AutoRoute"); try { transaction.Start(); //Lists to temporarily record the created elements List<Duct> ducts = new List<Duct>(); List<GXYZ> points = new List<GXYZ>(); List<Connector> connectors = new List<Connector>(); List<Connector> baseConnectors = new List<Connector>(); //Get the connectors and bounding boxes List<Autodesk.Revit.DB.ElementId> ids = new List<ElementId>(); ids.Add(new ElementId(378728)); ids.Add(new ElementId(378707)); ids.Add(new ElementId(378716)); FamilyInstance[] instances = new FamilyInstance[3]; Autodesk.Revit.DB.BoundingBoxXYZ[] boxes = new Autodesk.Revit.DB.BoundingBoxXYZ[3]; Connector[] conns = new Connector[3]; ConnectorSetIterator csi = null; for (int i = 0; i < ids.Count; ++i) { Element element = m_document.get_Element(ids[i]); if (null == element) { message = "Element " + ids[i].IntegerValue + " can't be found."; return Autodesk.Revit.UI.Result.Failed; } instances[i] = element as FamilyInstance; csi = ConnectorInfo.GetConnectors(ids[i].IntegerValue).ForwardIterator(); csi.MoveNext(); conns[i] = csi.Current as Connector; boxes[i] = instances[i].get_BoundingBox(m_document.ActiveView); } //Find the "Out" and "SupplyAir" connector on the base equipment csi = ConnectorInfo.GetConnectors(ids[0].IntegerValue).ForwardIterator(); while (csi.MoveNext()) { Connector conn = csi.Current as Connector; if (conn.Direction == FlowDirectionType.Out && conn.DuctSystemType == DuctSystemType.SupplyAir) { conns[0] = conn; } } //Create a mechanical system with a base air supply equipment and 2 terminals. m_mechanicalSystem = CreateMechanicalSystem( //[378728][SupplyAir][Out][RectProfile][OST_MechanicalEquipment] new ConnectorInfo(378728, conns[0].Origin.X, conns[0].Origin.Y, conns[0].Origin.Z), new ConnectorInfo[]{ //[378707][SupplyAir][In][RectProfile] new ConnectorInfo(378707, conns[1].Origin.X, conns[1].Origin.Y, conns[1].Origin.Z), //[378716][SupplyAir][In][RectProfile] new ConnectorInfo(378716, conns[2].Origin.X, conns[2].Origin.Y, conns[2].Origin.Z) }, DuctSystemType.SupplyAir ); //Get the boundary of the system double minX = conns[0].Origin.X; double minY = conns[0].Origin.Y; double maxX = conns[0].Origin.X; double maxY = conns[0].Origin.Y; double maxZ = conns[0].Origin.Z; for (int i = 1; i < boxes.Length; ++i) { if (conns[i].Origin.X < minX) minX = conns[i].Origin.X; if (conns[i].Origin.Y < minY) minY = conns[i].Origin.Y; if (conns[i].Origin.X > maxX) maxX = conns[i].Origin.X; if (conns[i].Origin.Y > maxY) maxY = conns[i].Origin.Y; if (conns[i].Origin.Z > maxZ) maxZ = conns[i].Origin.Z; } //Calculate the optional values for the trunk ducts double midX = (minX + maxX) / 2; double midY = (minY + maxY) / 2; double[] baseXValues = new double[3] { midX, (minX + midX) / 2, (maxX + midX) / 2 }; double[] baseYValues = new double[3] { midY, (minY + midY) / 2, (maxY + midY) / 2 }; //Get the duct type for the ducts to be created Autodesk.Revit.DB.ElementId ductTypeId = new Autodesk.Revit.DB.ElementId(139191); dtRectangle = m_document.get_Element(ductTypeId) as DuctType; //Create the ducts and elbows that connect the base mechanical equipment GXYZ connectorDirection = conns[0].CoordinateSystem.BasisZ; if (0 == connectorDirection.DistanceTo(new GXYZ(-1, 0, 0))) { points.Add(new GXYZ(conns[0].Origin.X - min1FittingLength, conns[0].Origin.Y, conns[0].Origin.Z)); points.Add(new GXYZ(conns[0].Origin.X - min2FittingsLength, conns[0].Origin.Y, conns[0].Origin.Z + min1FittingLength)); points.Add(new GXYZ(conns[0].Origin.X - min2FittingsLength, conns[0].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new GXYZ(1, 0, 0))) { points.Add(new GXYZ(conns[0].Origin.X + min1FittingLength, conns[0].Origin.Y, conns[0].Origin.Z)); points.Add(new GXYZ(conns[0].Origin.X + min2FittingsLength, conns[0].Origin.Y, conns[0].Origin.Z + min1FittingLength)); points.Add(new GXYZ(conns[0].Origin.X + min2FittingsLength, conns[0].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new GXYZ(0, -1, 0))) { points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y - min1FittingLength, conns[0].Origin.Z)); points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y - min2FittingsLength, conns[0].Origin.Z + min1FittingLength)); points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y - min2FittingsLength, maxZ + verticalTrunkOffset - min1FittingLength)); } else if (0 == connectorDirection.DistanceTo(new GXYZ(0, 1, 0))) { points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y + min1FittingLength, conns[0].Origin.Z)); points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y + min2FittingsLength, conns[0].Origin.Z + min1FittingLength)); points.Add(new GXYZ(conns[0].Origin.X, conns[0].Origin.Y + min2FittingsLength, maxZ + verticalTrunkOffset - min1FittingLength)); } ducts.Add(m_document.Create.NewDuct(points[0], conns[0], dtRectangle)); ducts.Add(m_document.Create.NewDuct(points[1], points[2], dtRectangle)); connectors.Add(ConnectorInfo.GetConnector(ducts[0].Id.IntegerValue, points[0])); connectors.Add(ConnectorInfo.GetConnector(ducts[1].Id.IntegerValue, points[1])); connectors.Add(ConnectorInfo.GetConnector(ducts[1].Id.IntegerValue, points[2])); connectors[0].ConnectTo(connectors[1]); m_document.Create.NewElbowFitting(connectors[0], connectors[1]); baseConnectors.Add(connectors[2]); //Create the vertical ducts for terminals points.Clear(); ducts.Clear(); points.Add(new GXYZ(conns[1].Origin.X, conns[1].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); points.Add(new GXYZ(conns[2].Origin.X, conns[2].Origin.Y, maxZ + verticalTrunkOffset - min1FittingLength)); ducts.Add(m_document.Create.NewDuct(points[0], conns[1], dtRectangle)); ducts.Add(m_document.Create.NewDuct(points[1], conns[2], dtRectangle)); baseConnectors.Add(ConnectorInfo.GetConnector(ducts[0].Id.IntegerValue, points[0])); baseConnectors.Add(ConnectorInfo.GetConnector(ducts[1].Id.IntegerValue, points[1])); //Connect the system by creating the trunk line of ducts and connect them to the base connectors SortConnectorsByX(baseConnectors); for (int i = 0; i < baseYValues.Length; ++i) { if (ConnectSystemOnXAxis(baseConnectors, baseYValues[i])) { LogUtility.WriteMechanicalSystem(m_mechanicalSystem); return Autodesk.Revit.UI.Result.Succeeded; } } SortConnectorsByY(baseConnectors); for (int i = 0; i < baseXValues.Length; ++i) { if (ConnectSystemOnYAxis(baseConnectors, baseXValues[i])) { LogUtility.WriteMechanicalSystem(m_mechanicalSystem); return Autodesk.Revit.UI.Result.Succeeded; } } //If all the cases fail to route the system, try the trunks out of the bounding box SortConnectorsByX(baseConnectors); if (ConnectSystemOnXAxis(baseConnectors, maxY + horizontalOptionalTrunkOffset)) { LogUtility.WriteMechanicalSystem(m_mechanicalSystem); return Autodesk.Revit.UI.Result.Succeeded; } SortConnectorsByY(baseConnectors); if (ConnectSystemOnYAxis(baseConnectors, maxX + horizontalOptionalTrunkOffset)) { LogUtility.WriteMechanicalSystem(m_mechanicalSystem); return Autodesk.Revit.UI.Result.Succeeded; } //If there's no path for the connection, choose one path and let Revit report the error connectors.Clear(); SortConnectorsByX(baseConnectors); connectors.AddRange(CreateDuct(new GXYZ(baseConnectors[0].Origin.X + min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset), new GXYZ(baseConnectors[1].Origin.X - min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset))); connectors.AddRange(CreateDuct(new GXYZ(baseConnectors[1].Origin.X + min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset), new GXYZ(baseConnectors[2].Origin.X - min1FittingLength, baseYValues[0], maxZ + verticalTrunkOffset))); ConnectWithElbowFittingOnXAxis(baseConnectors[0], connectors[0]); ConnectWithElbowFittingOnXAxis(baseConnectors[2], connectors[3]); ConnectWithTeeFittingOnXAxis(baseConnectors[1], connectors[1], connectors[2], false); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); message = ex.Message; retRes = Autodesk.Revit.UI.Result.Failed; } finally { transaction.Commit(); Trace.Flush(); listener.Close(); Trace.Close(); Trace.Listeners.Remove(listener); } return retRes; } #endregion /// <summary> /// Connect the system with a trunk line of ducts on X axis /// </summary> /// <param name="baseConnectors">the upper connectors of the vertical ducts that derived from the terminals and the base equipment</param> /// <param name="baseY">the y value of the trunk line</param> /// <returns> /// true if the system can be connected /// false if the system cannot be connected /// </returns> private bool ConnectSystemOnXAxis(List<Connector> baseConnectors, double baseY) { //Check the count of the base connectors if (null == baseConnectors || 3 != baseConnectors.Count) { return false; } for (int i = 0; i < baseConnectors.Count; ++i) { //Check the distance of the connector from the trunk if (baseConnectors[i].Origin.Y != baseY && Math.Abs(baseConnectors[i].Origin.Y - baseY) < min1Duct2FittingsLength) { return false; } //Check the distance of the connectors on X axis for (int j = i + 1; j < baseConnectors.Count; ++j) { if (baseConnectors[j].Origin.X != baseConnectors[i].Origin.X && baseConnectors[j].Origin.X - baseConnectors[i].Origin.X < min2FittingsLength) { return false; } } } try { double baseZ = baseConnectors[0].Origin.Z + min1FittingLength; //Create the ducts and elbow fittings to connect the vertical ducts and the trunk ducts List<Connector> connectors = new List<Connector>(); if (baseConnectors[0].Origin.X == baseConnectors[1].Origin.X) { //All 3 connectors are with the same X value if (baseConnectors[1].Origin.X == baseConnectors[2].Origin.X) { return false; } else { //The 1st and 2nd base connectors are on the same side of the trunk if (Math.Sign(baseConnectors[0].Origin.Y - baseY) * Math.Sign(baseConnectors[1].Origin.Y - baseY) == 1) { return false; } //Create the trunk connectors = CreateDuct(new GXYZ(baseConnectors[0].Origin.X + min1FittingLength, baseY, baseZ), new GXYZ(baseConnectors[2].Origin.X - min1FittingLength, baseY, baseZ)); //Create a tee fitting connecting the 1st and 2nd base connectors to the trunk ConnectWithTeeFittingOnXAxis(baseConnectors[0], baseConnectors[1], connectors[0], true); //Create an elbow fitting connection the 3rd base connector to the trunk ConnectWithElbowFittingOnXAxis(baseConnectors[2], connectors[1]); } } else { //Create the segment of duct on the trunk to be connected to the 1st base connector connectors = CreateDuct(new GXYZ(baseConnectors[0].Origin.X + min1FittingLength, baseY, baseZ), new GXYZ(baseConnectors[1].Origin.X - min1FittingLength, baseY, baseZ)); //Create an elbow fitting connection the 1st base connector with the trunk ConnectWithElbowFittingOnXAxis(baseConnectors[0], connectors[0]); if (baseConnectors[1].Origin.X == baseConnectors[2].Origin.X) { //The 2nd and 3rd connectors are on the same side of the trunk if (Math.Sign(baseConnectors[1].Origin.Y - baseY) * Math.Sign(baseConnectors[2].Origin.Y - baseY) == 1) { return false; } //Create a tee fitting connecting the 2nd and 3rd base connectors to the trunk ConnectWithTeeFittingOnXAxis(baseConnectors[1], baseConnectors[2], connectors[1], true); } else { connectors.AddRange(CreateDuct(new GXYZ(baseConnectors[1].Origin.X + min1FittingLength, baseY, baseZ), new GXYZ(baseConnectors[2].Origin.X - min1FittingLength, baseY, baseZ))); //Create a tee fitting connecting the 2nd base connector to the trunk ConnectWithTeeFittingOnXAxis(baseConnectors[1], connectors[1], connectors[2], false); //Create an elbow fitting connection the 3rd base connector to the trunk ConnectWithElbowFittingOnXAxis(baseConnectors[2], connectors[3]); } } return true; } catch { return false; } } /// <summary> /// Connect a base connector to a connector on the trunk with an elbow fitting /// </summary> /// <param name="baseConn">the upper connector of the vertical duct that derived from a terminal or the base equipment</param> /// <param name="conn">the connector of a duct on the trunk</param> private void ConnectWithElbowFittingOnXAxis(Connector baseConn, Connector conn) { double baseY = conn.Origin.Y; double baseZ = conn.Origin.Z; List<Connector> connectors = new List<Connector>(); //If the distance of the two connectors on the Y axis is greater than 2, create a duct on the Y axis and then connect it to the 2 connectors with elbow fittings if (Math.Abs(baseConn.Origin.Y - baseY) > min1Duct2FittingsLength) { connectors.AddRange(CreateDuct(new GXYZ(baseConn.Origin.X, baseConn.Origin.Y - Math.Sign(baseConn.Origin.Y - baseY), baseZ), new GXYZ(baseConn.Origin.X, baseY + Math.Sign(baseConn.Origin.Y - baseY), baseZ))); connectors[0].ConnectTo(baseConn); m_document.Create.NewElbowFitting(connectors[0], baseConn); connectors[1].ConnectTo(conn); m_document.Create.NewElbowFitting(connectors[1], conn); } //If the distance of the two connectors on the Y axis is less than 2, connect them with an elbow fitting else { baseConn.ConnectTo(conn); m_document.Create.NewElbowFitting(baseConn, conn); } } /// <summary> /// Connect 3 connectors on the trunk with a tee fitting /// </summary> /// <param name="conn1">the first connector</param> /// <param name="conn2">the second connector</param> /// <param name="conn3">the third connector</param> /// <param name="flag">a flag to indicate whether there are 2 base connectors or 1 base connector</param> private void ConnectWithTeeFittingOnXAxis(Connector conn1, Connector conn2, Connector conn3, bool flag) { double baseY = conn3.Origin.Y; double baseZ = conn3.Origin.Z; List<GXYZ> points = new List<GXYZ>(); List<Duct> ducts = new List<Duct>(); List<Connector> connectors = new List<Connector>(); //Connect two base connectors to a connector on the trunk if (true == flag) { Connector baseConn1 = conn1; Connector baseConn2 = conn2; Connector conn = conn3; connectors.AddRange(CreateDuct(new GXYZ(baseConn1.Origin.X, baseConn1.Origin.Y - Math.Sign(baseConn1.Origin.Y - baseY), baseZ), new GXYZ(baseConn1.Origin.X, baseY + Math.Sign(baseConn1.Origin.Y - baseY), baseZ))); connectors.AddRange(CreateDuct(new GXYZ(baseConn2.Origin.X, baseConn2.Origin.Y - Math.Sign(baseConn2.Origin.Y - baseY), baseZ), new GXYZ(baseConn2.Origin.X, baseY + Math.Sign(baseConn2.Origin.Y - baseY), baseZ))); connectors[0].ConnectTo(baseConn1); connectors[2].ConnectTo(baseConn2); m_document.Create.NewElbowFitting(connectors[0], baseConn1); m_document.Create.NewElbowFitting(connectors[2], baseConn2); connectors[1].ConnectTo(connectors[3]); connectors[1].ConnectTo(conn); connectors[3].ConnectTo(conn); m_document.Create.NewTeeFitting(connectors[1], connectors[3], conn); } //Connect a base connector to two connectors on the trunk else { Connector baseConn = conn1; if (Math.Abs(baseConn.Origin.Y - baseY) > min1Duct2FittingsLength) { connectors.AddRange(CreateDuct(new GXYZ(baseConn.Origin.X, baseConn.Origin.Y - Math.Sign(baseConn.Origin.Y - baseY), baseZ), new GXYZ(baseConn.Origin.X, baseY + Math.Sign(baseConn.Origin.Y - baseY), baseZ))); baseConn.ConnectTo(connectors[0]); m_document.Create.NewElbowFitting(connectors[0], baseConn); connectors[1].ConnectTo(conn2); connectors[1].ConnectTo(conn3); conn2.ConnectTo(conn3); m_document.Create.NewTeeFitting(conn2, conn3, connectors[1]); } else { baseConn.ConnectTo(conn2); baseConn.ConnectTo(conn3); conn2.ConnectTo(conn3); m_document.Create.NewTeeFitting(conn2, conn3, baseConn); } } } /// <summary> /// Sort the base connectors by their x values /// </summary> /// <param name="connectors">the connectors to be sorted</param> private void SortConnectorsByX(List<Connector> connectors) { for (int i = 0; i < connectors.Count; ++i) { double min = connectors[i].Origin.X; int minIndex = i; for (int j = i; j < connectors.Count; ++j) { if (connectors[j].Origin.X < min) { min = connectors[j].Origin.X; minIndex = j; } } Connector t = connectors[i]; connectors[i] = connectors[minIndex]; connectors[minIndex] = t; } } /// <summary> /// Connect the system with a trunk line of ducts on Y axis /// </summary> /// <param name="baseConnectors">the upper connectors of the vertical ducts that derived from the terminals and the base equipment</param> /// <param name="baseX">the x value of the trunk line</param> /// <returns> /// true if the system can be connected /// false if the system cannot be connected /// </returns> private bool ConnectSystemOnYAxis(List<Connector> baseConnectors, double baseX) { //Check the count of the base connectors if (null == baseConnectors || 3 != baseConnectors.Count) { return false; } for (int i = 0; i < baseConnectors.Count; ++i) { //Check the distance of the connector from the trunk if (baseConnectors[i].Origin.X != baseX && Math.Abs(baseConnectors[i].Origin.X - baseX) < min1Duct2FittingsLength) { return false; } //Check the distance of the connectors on Y axis for (int j = i + 1; j < baseConnectors.Count; ++j) { if (baseConnectors[j].Origin.Y != baseConnectors[i].Origin.Y && baseConnectors[j].Origin.Y - baseConnectors[i].Origin.Y < min2FittingsLength) { return false; } } } try { double baseZ = baseConnectors[0].Origin.Z + min1FittingLength; //Create the ducts and elbow fittings to connect the vertical ducts and the trunk ducts List<Connector> connectors = new List<Connector>(); if (baseConnectors[0].Origin.Y == baseConnectors[1].Origin.Y) { //All 3 connectors are with the same Y value if (baseConnectors[1].Origin.Y == baseConnectors[2].Origin.Y) { return false; } else { //The 1st and 2nd base connectors are on the same side of the trunk if (Math.Sign(baseConnectors[0].Origin.X - baseX) * Math.Sign(baseConnectors[1].Origin.X - baseX) == 1) { return false; } //Create the trunk connectors = CreateDuct(new GXYZ(baseX, baseConnectors[0].Origin.Y + min1FittingLength, baseZ), new GXYZ(baseX, baseConnectors[2].Origin.Y - min1FittingLength, baseZ)); //Create a tee fitting connecting the 1st and 2nd base connectors to the trunk ConnectWithTeeFittingOnYAxis(baseConnectors[0], baseConnectors[1], connectors[0], true); //Create an elbow fitting connection the 3rd base connector to the trunk ConnectWithElbowFittingOnYAxis(baseConnectors[2], connectors[1]); } } else { //Create the segment of duct on the trunk to be connected to the 1st base connector connectors = CreateDuct(new GXYZ(baseX, baseConnectors[0].Origin.Y + min1FittingLength, baseZ), new GXYZ(baseX, baseConnectors[1].Origin.Y - min1FittingLength, baseZ)); //Create an elbow fitting connection the 1st base connector with the trunk ConnectWithElbowFittingOnYAxis(baseConnectors[0], connectors[0]); if (baseConnectors[1].Origin.Y == baseConnectors[2].Origin.Y) { //The 2nd and 3rd connectors are on the same side of the trunk if (Math.Sign(baseConnectors[1].Origin.X - baseX) * Math.Sign(baseConnectors[2].Origin.X - baseX) == 1) { return false; } //Create a tee fitting connecting the 2nd and 3rd base connectors to the trunk ConnectWithTeeFittingOnYAxis(baseConnectors[1], baseConnectors[2], connectors[1], true); } else { connectors.AddRange(CreateDuct(new GXYZ(baseX, baseConnectors[1].Origin.Y + min1FittingLength, baseZ), new GXYZ(baseX, baseConnectors[2].Origin.Y - min1FittingLength, baseZ))); //Create a tee fitting connecting the 2nd base connector to the trunk ConnectWithTeeFittingOnYAxis(baseConnectors[1], connectors[1], connectors[2], false); //Create an elbow fitting connection the 3rd base connector to the trunk ConnectWithElbowFittingOnYAxis(baseConnectors[2], connectors[3]); } } return true; } catch { return false; } } /// <summary> /// Connect a base connector to a connector on the trunk with an elbow fitting /// </summary> /// <param name="baseConn">the upper connector of the vertical duct that derived from a terminal or the base equipment</param> /// <param name="conn">the connector of a duct on the trunk</param> private void ConnectWithElbowFittingOnYAxis(Connector baseConn, Connector conn) { double baseX = conn.Origin.X; double baseZ = conn.Origin.Z; List<Connector> connectors = new List<Connector>(); //If the distance of the two connectors on the X axis is greater than 2, create a duct on the X axis and then connect it to the 2 connectors with elbow fittings if (Math.Abs(baseConn.Origin.X - baseX) > min1Duct2FittingsLength) { connectors.AddRange(CreateDuct(new GXYZ(baseConn.Origin.X - Math.Sign(baseConn.Origin.X - baseX), baseConn.Origin.Y, baseZ), new GXYZ(baseX + Math.Sign(baseConn.Origin.X - baseX), baseConn.Origin.Y, baseZ))); connectors[0].ConnectTo(baseConn); m_document.Create.NewElbowFitting(connectors[0], baseConn); connectors[1].ConnectTo(conn); m_document.Create.NewElbowFitting(connectors[1], conn); } //If the distance of the two connectors on the X axis is less than 2, connect them with an elbow fitting else { baseConn.ConnectTo(conn); m_document.Create.NewElbowFitting(baseConn, conn); } } /// <summary> /// Connect 3 connectors on the trunk with a tee fitting /// </summary> /// <param name="conn1">the first connector</param> /// <param name="conn2">the second connector</param> /// <param name="conn3">the third connector</param> /// <param name="flag">a flag to indicate whether there are 2 base connectors or 1 base connector</param> private void ConnectWithTeeFittingOnYAxis(Connector conn1, Connector conn2, Connector conn3, bool flag) { double baseX = conn3.Origin.X; double baseZ = conn3.Origin.Z; List<GXYZ> points = new List<GXYZ>(); List<Duct> ducts = new List<Duct>(); List<Connector> connectors = new List<Connector>(); //Connect two base connectors to a connector on the trunk if (true == flag) { Connector baseConn1 = conn1; Connector baseConn2 = conn2; Connector conn = conn3; connectors.AddRange(CreateDuct(new GXYZ(baseConn1.Origin.X - Math.Sign(baseConn1.Origin.X - baseX), baseConn1.Origin.Y, baseZ), new GXYZ(baseX + Math.Sign(baseConn1.Origin.X - baseX), baseConn1.Origin.Y, baseZ))); connectors.AddRange(CreateDuct(new GXYZ(baseConn2.Origin.X - Math.Sign(baseConn2.Origin.X - baseX), baseConn2.Origin.Y, baseZ), new GXYZ(baseX + Math.Sign(baseConn2.Origin.X - baseX), baseConn2.Origin.Y, baseZ))); connectors[0].ConnectTo(baseConn1); connectors[2].ConnectTo(baseConn2); m_document.Create.NewElbowFitting(connectors[0], baseConn1); m_document.Create.NewElbowFitting(connectors[2], baseConn2); connectors[1].ConnectTo(connectors[3]); connectors[1].ConnectTo(conn); connectors[3].ConnectTo(conn); m_document.Create.NewTeeFitting(connectors[1], connectors[3], conn); } //Connect a base connector to two connectors on the trunk else { Connector baseConn = conn1; if (Math.Abs(baseConn.Origin.X - baseX) > min1Duct2FittingsLength) { connectors.AddRange(CreateDuct(new GXYZ(baseConn.Origin.X - Math.Sign(baseConn.Origin.X - baseX), baseConn.Origin.Y, baseZ), new GXYZ(baseX + Math.Sign(baseConn.Origin.X - baseX), baseConn.Origin.Y, baseZ))); baseConn.ConnectTo(connectors[0]); m_document.Create.NewElbowFitting(connectors[0], baseConn); connectors[1].ConnectTo(conn2); connectors[1].ConnectTo(conn3); conn2.ConnectTo(conn3); m_document.Create.NewTeeFitting(conn2, conn3, connectors[1]); } else { baseConn.ConnectTo(conn2); baseConn.ConnectTo(conn3); conn2.ConnectTo(conn3); m_document.Create.NewTeeFitting(conn2, conn3, baseConn); } } } /// <summary> /// Sort the base connectors by their y values /// </summary> /// <param name="connectors">the connectors to be sorted</param> private void SortConnectorsByY(List<Connector> connectors) { for (int i = 0; i < connectors.Count; ++i) { double min = connectors[i].Origin.Y; int minIndex = i; for (int j = i; j < connectors.Count; ++j) { if (connectors[j].Origin.Y < min) { min = connectors[j].Origin.Y; minIndex = j; } } Connector t = connectors[i]; connectors[i] = connectors[minIndex]; connectors[minIndex] = t; } } /// <summary> /// Create a duct with two points /// </summary> /// <param name="point1">the first point</param> /// <param name="point2">the second point</param> /// <returns></returns> private List<Connector> CreateDuct(GXYZ point1, GXYZ point2) { List<Connector> connectors = new List<Connector>(); Duct duct = m_document.Create.NewDuct(point1, point2, dtRectangle); connectors.Add(ConnectorInfo.GetConnector(duct.Id.IntegerValue, point1)); connectors.Add(ConnectorInfo.GetConnector(duct.Id.IntegerValue, point2)); return connectors; } /// <summary> /// Create a mechanical system /// </summary> /// <param name="baseConnector">the base connector of the mechanical system</param> /// <param name="connectors">the connectors of the mechanical system</param> /// <param name="systemType">the system type of the mechanical system</param> /// <returns>the created mechanical system</returns> private MechanicalSystem CreateMechanicalSystem(ConnectorInfo baseConnector, ConnectorInfo[] connectors, DuctSystemType systemType) { ConnectorSet cset = null; if (connectors != null) { cset = new ConnectorSet(); foreach (ConnectorInfo ci in connectors) { cset.Insert(ci.Connector); } } MechanicalSystem mechanicalSystem = m_document.Create.NewMechanicalSystem(baseConnector == null ? null : baseConnector.Connector, cset, systemType); return mechanicalSystem; } /// <summary> /// information of a connector /// </summary> public class ConnectorInfo { /// <summary> /// The owner's element ID /// </summary> int m_ownerId; /// <summary> /// The origin of the connector /// </summary> GXYZ m_origin; /// <summary> /// The Connector object /// </summary> Connector m_connector; /// <summary> /// The connector this object represents /// </summary> public Connector Connector { get { return m_connector; } set { m_connector = value; } } /// <summary> /// The owner ID of the connector /// </summary> public int OwnerId { get { return m_ownerId; } set { m_ownerId = value; } } /// <summary> /// The origin of the connector /// </summary> public GXYZ Origin { get { return m_origin; } set { m_origin = value; } } /// <summary> /// The constructor that finds the connector with the owner ID and origin /// </summary> /// <param name="ownerId">the ownerID of the connector</param> /// <param name="origin">the origin of the connector</param> public ConnectorInfo(int ownerId, GXYZ origin) { m_ownerId = ownerId; m_origin = origin; m_connector = ConnectorInfo.GetConnector(m_ownerId, origin); } /// <summary> /// The constructor that finds the connector with the owner ID and the values of the origin /// </summary> /// <param name="ownerId">the ownerID of the connector</param> /// <param name="x">the X value of the connector</param> /// <param name="y">the Y value of the connector</param> /// <param name="z">the Z value of the connector</param> public ConnectorInfo(int ownerId, double x, double y, double z) : this(ownerId, new GXYZ(x, y, z)) { } /// <summary> /// Get the connector of the owner at the specific origin /// </summary> /// <param name="ownerId">the owner ID of the connector</param> /// <param name="connectorOrigin">the origin of the connector</param> /// <returns>if found, return the connector, or else return null</returns> public static Connector GetConnector(int ownerId, GXYZ connectorOrigin) { ConnectorSet connectors = GetConnectors(ownerId); foreach (Connector conn in connectors) { if (conn.ConnectorType == ConnectorType.Logical) continue; if (conn.Origin.IsAlmostEqualTo(connectorOrigin)) return conn; } return null; } /// <summary> /// Get all the connectors of an element with a specific ID /// </summary> /// <param name="ownerId">the owner ID of the connector</param> /// <returns>the connector set which includes all the connectors found</returns> public static ConnectorSet GetConnectors(int ownerId) { Autodesk.Revit.DB.ElementId elementId = new ElementId(ownerId); Element element = m_document.get_Element(elementId); return GetConnectors(element); } /// <summary> /// Get all the connectors of a specific element /// </summary> /// <param name="element">the owner of the connector</param> /// <returns>if found, return all the connectors found, or else return null</returns> public static ConnectorSet GetConnectors(Autodesk.Revit.DB.Element element) { if (element == null) return null; FamilyInstance fi = element as FamilyInstance; if (fi != null && fi.MEPModel != null) { return fi.MEPModel.ConnectorManager.Connectors; } MEPSystem system = element as MEPSystem; if (system != null) { return system.ConnectorManager.Connectors; } MEPCurve duct = element as MEPCurve; if (duct != null) { return duct.ConnectorManager.Connectors; } return null; } /// <summary> /// Find the two connectors of the specific ConnectorManager at the two locations /// </summary> /// <param name="connMgr">The ConnectorManager of the connectors to be found</param> /// <param name="ptn1">the location of the first connector</param> /// <param name="ptn2">the location of the second connector</param> /// <returns>The two connectors found</returns> public static Connector[] FindConnectors(ConnectorManager connMgr, GXYZ pnt1, GXYZ pnt2) { Connector[] result = new Connector[2]; ConnectorSet conns = connMgr.Connectors; foreach (Connector conn in conns) { if (conn.Origin.IsAlmostEqualTo(pnt1)) { result[0] = conn; } else if (conn.Origin.IsAlmostEqualTo(pnt2)) { result[1] = conn; } } return result; } }; } public class LogUtility { /// <summary> /// Invalid string. /// </summary> public const string InvalidString = "[!]"; /// <summary> /// Write the information of an element to the log file /// </summary> /// <param name="element">the element whose information is to be written</param> public static void WriteElement(Element element) { WriteElement(element, true); } /// <summary> /// Write the information of an element to the log file /// </summary> /// <param name="element">the element whose information is to be written</param> /// <param name="writeId">whether the id will be outputted</param> public static void WriteElement(Element element, bool writeId) { if (element == null) { Trace.WriteLine("null"); return; } int elementId = element.Id.IntegerValue; int familyId = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsElementId().IntegerValue; string familyName = LogUtility.InvalidString; Element objectType = GetElement<Element>(element.Document, familyId); string elementName = LogUtility.InvalidString; try { elementName = element.Name; } catch { } if (objectType != null) { Parameter familyNameParameter = objectType.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME); if (familyNameParameter != null) familyName = familyNameParameter.AsString(); } BuiltInCategory category = (BuiltInCategory)(element.get_Parameter(BuiltInParameter.ELEM_CATEGORY_PARAM).AsElementId().IntegerValue); Trace.WriteLine("Type: " + element.GetType().FullName); Trace.WriteLine("Name: " + familyName + ":" + elementName); if(writeId) Trace.WriteLine("Id: " + elementId); Trace.WriteLine("Category: " + category); Trace.WriteLine("FamilyId: " + familyId); } /// <summary> /// Write the information of a mechanical system to the log file /// </summary> /// <param name="system">the mechanical system whose information is to be written</param> public static void WriteMechanicalSystem(MechanicalSystem system) { string flow = InvalidString; try { flow = system.Flow.ToString(); } catch (Exception) { } //string staticPressure = InvalidString; //try { staticPressure = system.StaticPressure.ToString(); } //catch (Exception) { } Trace.WriteLine("Flow: " + flow); Trace.WriteLine("IsWellConnected: " + system.IsWellConnected); //Trace.WriteLine("StaticPressure: " + staticPressure); Trace.WriteLine("SystemType: " + system.SystemType); Trace.WriteLine("+DuctNetwork"); Trace.Indent(); foreach (Element element in system.DuctNetwork) { LogUtility.WriteElement(element, false); Trace.WriteLine(""); } Trace.Unindent(); WriteMEPSystem(system); } /// <summary> /// Get element by its id and cast it to the specified type /// </summary> /// <param name="document">the owner document of the element</param> /// <param name="eid">the id of the element</param> /// <returns>the element of the specified type</returns> public static T GetElement<T>(Document document, int eid) where T : Autodesk.Revit.DB.Element { Autodesk.Revit.DB.ElementId elementId = new ElementId(eid); return document.get_Element(elementId) as T; } /// <summary> /// Write the information of a MEPSystem to the log file. /// </summary> /// <param name="system">the MEP system whose information is to be written</param> public static void WriteMEPSystem(MEPSystem system) { Trace.WriteLine("IsDefaultSystem: " + system.IsDefaultSystem); Trace.WriteLine("+BaseEquipment"); Trace.Indent(); WriteElement(system.BaseEquipment); Trace.Unindent(); Trace.WriteLine("+BaseEquipmentConnector"); Trace.Indent(); WriteConnector(system.BaseEquipmentConnector); Trace.Unindent(); Trace.WriteLine("+Elements"); Trace.Indent(); foreach (Element element in system.Elements) { WriteElement(element); Trace.WriteLine(""); } Trace.Unindent(); Trace.WriteLine("+ConnectorManager"); Trace.Indent(); WriteConnectorManager(system.ConnectorManager); Trace.Unindent(); } /// <summary> /// Write the information of a connector to the log file /// </summary> /// <param name="connector">the connector whose information is to be written</param> public static void WriteConnector(Connector connector) { if (connector == null) { Trace.WriteLine("null"); return; } object connType = InvalidString; object connDirection = InvalidString; object connShape = InvalidString; try { connShape = connector.Shape; } catch { } object connSize = InvalidString; try { connSize = GetShapeInfo(connector); } catch { } object connLocation = GetLocation(connector); object connAType = connector.ConnectorType; object connIsConnected = InvalidString; switch (connector.Domain) { case Domain.DomainElectrical: connType = connector.ElectricalSystemType; break; case Domain.DomainHvac: connType = connector.DuctSystemType; connDirection = connector.Direction; connIsConnected = connector.IsConnected; break; case Domain.DomainPiping: connType = connector.PipeSystemType; connDirection = connector.Direction; connIsConnected = connector.IsConnected; break; case Domain.DomainUndefined: default: connType = Domain.DomainUndefined; break; } Trace.WriteLine("Type: " + connAType); Trace.WriteLine("SystemType: " + connType); Trace.WriteLine("Direction: " + connDirection); Trace.WriteLine("Shape: " + connShape); Trace.WriteLine("Size: " + connSize); Trace.WriteLine("Location: " + connLocation); Trace.WriteLine("IsConnected: " + connIsConnected); } /// <summary> /// Write the information of a ConnectorManager to the log file /// </summary> /// <param name="connectorManager">the ConnectorManager whose information is to be written</param> public static void WriteConnectorManager(ConnectorManager connectorManager) { Trace.WriteLine("+Connectors"); Trace.Indent(); WriteConnectorSet2(connectorManager.Connectors); Trace.Unindent(); Trace.WriteLine("+UnusedConnectors"); Trace.Indent(); WriteConnectorSet2(connectorManager.UnusedConnectors); Trace.Unindent(); } /// <summary> /// Get the information string of a connector /// </summary> /// <param name="connector">the connector to be read</param> /// <returns>the information string of the connector</returns> public static string GetConnectorId(Connector connector) { if (connector == null) { return "null"; } int ownerId = connector.Owner.Id.IntegerValue; string systemId = InvalidString; try { systemId = connector.MEPSystem.Id.IntegerValue.ToString(); } catch { } object connType = InvalidString; object connDirection = InvalidString; object connShape = InvalidString; try { connShape = connector.Shape; } catch { } object connSize = InvalidString; try { connSize = GetShapeInfo(connector); } catch { } object connLocation = GetLocation(connector); object connAType = connector.ConnectorType; object connIsConnected = InvalidString; switch (connector.Domain) { case Domain.DomainElectrical: connType = connector.ElectricalSystemType; break; case Domain.DomainHvac: connType = connector.DuctSystemType; connDirection = connector.Direction; connIsConnected = connector.IsConnected; break; case Domain.DomainPiping: connType = connector.PipeSystemType; connDirection = connector.Direction; connIsConnected = connector.IsConnected; break; case Domain.DomainUndefined: default: connType = Domain.DomainUndefined; break; } return string.Format("[{0}]\t[{1}]\t[{2}]\t[{3}]\t[{4}]\t[{5}]\t[{6}]\t[{7}]\t[{8}]\t", ownerId, connType, connDirection, connShape, connSize, connLocation, connAType, connIsConnected, systemId); } /// <summary> /// Get the shape information string of a connector /// </summary> /// <param name="conn">the element to be read</param> /// <returns>the shape information string of the connector</returns> private static string GetShapeInfo(Connector conn) { switch (conn.Shape) { case ConnectorProfileType.InvalidProfile: break; case ConnectorProfileType.OvalProfile: break; case ConnectorProfileType.RectProfile: return string.Format("{0}\" x {1}\"", conn.Width, conn.Height); case ConnectorProfileType.RoundProfile: return string.Format("{0}\"", conn.Radius); default: break; } return InvalidString; } /// <summary> /// Get the location string of a connector /// </summary> /// <param name="conn">the connector to be read</param> /// <returns>the location information string of the connector</returns> private static object GetLocation(Connector conn) { if (conn.ConnectorType == ConnectorType.Logical) { return InvalidString; } Autodesk.Revit.DB.XYZ origin = conn.Origin; return string.Format("{0},{1},{2}", origin.X, origin.Y, origin.Z); } /// <summary> /// Write the information of a ConnectorSet to the log file. /// </summary> /// <param name="connectorSet">the ConnectorSet whose information is to be written</param> private static void WriteConnectorSet2(ConnectorSet connectorSet) { SortedDictionary<string, List<Connector>> connectors = new SortedDictionary<string, List<Connector>>(); foreach (Connector conn in connectorSet) { string connId = GetConnectorId(conn); if (conn.ConnectorType == ConnectorType.Logical) { foreach (Connector logLinkConn in conn.AllRefs) { connId += GetConnectorId(logLinkConn); } } if (!connectors.ContainsKey(connId)) { connectors.Add(connId, new List<Connector>()); } connectors[connId].Add(conn); } foreach (string key in connectors.Keys) { foreach (Connector conn in connectors[key]) { WriteConnector(conn); Trace.WriteLine("+AllRefs"); Trace.Indent(); WriteConnectorSet(conn.AllRefs); Trace.Unindent(); Trace.WriteLine(""); } } } /// <summary> /// Write the information of a ConnectorSet to the log file. /// </summary> /// <param name="connectorSet">the mechanical system whose information is to be written</param> private static void WriteConnectorSet(ConnectorSet connectorSet) { SortedDictionary<string, List<Connector>> connectors = new SortedDictionary<string, List<Connector>>(); foreach (Connector conn in connectorSet) { string connId = GetConnectorId(conn); if (conn.ConnectorType == ConnectorType.Logical) { foreach (Connector logLinkConn in conn.AllRefs) { connId += GetConnectorId(logLinkConn); } } if (!connectors.ContainsKey(connId)) { connectors.Add(connId, new List<Connector>()); } connectors[connId].Add(conn); } foreach (string key in connectors.Keys) { foreach (Connector conn in connectors[key]) { WriteConnector(conn); Trace.WriteLine(""); } } } } }
using System; using SharpDX; using SharpDX.Toolkit.Graphics; namespace DXFramework.Util { /// <summary> /// Manages screen view. /// Based on: http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/. /// </summary> public class Camera { private GraphicsDevice graphics; private Matrix transform; private Matrix orthographicTransform; private Vector2 cameraPos; private Vector2 localCursorPos; private Vector2 oldLocalCursorPos; private float zoom; private float invZoom; private float rotation; private float radianRotation; private bool updateTransform; private bool updateOrthographicTransform; public Camera( GraphicsDevice graphics ) { this.graphics = graphics; UpdateTransformations(); Zoom = 1.0f; } #region Properties /// <summary> /// Camera zoom factor. Set to 1.0f for no zoom. /// </summary> public float Zoom { get { return zoom; } set { if( zoom != value ) { zoom = value; if( zoom < 0.002f ) // Negative zoom will flip image { zoom = 0.002f; } invZoom = 1f / zoom; UpdateTransformations(); } } } /// <summary> /// The inverse of the camera zoom. /// </summary> public float InverseZoom { get { return invZoom; } } /// <summary> /// Camera rotation in degrees. /// </summary> public float Rotation { get { return rotation; } set { if( rotation != value ) { rotation = value % 360; while( rotation < 0 ) { rotation += 360; } radianRotation = MathUtil.DegreesToRadians( rotation ); UpdateTransformations(); } } } /// <summary> /// Camera rotation in radians. /// </summary> public float RadianRotation { get { return radianRotation; } } /// <summary> /// Camera position. This position is always in the center of the viewport. /// </summary> public Vector2 Position { get { return cameraPos; } set { if (cameraPos != value) { cameraPos = value; UpdateTransformations(); } } } /// <summary> /// Camera-space cursor position. /// </summary> public Vector2 CursorPosition { get { return cameraPos + ( ( InputManager.MousePosition - HalfViewportSize ) * invZoom ); } } /// <summary> /// How far the cursor has moved in camera-space, since last call to 'MoveCursor'. /// </summary> public Vector2 CursorMoveDist { get { return ( oldLocalCursorPos - localCursorPos ) * invZoom; } } /// <summary> /// Returns the center position of the camera's viewport in camera-space. /// </summary> public Vector2 ViewportCenter { get { return -( cameraPos * zoom ) + HalfViewportSize; } } private ViewportF Viewport { get { return graphics.Viewport; } } private Vector2 HalfViewportSize { get { return new Vector2( graphics.Viewport.Width * 0.5f, graphics.Viewport.Height * 0.5f ); } } #endregion #region Methods /// <summary> /// Initiates camera cursort movement. /// </summary> public void InitiateCursorMovement() { localCursorPos = InputManager.MousePosition; } /// <summary> /// Handles camera cursor movement. /// </summary> public void DoCursorMovement() { oldLocalCursorPos = localCursorPos; localCursorPos = InputManager.MousePosition; Vector2 dist = CursorMoveDist; if( radianRotation != 0 ) { Position += dist.RotateAroundOrigin( Vector2.Zero, radianRotation ); } else { Position += dist; } } /// <summary> /// Returns camera-space position, from a local-space positon. /// </summary> /// <param name="localSpacePosition">Local-space position to convert.</param> public Vector2 GetCameraPos( Vector2 localSpacePosition ) { return cameraPos + ( ( localSpacePosition - HalfViewportSize ) * invZoom ); } /// <summary> /// Returns camera-space position, from a local-space positon. /// </summary> /// <param name="localSpacePosition">Local-space position to convert.</param> public void GetCameraPos( ref Vector2 localSpacePosition, out Vector2 cameraSpacePosition ) { cameraSpacePosition = cameraPos + ( ( localSpacePosition - HalfViewportSize ) * invZoom ); } /// <summary> /// Moves the camera by a set amount. /// </summary> /// <param name="amount">Amount to move the camera in local-space.</param> public void Move( Vector2 amount ) { if (amount == Vector2.Zero) { return; } Position -= amount * invZoom; } /// <summary> /// Centers the Camera to the level center. /// </summary> public void CenterToLevel() { Position = Vector2.Zero; } /// <summary> /// Centers the Camera to the cursor. /// </summary> public void CenterToCursor() { Position = CursorPosition; } /// <summary> /// Centers the Camera to a position. /// </summary> /// <param name="pos">Camera-space position.</param> public void CenterToPosition( Vector2 pos ) { Position = pos; } /// <summary> /// Zooms the camera by a set amount to a given position. /// </summary> /// <param name="zoomAmount">Zoom increment.</param> /// <param name="pos">Position to zoom too.</param> public void ZoomToPos( int zoomPercentAmount, Vector2 pos ) { Vector2 oldPos; GetCameraPos( ref pos, out oldPos ); Zoom += ( zoom * 0.01f ) * zoomPercentAmount; Vector2 newPos; GetCameraPos( ref pos, out newPos ); Position -= newPos - oldPos; } /// <summary> /// Forces the camera to update its transformation matrices. /// </summary> public void UpdateTransformations() { updateTransform = true; updateOrthographicTransform = true; } /// <summary> /// Returns the Camera's transformation matrix calculated by position, rotation, zoom and viewport where {x:0, y:0} is the center of the viewport. /// Used when drawing in 2D spaces. /// If no changes has happened to the camera, the matrix will not be recalculated, and the previous matrix will be returned. /// </summary> public Matrix GetTransformation() { if( updateTransform ) { updateTransform = false; transform = Matrix.Translation( -cameraPos.X, -cameraPos.Y, 0 ) * Matrix.RotationZ( radianRotation ) * Matrix.Scaling( zoom, zoom, 0 ) * Matrix.Translation( graphics.Viewport.Width * 0.5f, graphics.Viewport.Height * 0.5f, 0 ); } return transform; } /// <summary> /// Returns the Camera's Orthographic transformation matrix. Used when drawing in 3D spaces and when drawing primitives. /// If no changes has happened to the camera, the matrix will not be recalculated, and the previous matrix will be returned. /// </summary> public Matrix GetOrthographicTransformation() { if( updateOrthographicTransform ) { updateOrthographicTransform = false; orthographicTransform = GetTransformation() * Matrix.OrthoOffCenterLH( 0f, graphics.Viewport.Width, graphics.Viewport.Height, 0f, 0f, 1f ); } return orthographicTransform; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.Internal; namespace Orleans.Runtime.GrainDirectory { [Serializable] internal class ActivationInfo : IActivationInfo { public SiloAddress SiloAddress { get; private set; } public DateTime TimeCreated { get; private set; } public ActivationInfo(SiloAddress siloAddress) { SiloAddress = siloAddress; TimeCreated = DateTime.UtcNow; } public ActivationInfo(IActivationInfo iActivationInfo) { SiloAddress = iActivationInfo.SiloAddress; TimeCreated = iActivationInfo.TimeCreated; } public bool OkToRemove(UnregistrationCause cause, TimeSpan lazyDeregistrationDelay) { switch (cause) { case UnregistrationCause.Force: return true; case UnregistrationCause.NonexistentActivation: { var delayparameter = lazyDeregistrationDelay; if (delayparameter <= TimeSpan.Zero) return false; // no lazy deregistration else return (TimeCreated <= DateTime.UtcNow - delayparameter); } default: throw new OrleansException("unhandled case"); } } public override string ToString() { return String.Format("{0}, {1}", SiloAddress, TimeCreated); } } [Serializable] internal class GrainInfo : IGrainInfo { public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; } public int VersionTag { get; private set; } public bool SingleInstance { get; private set; } internal const int NO_ETAG = -1; internal GrainInfo() { Instances = new Dictionary<ActivationId, IActivationInfo>(); VersionTag = 0; SingleInstance = false; } public bool AddActivation(ActivationId act, SiloAddress silo) { if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act)) { throw new InvalidOperationException( "Attempting to add a second activation to an existing grain in single activation mode"); } IActivationInfo info; if (Instances.TryGetValue(act, out info)) { if (info.SiloAddress.Equals(silo)) { // just refresh, no need to generate new VersionTag return false; } } Instances[act] = new ActivationInfo(silo); VersionTag = ThreadSafeRandom.Next(); return true; } public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo) { SingleInstance = true; if (Instances.Count > 0) { var item = Instances.First(); return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key); } else { Instances.Add(act, new ActivationInfo(silo)); VersionTag = ThreadSafeRandom.Next(); return ActivationAddress.GetAddress(silo, grain, act); } } public bool RemoveActivation(ActivationId act, UnregistrationCause cause, TimeSpan lazyDeregistrationDelay, out IActivationInfo info, out bool wasRemoved) { wasRemoved = false; if (Instances.TryGetValue(act, out info) && info.OkToRemove(cause, lazyDeregistrationDelay)) { Instances.Remove(act); wasRemoved = true; VersionTag = ThreadSafeRandom.Next(); } return Instances.Count == 0; } public Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainId grain, IGrainInfo other) { bool modified = false; foreach (var pair in other.Instances) { if (Instances.ContainsKey(pair.Key)) continue; Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress); modified = true; } if (modified) { VersionTag = ThreadSafeRandom.Next(); } if (SingleInstance && (Instances.Count > 0)) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. var orderedActivations = Instances.OrderBy(pair => pair.Key); var activationToKeep = orderedActivations.First(); var activationsToDrop = orderedActivations.Skip(1); Instances.Clear(); Instances.Add(activationToKeep.Key, activationToKeep.Value); var mapping = new Dictionary<SiloAddress, List<ActivationAddress>>(); foreach (var activationPair in activationsToDrop) { var activation = ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key); List<ActivationAddress> activationsToRemoveOnSilo; if (!mapping.TryGetValue(activation.Silo, out activationsToRemoveOnSilo)) { activationsToRemoveOnSilo = mapping[activation.Silo] = new List<ActivationAddress>(1); } activationsToRemoveOnSilo.Add(activation); } return mapping; } return null; } } internal class GrainDirectoryPartition { // Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full // parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do // a lot more lookups and so can sort periodically? /// <summary> /// contains a map from grain to its list of activations along with the version (etag) counter for the list /// </summary> private Dictionary<GrainId, IGrainInfo> partitionData; private readonly object lockable; private readonly ILogger log; private readonly ILoggerFactory loggerFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly IOptions<GrainDirectoryOptions> grainDirectoryOptions; [ThreadStatic] private static ActivationId[] activationIdsHolder; [ThreadStatic] private static IActivationInfo[] activationInfosHolder; internal int Count { get { return partitionData.Count; } } public GrainDirectoryPartition(ISiloStatusOracle siloStatusOracle, IOptions<GrainDirectoryOptions> grainDirectoryOptions, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory) { partitionData = new Dictionary<GrainId, IGrainInfo>(); lockable = new object(); log = loggerFactory.CreateLogger<GrainDirectoryPartition>(); this.siloStatusOracle = siloStatusOracle; this.grainDirectoryOptions = grainDirectoryOptions; this.grainFactory = grainFactory; this.loggerFactory = loggerFactory; } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } internal void Clear() { lock (lockable) { partitionData.Clear(); } } /// <summary> /// Returns all entries stored in the partition as an enumerable collection /// </summary> /// <returns></returns> public List<KeyValuePair<GrainId, IGrainInfo>> GetItems() { lock (lockable) { return partitionData.ToList(); } } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <returns>The version associated with this directory mapping</returns> internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo) { if (!IsValidSilo(silo)) { return GrainInfo.NO_ETAG; } IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } grainInfo.AddActivation(activation, silo); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding activation for grain {0}", grain.ToString()); return grainInfo.VersionTag; } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <returns>The registered ActivationAddress and version associated with this directory mapping</returns> internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding single activation for grain {0}{1}{2}", silo, grain, activation); AddressAndTag result = new AddressAndTag(); if (!IsValidSilo(silo)) { var siloStatus = this.siloStatusOracle.GetApproximateSiloStatus(silo); throw new OrleansException($"Trying to register {grain} on invalid silo: {silo}. Known status: {siloStatus}"); } IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } result.Address = grainInfo.AddSingleActivation(grain, activation, silo); result.VersionTag = grainInfo.VersionTag; } return result; } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force) { RemoveActivation(grain, activation, cause, out _, out _); } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> /// <param name="entry">returns the entry, if found </param> /// <param name="wasRemoved">returns whether the entry was actually removed</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved) { wasRemoved = false; entry = null; lock (lockable) { if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, this.grainDirectoryOptions.Value.LazyDeregistrationDelay, out entry, out wasRemoved)) // if the last activation for the grain was removed, we remove the entire grain info partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved); } /// <summary> /// Removes the grain (and, effectively, all its activations) from the directory /// </summary> /// <param name="grain"></param> internal void RemoveGrain(GrainId grain) { lock (lockable) { partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing grain {0}", grain.ToString()); } /// <summary> /// Returns a list of activations (along with the version number of the list) for the given grain. /// If the grain is not found, null is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal AddressesAndTag LookUpActivations(GrainId grain) { var result = new AddressesAndTag(); ActivationId[] activationIds; IActivationInfo[] activationInfos; const int arrayReusingThreshold = 100; int grainInfoInstancesCount; lock (lockable) { IGrainInfo graininfo; if (!partitionData.TryGetValue(grain, out graininfo)) { return result; } result.VersionTag = graininfo.VersionTag; grainInfoInstancesCount = graininfo.Instances.Count; if (grainInfoInstancesCount < arrayReusingThreshold) { if ((activationIds = activationIdsHolder) == null) { activationIdsHolder = activationIds = new ActivationId[arrayReusingThreshold]; } if ((activationInfos = activationInfosHolder) == null) { activationInfosHolder = activationInfos = new IActivationInfo[arrayReusingThreshold]; } } else { activationIds = new ActivationId[grainInfoInstancesCount]; activationInfos = new IActivationInfo[grainInfoInstancesCount]; } graininfo.Instances.Keys.CopyTo(activationIds, 0); graininfo.Instances.Values.CopyTo(activationInfos, 0); } result.Addresses = new List<ActivationAddress>(grainInfoInstancesCount); for (var i = 0; i < grainInfoInstancesCount; i++) { var activationInfo = activationInfos[i]; if (IsValidSilo(activationInfo.SiloAddress)) { result.Addresses.Add(ActivationAddress.GetAddress(activationInfo.SiloAddress, grain, activationIds[i])); } activationInfos[i] = null; activationIds[i] = null; } return result; } /// <summary> /// Returns the version number of the list of activations for the grain. /// If the grain is not found, -1 is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal int GetGrainETag(GrainId grain) { IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainInfo.NO_ETAG; } return grainInfo.VersionTag; } } /// <summary> /// Merges one partition into another, assuming partitions are disjoint. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="other"></param> /// <returns>Activations which must be deactivated.</returns> internal Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainDirectoryPartition other) { Dictionary<SiloAddress, List<ActivationAddress>> activationsToRemove = null; lock (lockable) { foreach (var pair in other.partitionData) { if (partitionData.ContainsKey(pair.Key)) { if (log.IsEnabled(LogLevel.Debug)) log.Debug("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions"); var activationsToDrop = partitionData[pair.Key].Merge(pair.Key, pair.Value); if (activationsToDrop == null) continue; if (activationsToRemove == null) activationsToRemove = new Dictionary<SiloAddress, List<ActivationAddress>>(); foreach (var siloActivations in activationsToDrop) { if (activationsToRemove.TryGetValue(siloActivations.Key, out var activations)) { activations.AddRange(siloActivations.Value); } else { activationsToRemove[siloActivations.Key] = siloActivations.Value; } } } else { partitionData.Add(pair.Key, pair.Value); } } } return activationsToRemove; } /// <summary> /// Runs through all entries in the partition and moves/copies (depending on the given flag) the /// entries satisfying the given predicate into a new partition. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param> /// <param name="modifyOrigin">flag controlling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param> /// <returns>new grain directory partition containing entries satisfying the given predicate</returns> internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin) { var newDirectory = new GrainDirectoryPartition(this.siloStatusOracle, this.grainDirectoryOptions, this.grainFactory, this.loggerFactory); if (modifyOrigin) { // SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here List<KeyValuePair<GrainId, IGrainInfo>> pairs; lock (lockable) { pairs = partitionData.Where(pair => predicate(pair.Key)).ToList(); } foreach (var pair in pairs) { newDirectory.partitionData.Add(pair.Key, pair.Value); } lock (lockable) { foreach (var pair in pairs) { partitionData.Remove(pair.Key); } } } else { lock (lockable) { foreach (var pair in partitionData.Where(pair => predicate(pair.Key))) { newDirectory.partitionData.Add(pair.Key, pair.Value); } } } return newDirectory; } internal List<ActivationAddress> ToListOfActivations(bool singleActivation) { var result = new List<ActivationAddress>(); lock (lockable) { foreach (var pair in partitionData) { var grain = pair.Key; if (pair.Value.SingleInstance == singleActivation) { result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key)) .Where(addr => IsValidSilo(addr.Silo))); } } } return result; } /// <summary> /// Sets the internal partition dictionary to the one given as input parameter. /// This method is supposed to be used by handoff manager to update the old partition with a new partition. /// </summary> /// <param name="newPartitionData">new internal partition dictionary</param> internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData) { partitionData = newPartitionData; } /// <summary> /// Updates partition with a new delta of changes. /// This method is supposed to be used by handoff manager to update the partition with a set of delta changes. /// </summary> /// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition. /// If the value for a given key in the delta is valid, then existing entry in the partition is replaced. /// Otherwise, i.e., if the value is null, the corresponding entry is removed. /// </param> internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta) { lock (lockable) { foreach (var kv in newPartitionDelta) { if (kv.Value != null) { partitionData[kv.Key] = kv.Value; } else { partitionData.Remove(kv.Key); } } } } public override string ToString() { var sb = new StringBuilder(); lock (lockable) { foreach (var grainEntry in partitionData) { foreach (var activationEntry in grainEntry.Value.Instances) { sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]"). Append(" => ").Append(activationEntry.Key.ToString()). Append(" @ ").AppendLine(activationEntry.Value.ToString()); } } } return sb.ToString(); } } }
using System; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Core; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// Indicates that a <see cref="GrainReference"/> was not bound to the runtime before being used. /// </summary> [Serializable] public class GrainReferenceNotBoundException : OrleansException { internal GrainReferenceNotBoundException(GrainReference grainReference) : base(CreateMessage(grainReference)) { } private static string CreateMessage(GrainReference grainReference) { return $"Attempted to use a GrainReference which has not been bound to the runtime: {grainReference.ToDetailedString()}." + $" Use the {nameof(IGrainFactory)}.{nameof(IGrainFactory.BindGrainReference)} method to bind this reference to the runtime."; } internal GrainReferenceNotBoundException(string msg) : base(msg) { } internal GrainReferenceNotBoundException(string message, Exception innerException) : base(message, innerException) { } protected GrainReferenceNotBoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; /// <summary> /// Invoke method options specific to this grain reference instance /// </summary> [NonSerialized] private readonly InvokeMethodOptions invokeMethodOptions; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } public bool IsGrainService => this.IsSystemTarget; // TODO make this distinct internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } internal bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal IGrainReferenceRuntime Runtime { get { if (this.runtime == null) throw new GrainReferenceNotBoundException(this); return this.runtime; } } /// <summary> /// Gets a value indicating whether this instance is bound to a runtime and hence valid for making requests. /// </summary> internal bool IsBound => this.runtime != null; internal GrainId GrainId { get; private set; } public IGrainIdentity GrainIdentity => this.GrainId; /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; public SiloAddress GrainServiceSiloAddress => this.SystemTargetSilo; // TODO make this distinct [NonSerialized] private IGrainReferenceRuntime runtime; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal string GenericArguments => this.genericArguments; /// <summary>Constructs a reference to the grain with the specified Id.</summary> /// <param name="grainId">The Id of the grain to refer to.</param> /// <param name="genericArgument">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> /// <param name="observerId">Observer ID in case of an observer reference.</param> /// <param name="runtime">The runtime which this grain reference is bound to.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId, IGrainReferenceRuntime runtime) { GrainId = grainId; this.genericArguments = genericArgument; this.SystemTargetSilo = systemTargetSilo; this.observerId = observerId; this.runtime = runtime; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId, other.runtime) { this.invokeMethodOptions = other.invokeMethodOptions; } protected internal GrainReference(GrainReference other, InvokeMethodOptions invokeMethodOptions) : this(other) { this.invokeMethodOptions = invokeMethodOptions; } /// <summary>Constructs a reference to the grain with the specified ID.</summary> /// <param name="grainId">The ID of the grain to refer to.</param> /// <param name="runtime">The runtime client</param> /// <param name="genericArguments">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> internal static GrainReference FromGrainId(GrainId grainId, IGrainReferenceRuntime runtime, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null, runtime); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId, IGrainReferenceRuntime runtime) { return new GrainReference(grainId, null, null, observerId, runtime); } /// <summary> /// Binds this instance to a runtime. /// </summary> /// <param name="runtime">The runtime.</param> internal void Bind(IGrainReferenceRuntime runtime) { this.runtime = runtime; } /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> public virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual ushort InterfaceVersion { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> public virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo); } /// <summary> /// Called from generated code. /// </summary> protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { return this.Runtime.InvokeMethodAsync<T>(this, methodId, arguments, options | invokeMethodOptions, silo); } private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string SYSTEM_TARGET_STR_WITH_EQUAL_SIGN = SYSTEM_TARGET_STR + "="; private const string OBSERVER_ID_STR = "ObserverId"; private const string OBSERVER_ID_STR_WITH_EQUAL_SIGN = OBSERVER_ID_STR + "="; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; private const string GENERIC_ARGUMENTS_STR_WITH_EQUAL_SIGN = GENERIC_ARGUMENTS_STR + "="; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } public GrainReferenceKeyInfo ToKeyInfo() { if (IsObserverReference) { return new GrainReferenceKeyInfo(GrainId.ToKeyInfo(), observerId.Guid); } if (IsSystemTarget) { return new GrainReferenceKeyInfo(GrainId.ToKeyInfo(), (SystemTargetSilo.Endpoint, SystemTargetSilo.Generation)); } if (HasGenericArgument) { return new GrainReferenceKeyInfo(GrainId.ToKeyInfo(), genericArguments); } return new GrainReferenceKeyInfo(GrainId.ToKeyInfo()); } internal static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key), "GrainReference.FromKeyString cannot parse null key"); ReadOnlySpan<char> trimmed = key.AsSpan().Trim(); ReadOnlySpan<char> grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR_WITH_EQUAL_SIGN.AsSpan(), StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR_WITH_EQUAL_SIGN.AsSpan(), StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR_WITH_EQUAL_SIGN.AsSpan(), StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Slice(grainIdIndex, genericIndex - grainIdIndex).Trim(); ReadOnlySpan<char> genericStr = trimmed.Slice(genericIndex + GENERIC_ARGUMENTS_STR_WITH_EQUAL_SIGN.Length); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, genericStr.ToString()); } else if (observerIndex >= 0) { grainIdStr = trimmed.Slice(grainIdIndex, observerIndex - grainIdIndex).Trim(); ReadOnlySpan<char> observerIdStr = trimmed.Slice(observerIndex + OBSERVER_ID_STR_WITH_EQUAL_SIGN.Length); GuidId observerId = GuidId.FromParsableString(observerIdStr.ToString()); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId, runtime); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Slice(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); ReadOnlySpan<char> systemTargetStr = trimmed.Slice(systemTargetIndex + SYSTEM_TARGET_STR_WITH_EQUAL_SIGN.Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr.ToString()); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, null, siloAddress); } else { grainIdStr = trimmed.Slice(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime); } } internal static GrainReference FromKeyInfo(GrainReferenceKeyInfo keyInfo, IGrainReferenceRuntime runtime) { if (keyInfo.HasGenericArgument) { return FromGrainId(GrainId.FromKeyInfo(keyInfo.Key), runtime, keyInfo.GenericArgument); } else if (keyInfo.HasObserverId) { return NewObserverGrainReference(GrainId.FromKeyInfo(keyInfo.Key), GuidId.GetGuidId(keyInfo.ObserverId), runtime); } else if (keyInfo.HasTargetSilo) { return FromGrainId(GrainId.FromKeyInfo(keyInfo.Key), runtime, null, SiloAddress.New(keyInfo.TargetSilo.endpoint, keyInfo.TargetSilo.generation)); } else { return FromGrainId(GrainId.FromKeyInfo(keyInfo.Key), runtime); } } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; var serializerContext = context.Context as ISerializerContext; this.runtime = serializerContext?.ServiceProvider.GetService(typeof(IGrainReferenceRuntime)) as IGrainReferenceRuntime; } } }
// Copyright 2015, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201506; using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201506 { /// <summary> /// This code example shows how to handle RateExceededError in your /// application. To trigger the rate exceeded error, this code example runs /// 100 threads in parallel, each thread attempting to validate 100 keywords /// in a single request. Note that spawning 100 parallel threads is for /// illustrative purposes only, you shouldn't do this in your application. /// /// Tags: AdGroupAdService.mutate /// </summary> public class HandleRateExceededError: ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { HandleRateExceededError codeExample = new HandleRateExceededError(); Console.WriteLine(codeExample.Description); try { long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE"); codeExample.Run(new AdWordsUser(), adGroupId); } catch (Exception ex) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(ex)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example shows how to handle RateExceededError in your application. " + "To trigger the rate exceeded error, this code example runs 100 threads in " + "parallel, each thread attempting to validate 100 keywords in a single request. " + "Note that spawning 100 parallel threads is for illustrative purposes only, you " + "shouldn't do this in your application."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which keywords are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { const int NUM_THREADS = 100; // Increase the maximum number of parallel HTTP connections that .NET // framework allows. By default, this is set to 2 by the .NET framework. System.Net.ServicePointManager.DefaultConnectionLimit = NUM_THREADS; List<Thread> threads = new List<Thread>(); for (int i = 0; i < NUM_THREADS; i++) { Thread thread = new Thread(new KeywordThread(user, i, adGroupId).Run); threads.Add(thread); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Start(i); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Join(); } } /// <summary> /// Thread class for validating keywords. /// </summary> class KeywordThread { /// <summary> /// Index of this thread, for identifying and debugging. /// </summary> int threadIndex; /// <summary> /// The ad group id to which keywords are added. /// </summary> long adGroupId; /// <summary> /// The AdWords user who owns this ad group. /// </summary> AdWordsUser user; /// <summary> /// Number of keywords to be validated in each API call. /// </summary> const int NUM_KEYWORDS = 100; /// <summary> /// Initializes a new instance of the <see cref="KeywordThread" /> class. /// </summary> /// <param name="threadIndex">Index of the thread.</param> /// <param name="adGroupId">The ad group id.</param> /// <param name="user">The AdWords user who owns the ad group.</param> public KeywordThread(AdWordsUser user, int threadIndex, long adGroupId) { this.user = user; this.threadIndex = threadIndex; this.adGroupId = adGroupId; } /// <summary> /// Main method for the thread. /// </summary> /// <param name="obj">The thread parameter.</param> public void Run(Object obj) { // Create the operations. List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>(); for (int j = 0; j < NUM_KEYWORDS; j++) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString(); keyword.matchType = KeywordMatchType.BROAD; // Create the biddable ad group criterion. AdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion(); keywordCriterion.adGroupId = adGroupId; keywordCriterion.criterion = keyword; // Create the operations. AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation(); keywordOperation.@operator = Operator.ADD; keywordOperation.operand = keywordCriterion; operations.Add(keywordOperation); } // Get the AdGroupCriterionService. This should be done within the // thread, since a service can only handle one outgoing HTTP request // at a time. AdGroupCriterionService service = (AdGroupCriterionService) user.GetService( AdWordsService.v201506.AdGroupCriterionService); service.RequestHeader.validateOnly = true; int retryCount = 0; const int NUM_RETRIES = 3; try { while (retryCount < NUM_RETRIES) { try { // Validate the keywords. AdGroupCriterionReturnValue retval = service.mutate(operations.ToArray()); break; } catch (AdWordsApiException ex) { // Handle API errors. ApiException innerException = ex.ApiException as ApiException; if (innerException == null) { throw new Exception("Failed to retrieve ApiError. See inner exception for more " + "details.", ex); } foreach (ApiError apiError in innerException.errors) { if (!(apiError is RateExceededError)) { // Rethrow any errors other than RateExceededError. throw; } // Handle rate exceeded errors. RateExceededError rateExceededError = (RateExceededError) apiError; Console.WriteLine("Got Rate exceeded error - rate name = '{0}', scope = '{1}', " + "retry After {2} seconds.", rateExceededError.rateScope, rateExceededError.rateName, rateExceededError.retryAfterSeconds); Thread.Sleep(rateExceededError.retryAfterSeconds * 1000); retryCount = retryCount + 1; } } finally { if (retryCount == NUM_RETRIES) { throw new Exception(String.Format("Could not recover after making {0} attempts.", retryCount)); } } } } catch (Exception ex) { throw new System.ApplicationException("Failed to validate keywords.", ex); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class GridUserServicesConnector : IGridUserService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public GridUserServicesConnector() { } public GridUserServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public GridUserServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["GridUserService"]; if (gridConfig == null) { m_log.Error("[GRID USER CONNECTOR]: GridUserService missing from OpenSim.ini"); throw new Exception("GridUser connector init error"); } string serviceURI = gridConfig.GetString("GridUserServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[GRID USER CONNECTOR]: No Server URI named in section GridUserService"); throw new Exception("GridUser connector init error"); } m_ServerURI = serviceURI; } #region IGridUserService public GridUserInfo LoggedIn(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedin"; sendData["UserID"] = userID; return Get(sendData); } public bool LoggedOut(string userID, UUID region, Vector3 position, Vector3 lookat) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedout"; return Set(sendData, userID, region, position, lookat); } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "sethome"; return Set(sendData, userID, regionID, position, lookAt); } public bool SetLastPosition(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "setposition"; return Set(sendData, userID, regionID, position, lookAt); } public GridUserInfo GetGridUserInfo(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getgriduserinfo"; sendData["UserID"] = userID; return Get(sendData); } #endregion protected bool Set(Dictionary<string, object> sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt) { sendData["UserID"] = userID; sendData["RegionID"] = regionID.ToString(); sendData["Position"] = position.ToString(); sendData["LookAt"] = lookAt.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/griduser", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition reply data does not contain result field"); } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); } return false; } protected GridUserInfo Get(Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/griduser", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); GridUserInfo guinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) guinfo = new GridUserInfo((Dictionary<string, object>)replyData["result"]); } return guinfo; } else m_log.DebugFormat("[GRID USER CONNECTOR]: Loggedin received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); } return null; } } }
// *********************************************************************** // Copyright (c) 2015-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using NUnit.Common; using NUnit; using NUnit.Framework.Api; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Filters; namespace NUnitLite { /// <summary> /// TextRunner is a general purpose class that runs tests and /// outputs to a text-based user interface (TextUI). /// /// Call it from your Main like this: /// new TextRunner(textWriter).Execute(args); /// OR /// new TextUI().Execute(args); /// The provided TextWriter is used by default, unless the /// arguments to Execute override it using -out. The second /// form uses the Console, provided it exists on the platform. /// /// NOTE: When running on a platform without a Console, such /// as Windows Phone, the results will simply not appear if /// you fail to specify a file in the call itself or as an option. /// </summary> public class TextRunner : ITestListener { #region Runner Return Codes /// <summary>OK</summary> public const int OK = 0; /// <summary>Invalid Arguments</summary> public const int INVALID_ARG = -1; /// <summary>File not found</summary> public const int FILE_NOT_FOUND = -2; /// <summary>Test fixture not found - No longer in use</summary> //public const int FIXTURE_NOT_FOUND = -3; /// <summary>Invalid test suite</summary> public const int INVALID_TEST_FIXTURE = -4; /// <summary>Unexpected error occurred</summary> public const int UNEXPECTED_ERROR = -100; #endregion private Assembly _testAssembly; private ITestAssemblyRunner _runner; private NUnitLiteOptions _options; private ITestListener _teamCity = null; private TextUI _textUI; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TextRunner"/> class /// without specifying an assembly. This is interpreted as allowing /// a single input file in the argument list to Execute(). /// </summary> public TextRunner() { } /// <summary> /// Initializes a new instance of the <see cref="TextRunner"/> class /// specifying a test assembly whose tests are to be run. /// </summary> /// <param name="testAssembly"></param> /// </summary> public TextRunner(Assembly testAssembly) { _testAssembly = testAssembly; } #endregion #region Properties public ResultSummary Summary { get; private set; } #endregion #region Public Methods public int Execute(string[] args) { _options = new NUnitLiteOptions(_testAssembly == null, args); ExtendedTextWriter outWriter = null; if (_options.OutFile != null) { var outFile = Path.Combine(_options.WorkDirectory, _options.OutFile); #if NETSTANDARD1_4 var textWriter = File.CreateText(outFile); #else var textWriter = TextWriter.Synchronized(new StreamWriter(outFile)); #endif outWriter = new ExtendedTextWrapper(textWriter); Console.SetOut(outWriter); } else { outWriter = new ColorConsoleWriter(!_options.NoColor); } using (outWriter) { TextWriter errWriter = null; if (_options.ErrFile != null) { var errFile = Path.Combine(_options.WorkDirectory, _options.ErrFile); #if NETSTANDARD1_4 errWriter = File.CreateText(errFile); #else errWriter = TextWriter.Synchronized(new StreamWriter(errFile)); #endif Console.SetError(errWriter); } using (errWriter) { _textUI = new TextUI(outWriter, Console.In, _options); return Execute(); } } } // Entry point called by AutoRun and by the .NET Standard nunitlite.runner public int Execute(ExtendedTextWriter writer, TextReader reader, string[] args) { _options = new NUnitLiteOptions(_testAssembly == null, args); _textUI = new TextUI(writer, reader, _options); return Execute(); } // Internal Execute depends on _textUI and _options having been set already. private int Execute() { _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); InitializeInternalTrace(); try { if (!Directory.Exists(_options.WorkDirectory)) Directory.CreateDirectory(_options.WorkDirectory); if (_options.TeamCity) _teamCity = new TeamCityEventListener(_textUI.Writer); if (_options.ShowVersion || !_options.NoHeader) _textUI.DisplayHeader(); if (_options.ShowHelp) { _textUI.DisplayHelp(); return TextRunner.OK; } // We already showed version as a part of the header if (_options.ShowVersion) return TextRunner.OK; if (_options.ErrorMessages.Count > 0) { _textUI.DisplayErrors(_options.ErrorMessages); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return TextRunner.INVALID_ARG; } if (_testAssembly == null && _options.InputFile == null) { _textUI.DisplayError("No test assembly was specified."); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return TextRunner.OK; } _textUI.DisplayRuntimeEnvironment(); var testFile = _testAssembly != null ? AssemblyHelper.GetAssemblyPath(_testAssembly) : _options.InputFile; _textUI.DisplayTestFiles(new string[] { testFile }); if (_testAssembly == null) _testAssembly = AssemblyHelper.Load(testFile); if (_options.WaitBeforeExit && _options.OutFile != null) _textUI.DisplayWarning("Ignoring /wait option - only valid for Console"); var runSettings = MakeRunSettings(_options); LoadTests(runSettings); // We display the filters at this point so that any exception message // thrown by CreateTestFilter will be understandable. _textUI.DisplayTestFilters(); TestFilter filter = CreateTestFilter(_options); return _options.Explore ? ExploreTests(filter) : RunTests(filter, runSettings); } catch (FileNotFoundException ex) { _textUI.DisplayError(ex.Message); return FILE_NOT_FOUND; } catch (Exception ex) { _textUI.DisplayError(ex.ToString()); return UNEXPECTED_ERROR; } finally { if (_options.WaitBeforeExit) _textUI.WaitForUser("Press Enter key to continue . . ."); } } #endregion #region Helper Methods private void LoadTests(IDictionary<string, object> runSettings) { TimeStamp startTime = new TimeStamp(); _runner.Load(_testAssembly, runSettings); TimeStamp endTime = new TimeStamp(); _textUI.DisplayDiscoveryReport(startTime, endTime); } public int RunTests(TestFilter filter, IDictionary<string, object> runSettings) { var startTime = DateTime.UtcNow; ITestResult result = _runner.Run(this, filter); ReportResults(result); if (_options.ResultOutputSpecifications.Count > 0) { var outputManager = new OutputManager(_options.WorkDirectory); foreach (var spec in _options.ResultOutputSpecifications) outputManager.WriteResultFile(result, spec, runSettings, filter); } if (Summary.InvalidTestFixtures > 0) return INVALID_TEST_FIXTURE; return Summary.FailureCount + Summary.ErrorCount + Summary.InvalidCount; } public void ReportResults(ITestResult result) { Summary = new ResultSummary(result); if (Summary.ExplicitCount + Summary.SkipCount + Summary.IgnoreCount > 0) _textUI.DisplayNotRunReport(result); if (result.ResultState.Status == TestStatus.Failed || result.ResultState.Status == TestStatus.Warning) _textUI.DisplayErrorsFailuresAndWarningsReport(result); #if FULL if (_options.Full) _textUI.PrintFullReport(_result); #endif _textUI.DisplayRunSettings(); _textUI.DisplaySummaryReport(Summary); } private int ExploreTests(ITestFilter filter) { ITest testNode = _runner.ExploreTests(filter); var specs = _options.ExploreOutputSpecifications; if (specs.Count == 0) new TestCaseOutputWriter().WriteTestFile(testNode, Console.Out); else { var outputManager = new OutputManager(_options.WorkDirectory); foreach (var spec in _options.ExploreOutputSpecifications) outputManager.WriteTestFile(testNode, spec); } return OK; } /// <summary> /// Make the settings for this run - this is public for testing /// </summary> public static Dictionary<string, object> MakeRunSettings(NUnitLiteOptions options) { // Transfer command line options to run settings var runSettings = new Dictionary<string, object>(); if (options.PreFilters.Count > 0) runSettings[FrameworkPackageSettings.LOAD] = options.PreFilters; else if (options.TestList.Count > 0) { var prefilters = new List<string>(); foreach (var testName in options.TestList) { int end = testName.IndexOfAny(new char[] { '(', '<' }); if (end > 0) prefilters.Add(testName.Substring(0, end)); else prefilters.Add(testName); } runSettings[FrameworkPackageSettings.LOAD] = prefilters; } if (options.NumberOfTestWorkers >= 0) runSettings[FrameworkPackageSettings.NumberOfTestWorkers] = options.NumberOfTestWorkers; if (options.InternalTraceLevel != null) runSettings[FrameworkPackageSettings.InternalTraceLevel] = options.InternalTraceLevel; if (options.RandomSeed >= 0) runSettings[FrameworkPackageSettings.RandomSeed] = options.RandomSeed; if (options.WorkDirectory != null) runSettings[FrameworkPackageSettings.WorkDirectory] = Path.GetFullPath(options.WorkDirectory); if (options.DefaultTimeout >= 0) runSettings[FrameworkPackageSettings.DefaultTimeout] = options.DefaultTimeout; if (options.StopOnError) runSettings[FrameworkPackageSettings.StopOnError] = true; if (options.DefaultTestNamePattern != null) runSettings[FrameworkPackageSettings.DefaultTestNamePattern] = options.DefaultTestNamePattern; if (options.TestParameters.Count != 0) runSettings[FrameworkPackageSettings.TestParametersDictionary] = options.TestParameters; return runSettings; } /// <summary> /// Create the test filter for this run - public for testing /// </summary> /// <param name="options"></param> /// <returns></returns> public static TestFilter CreateTestFilter(NUnitLiteOptions options) { var filter = TestFilter.Empty; if (options.TestList.Count > 0) { var testFilters = new List<TestFilter>(); foreach (var test in options.TestList) testFilters.Add(new FullNameFilter(test)); filter = testFilters.Count > 1 ? new OrFilter(testFilters.ToArray()) : testFilters[0]; } if (options.WhereClauseSpecified) { string xmlText = new TestSelectionParser().Parse(options.WhereClause); var whereFilter = TestFilter.FromXml(TNode.FromXml(xmlText)); filter = filter.IsEmpty ? whereFilter : new AndFilter(filter, whereFilter); } return filter; } private void InitializeInternalTrace() { var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true); if (traceLevel != InternalTraceLevel.Off) { var logName = GetLogFileName(); StreamWriter streamWriter = null; if (traceLevel > InternalTraceLevel.Off) { string logPath = Path.Combine(Directory.GetCurrentDirectory(), logName); streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write)); streamWriter.AutoFlush = true; } InternalTrace.Initialize(streamWriter, traceLevel); } } private string GetLogFileName() { const string logFileFormat = "InternalTrace.{0}.{1}.{2}"; // Some mobiles don't have an Open With menu item, // so we use .txt, which is opened easily. const string ext = "log"; var baseName = _testAssembly != null ? _testAssembly.GetName().Name : _options.InputFile != null ? Path.GetFileNameWithoutExtension(_options.InputFile) : "NUnitLite"; #if NETSTANDARD1_4 var id = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); #else var id = Process.GetCurrentProcess().Id; #endif return string.Format(logFileFormat, id, baseName, ext); } #endregion #region ITestListener Members /// <summary> /// Called when a test or suite has just started /// </summary> /// <param name="test">The test that is starting</param> public void TestStarted(ITest test) { if (_teamCity != null) _teamCity.TestStarted(test); _textUI.TestStarted(test); } /// <summary> /// Called when a test has finished /// </summary> /// <param name="result">The result of the test</param> public void TestFinished(ITestResult result) { if (_teamCity != null) _teamCity.TestFinished(result); _textUI.TestFinished(result); } /// <summary> /// Called when a test produces output for immediate display /// </summary> /// <param name="output">A TestOutput object containing the text to display</param> public void TestOutput(TestOutput output) { _textUI.TestOutput(output); } /// <summary> /// Called when a test produces a message to be sent to listeners /// </summary> /// <param name="message">A TestMessage object containing the text to send</param> public void SendMessage(TestMessage message) { } #endregion } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Builders.Execute; using FluentMigrator.Model; using FluentMigrator.Runner; using FluentMigrator.Runner.Processors.SqlServer; namespace FluentMigrator.SchemaDump.SchemaDumpers { public class SqlServerSchemaDumper : ISchemaDumper { public virtual IAnnouncer Announcer { get; set; } public SqlServerProcessor Processor { get; set; } public SqlServerSchemaDumper(SqlServerProcessor processor, IAnnouncer announcer) { Announcer = announcer; Processor = processor; } public virtual void Execute(string template, params object[] args) { Processor.Execute(template, args); } public virtual bool Exists(string template, params object[] args) { return Processor.Exists(template, args); } public virtual DataSet ReadTableData(string tableName) { return Processor.Read("SELECT * FROM [{0}]", tableName); } public virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); } public virtual void Process(PerformDBOperationExpression expression) { Processor.Process(expression); } public virtual IList<TableDefinition> ReadDbSchema() { IList<TableDefinition> tables = ReadTables(); foreach (TableDefinition table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables; } protected virtual IList<TableDefinition> ReadTables() { const string query = @"SELECT OBJECT_SCHEMA_NAME(t.[object_id],DB_ID()) AS [Schema], t.name AS [Table], c.[Name] AS ColumnName, t.object_id AS [TableID], c.column_id AS [ColumnID], def.definition AS [DefaultValue], c.[system_type_id] AS [TypeID], c.[user_type_id] AS [UserTypeID], c.[max_length] AS [Length], c.[precision] AS [Precision], c.[scale] AS [Scale], c.[is_identity] AS [IsIdentity], c.[is_nullable] AS [IsNullable], CASE WHEN EXISTS(SELECT 1 FROM sys.foreign_key_columns fkc WHERE t.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id) THEN 1 ELSE 0 END AS IsForeignKey, CASE WHEN EXISTS(select 1 from sys.index_columns ic WHERE t.object_id = ic.object_id AND c.column_id = ic.column_id) THEN 1 ELSE 0 END AS IsIndexed ,CASE WHEN kcu.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimaryKey , CASE WHEN EXISTS(select stc.CONSTRAINT_NAME, skcu.TABLE_NAME, skcu.COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS stc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE skcu ON skcu.CONSTRAINT_NAME = stc.CONSTRAINT_NAME WHERE stc.CONSTRAINT_TYPE = 'UNIQUE' AND skcu.TABLE_NAME = t.name AND skcu.COLUMN_NAME = c.name) THEN 1 ELSE 0 END AS IsUnique ,pk.name AS PrimaryKeyName FROM sys.all_columns c JOIN sys.tables t ON c.object_id = t.object_id AND t.type = 'u' LEFT JOIN sys.default_constraints def ON c.default_object_id = def.object_id LEFT JOIN sys.key_constraints pk ON t.object_id = pk.parent_object_id AND pk.type = 'PK' LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON t.name = kcu.TABLE_NAME AND c.name = kcu.COLUMN_NAME AND pk.name = kcu.CONSTRAINT_NAME ORDER BY t.name, c.column_id"; DataSet ds = Read(query); DataTable dt = ds.Tables[0]; IList<TableDefinition> tables = new List<TableDefinition>(); foreach (DataRow dr in dt.Rows) { List<TableDefinition> matches = (from t in tables where t.Name == dr["Table"].ToString() && t.SchemaName == dr["Schema"].ToString() select t).ToList(); TableDefinition tableDef = null; if (matches.Count > 0) tableDef = matches[0]; // create the table if not found if (tableDef == null) { tableDef = new TableDefinition { Name = dr["Table"].ToString(), SchemaName = dr["Schema"].ToString() }; tables.Add(tableDef); } //find the column List<ColumnDefinition> cmatches = (from c in tableDef.Columns where c.Name == dr["ColumnName"].ToString() select c).ToList(); ColumnDefinition colDef = null; if (cmatches.Count > 0) colDef = cmatches[0]; if (colDef == null) { //need to create and add the column tableDef.Columns.Add(new ColumnDefinition { Name = dr["ColumnName"].ToString(), CustomType = "", //TODO: set this property DefaultValue = dr.IsNull("DefaultValue") ? "" : dr["DefaultValue"].ToString(), IsForeignKey = dr["IsForeignKey"].ToString() == "1", IsIdentity = dr["IsIdentity"].ToString() == "True", IsIndexed = dr["IsIndexed"].ToString() == "1", IsNullable = dr["IsNullable"].ToString() == "True", IsPrimaryKey = dr["IsPrimaryKey"].ToString() == "1", IsUnique = dr["IsUnique"].ToString() == "1", Precision = int.Parse(dr["Precision"].ToString()), PrimaryKeyName = dr.IsNull("PrimaryKeyName") ? "" : dr["PrimaryKeyName"].ToString(), Size = int.Parse(dr["Length"].ToString()), TableName = dr["Table"].ToString(), Type = GetDbType(int.Parse(dr["TypeID"].ToString())), //TODO: set this property ModificationType = ColumnModificationType.Create }); } } return tables; } protected virtual DbType GetDbType(int typeNum) { var types = new Dictionary<int, DbType>() { {34, DbType.Binary}, {35, DbType.AnsiString}, {36, DbType.Guid}, {40, DbType.Date}, {41, DbType.Time}, {42, DbType.DateTime2}, {43, DbType.DateTimeOffset}, {48, DbType.Byte}, {52, DbType.Int16}, {56, DbType.Int32}, //{58, DbType.}, //smalldatetime {59, DbType.Single}, {60, DbType.Currency}, {61, DbType.DateTime}, {62, DbType.Double}, //{98, DbType.}, //sql_variant {99, DbType.String}, {104, DbType.Boolean}, {106, DbType.Decimal}, //{108, DbType.}, //numeric //{122, DbType.}, //smallmoney {127, DbType.Int64}, //{240, DbType.}, //hierarchyid //{240, DbType.}, //geometry //{240, DbType.}, //geography {165, DbType.Binary}, {167, DbType.AnsiString}, {173, DbType.Binary}, {175, DbType.AnsiStringFixedLength}, //{189, DbType.}, //Timestamp {231, DbType.String}, {239, DbType.StringFixedLength}, {241, DbType.Xml} //{231, DbType.} //Sysname }; DbType value; if (types.TryGetValue(typeNum, out value)) { return value; } else { throw new KeyNotFoundException(typeNum + " was not found!"); } } protected virtual IList<IndexDefinition> ReadIndexes(string schemaName, string tableName) { const string query = @"SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema], T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name], I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical], I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] FROM sys.[tables] AS T INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.object_id = OBJECT_ID('[{0}].[{1}]') ORDER BY T.[name], I.[index_id], IC.[key_ordinal]"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<IndexDefinition> indexes = new List<IndexDefinition>(); foreach (DataRow dr in dt.Rows) { List<IndexDefinition> matches = (from i in indexes where i.Name == dr["index_name"].ToString() && i.SchemaName == dr["Schema"].ToString() select i).ToList(); IndexDefinition iDef = null; if (matches.Count > 0) iDef = matches[0]; // create the table if not found if (iDef == null) { iDef = new IndexDefinition { Name = dr["index_name"].ToString(), SchemaName = dr["Schema"].ToString(), IsClustered = dr["type_desc"].ToString() == "CLUSTERED", IsUnique = dr["is_unique"].ToString() == "1", TableName = dr["table_name"].ToString() }; indexes.Add(iDef); } // columns ICollection<IndexColumnDefinition> ms = (from m in iDef.Columns where m.Name == dr["column_name"].ToString() select m).ToList(); if (ms.Count == 0) { iDef.Columns.Add(new IndexColumnDefinition { Name = dr["column_name"].ToString(), Direction = dr["is_descending_key"].ToString() == "1" ? Direction.Descending : Direction.Ascending }); } } return indexes; } protected virtual IList<ForeignKeyDefinition> ReadForeignKeys(string schemaName, string tableName) { const string query = @"SELECT C.CONSTRAINT_SCHEMA AS Contraint_Schema, C.CONSTRAINT_NAME AS Constraint_Name, FK.CONSTRAINT_SCHEMA AS ForeignTableSchema, FK.TABLE_NAME AS FK_Table, CU.COLUMN_NAME AS FK_Column, PK.CONSTRAINT_SCHEMA as PrimaryTableSchema, PK.TABLE_NAME AS PK_Table, PT.COLUMN_NAME AS PK_Column FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME = '{1}' AND PK.CONSTRAINT_SCHEMA = '{0}' ORDER BY Constraint_Name"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<ForeignKeyDefinition> keys = new List<ForeignKeyDefinition>(); foreach (DataRow dr in dt.Rows) { List<ForeignKeyDefinition> matches = (from i in keys where i.Name == dr["Constraint_Name"].ToString() select i).ToList(); ForeignKeyDefinition d = null; if (matches.Count > 0) d = matches[0]; // create the table if not found if (d == null) { d = new ForeignKeyDefinition { Name = dr["Constraint_Name"].ToString(), ForeignTableSchema = dr["ForeignTableSchema"].ToString(), ForeignTable = dr["FK_Table"].ToString(), PrimaryTable = dr["PK_Table"].ToString(), PrimaryTableSchema = dr["PrimaryTableSchema"].ToString() }; keys.Add(d); } // Foreign Columns ICollection<string> ms = (from m in d.ForeignColumns where m == dr["FK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.ForeignColumns.Add(dr["FK_Column"].ToString()); // Primary Columns ms = (from m in d.PrimaryColumns where m == dr["PK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.PrimaryColumns.Add(dr["PK_Column"].ToString()); } return keys; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public class DiscretionaryAcl_RemoveAccessSpecific { public static IEnumerable<object[]> DiscretionaryACL_RemoveAccessSpecific() { yield return new object[] { true, false, 1, "BA", 1, 0, 0, "0:1:1:BA:false:0#0:1:1:BG:false:0#0:1:1:BO:false:0 ", "0:1:1:BG:false:0#0:1:1:BO:false:0" }; yield return new object[] { true, false, 1, "BO", 1, 0, 0, "0:1:1:BA:false:0#0:1:1:BG:false:0#0:1:1:BO:false:0 ", "0:1:1:BA:false:0#0:1:1:BG:false:0" }; yield return new object[] { true, false, 1, "BG", 1, 0, 0, "0:1:1:BA:false:0#0:1:1:BG:false:0#0:1:1:BO:false:0 ", "0:1:1:BA:false:0#0:1:1:BO:false:0" }; yield return new object[] { true, false, 0, "BA", 1, 0, 0, "0:0:1:BA:false:0#0:0:1:BA:false:0#0:0:1:BA:false:0#0:0:1:BO:false:0", "0:0:1:BO:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 0, "16:1:1:BA:false:0 ", "16:1:1:BA:false:0 " }; yield return new object[] { true, false, 0, "BA", 1, 0, 0, "0:1:1:BA:false:0 ", "0:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 0, "0:0:1:BA:false:0 ", "0:0:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 0, "0:1:1:BO:false:0 ", "0:1:1:BO:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 0, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 1, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 3, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 4, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 1, 0, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 3, 1, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 4, 1, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 3, 3, "15:1:3:BA:false:0 ", "15:1:3:BA:false:0 " }; } private static bool TestRemoveAccessSpecific(DiscretionaryAcl discretionaryAcl, RawAcl rawAcl, AccessControlType accessControlType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { bool result = true; byte[] dAclBinaryForm = null; byte[] rAclBinaryForm = null; discretionaryAcl.RemoveAccessSpecific(accessControlType, sid, accessMask, inheritanceFlags, propagationFlags); if (discretionaryAcl.Count == rawAcl.Count && discretionaryAcl.BinaryLength == rawAcl.BinaryLength) { dAclBinaryForm = new byte[discretionaryAcl.BinaryLength]; rAclBinaryForm = new byte[rawAcl.BinaryLength]; discretionaryAcl.GetBinaryForm(dAclBinaryForm, 0); rawAcl.GetBinaryForm(rAclBinaryForm, 0); if (!Utils.IsBinaryFormEqual(dAclBinaryForm, rAclBinaryForm)) result = false; //redundant index check for (int i = 0; i < discretionaryAcl.Count; i++) { if (!Utils.IsAceEqual(discretionaryAcl[i], rawAcl[i])) { result = false; break; } } } else result = false; return result; } [Theory] [MemberData(nameof(DiscretionaryACL_RemoveAccessSpecific))] public static void RemoveAccessSpecific(bool isContainer, bool isDS, int accessControlType, string sid, int accessMask, int inheritanceFlags, int propagationFlags, string initialRawAclStr, string verifierRawAclStr) { RawAcl rawAcl = Utils.CreateRawAclFromString(initialRawAclStr); DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); rawAcl = Utils.CreateRawAclFromString(verifierRawAclStr); Assert.True(TestRemoveAccessSpecific(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags)); } [Fact] public static void RemoveAccessSpecific_AdditionalTestCases() { RawAcl rawAcl = null; DiscretionaryAcl discretionaryAcl = null; bool isContainer = false; bool isDS = false; int accessControlType = 0; string sid = null; int accessMask = 1; int inheritanceFlags = 0; int propagationFlags = 0; GenericAce gAce = null; byte[] opaque = null; //Case 1, remove one ACE from the DiscretionaryAcl with no ACE isContainer = true; isDS = false; accessControlType = 1; sid = "BA"; accessMask = 1; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); Assert.True(TestRemoveAccessSpecific(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags)) ; //Case 2, remove the last one ACE from the DiscretionaryAcl isContainer = true; isDS = false; accessControlType = 0; sid = "BA"; accessMask = 1; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); //15 = AceFlags.ObjectInherit |AceFlags.ContainerInherit | AceFlags.NoPropagateInherit | AceFlags.InheritOnly gAce = new CommonAce((AceFlags)15, AceQualifier.AccessAllowed, accessMask, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(rawAcl.Count, gAce); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); //remove the ace to create the validation rawAcl rawAcl.RemoveAce(rawAcl.Count - 1); Assert.True(TestRemoveAccessSpecific(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags)) ; //Case 3, accessMask = 0 AssertExtensions.Throws<ArgumentException>("accessMask", () => { isContainer = true; isDS = false; accessControlType = 1; sid = "BA"; accessMask = 0; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.RemoveAccessSpecific((AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 4, null sid Assert.Throws<ArgumentNullException>(() => { isContainer = true; isDS = false; accessControlType = 1; accessMask = 1; sid = "BA"; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.RemoveAccessSpecific((AccessControlType)accessControlType, null, accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 5, all the ACEs in the Dacl are non-qualified ACE, no remove isContainer = true; isDS = false; inheritanceFlags = 1;//InheritanceFlags.ContainerInherit propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 0; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); opaque = new byte[4]; gAce = new CustomAce(AceType.MaxDefinedAceType + 1, AceFlags.InheritanceFlags, opaque); ; rawAcl.InsertAce(0, gAce); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); //After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and //forbid the modification on uncanonical ACL, this case will throw InvalidOperationException Assert.Throws<InvalidOperationException>(() => { TestRemoveAccessSpecific (discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 7, Remove Specific Ace of NOT(AccessControlType.Allow |AccessControlType.Denied) to the DiscretionaryAcl with no ACE, // should throw appropriate exception for wrong parameter, bug#287188 Assert.Throws<ArgumentOutOfRangeException>(() => { isContainer = true; isDS = false; inheritanceFlags = 1;//InheritanceFlags.ContainerInherit propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 100; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.RemoveAccessSpecific((AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using Adxstudio.Xrm.AspNet; using Adxstudio.Xrm.Metadata; using Adxstudio.Xrm.Services; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using Adxstudio.Xrm.Web; namespace Adxstudio.Xrm.EventHubBasedInvalidation { /// <summary> /// Handles the interaction with CRM /// </summary> internal sealed class CrmChangeTrackingManager { private Guid organizationId; private OrganizationServiceContext organizationServiceContext; private static CrmChangeTrackingManager crmChangeTrackingManager; private readonly ConcurrentDictionary<string, EntityTrackingInfo> entityInfoList; private List<string> searchEnabledEntities = new List<string>(); /// <summary> /// Special cased entities and their corresponding name attributes /// </summary> private static readonly IDictionary<string, string> targetNames = new Dictionary<string, string> { { "adx_sitesetting", "adx_name" }, { "adx_setting", "adx_name" }, }; /// <summary> /// Keep a local refrence of the Processing Entity table /// </summary> private Dictionary<string, EntityRecordMessage> processingEntities; /// <summary> /// Gets the instance of this class /// </summary> public static CrmChangeTrackingManager Instance { get { return CrmChangeTrackingManager.crmChangeTrackingManager ?? (CrmChangeTrackingManager.crmChangeTrackingManager = new CrmChangeTrackingManager()); } } /// <summary> /// private constructor /// </summary> private CrmChangeTrackingManager() { this.entityInfoList = new ConcurrentDictionary<string, EntityTrackingInfo>(); } /// <summary> /// Update entities with initial timestamp, this will ensure that we are only getting the changes that we need /// </summary> /// <param name="updatedEntites">Entites that have Added/Modified records</param> private void UpdateTimeStamp(Dictionary<string, string> updatedEntites) { OrderExpression order = new OrderExpression(); order.AttributeName = "versionnumber"; order.OrderType = OrderType.Descending; var executeMulti = new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = true }, Requests = new OrganizationRequestCollection() }; List<RetrieveMultipleRequest> mRequests = new List<RetrieveMultipleRequest>(); foreach (KeyValuePair<string, string> entity in updatedEntites) { if (entity.Value == string.Empty || entity.Value == null) { QueryExpression query = new QueryExpression() { EntityName = entity.Key, ColumnSet = new ColumnSet("versionnumber"), PageInfo = new PagingInfo() { Count = 10, PageNumber = 1 } }; query.Orders.Add(order); var request = new RetrieveMultipleRequest() { Query = query }; mRequests.Add(request); } } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Number of timestamp query requests {0}", mRequests.Count.ToString())); if (mRequests.Count > 0) { executeMulti.Requests.AddRange(mRequests); var response = (ExecuteMultipleResponse)this.OrganizationServiceContext.Execute(executeMulti); foreach (ExecuteMultipleResponseItem item in response.Responses) { if (item.Response != null && item.Response.Results.Count > 0) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Result count for response {0}", item.Response.Results.Count)); EntityCollection collection = item.Response.Results.FirstOrDefault().Value as EntityCollection; if (collection != null && collection.Entities.Count > 0) { int index = collection.Entities.Count - 1; if (collection[index].Attributes.Contains("versionnumber")) { var timestamp = collection[index].Attributes["versionnumber"].ToString(); int currentVersionNumber; if (int.TryParse(timestamp, out currentVersionNumber)) { var prevVersionNumber = currentVersionNumber - 1; timestamp = prevVersionNumber.ToString(); } var timestampToken = timestamp + "!" + WebAppConfigurationProvider.AppStartTime; updatedEntites[collection[index].LogicalName] = timestampToken; ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Last timestamp token set for Entity {0} {1}", collection[index].LogicalName, timestampToken)); } } } } } } /// <summary> /// Requests the record changed info since the given timeStamp from CRM /// </summary> /// <param name="entitiesWithLastTimestamp">entities with the timestamp to use to get the delta</param> /// <returns>The changed entity information</returns> internal TimeBasedChangedData RequestRecordDeltaFromCrm(Dictionary<string, string> entitiesWithLastTimestamp, CrmDbContext context, Guid websiteId) { try { //Keep a local refrence of the Processing table processingEntities = NotificationUpdateManager.Instance.ProcessingEntitiesTable(); UpdateTimeStamp(entitiesWithLastTimestamp); var request = ExecuteMultipleRequest(entitiesWithLastTimestamp); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Running 'ExecuteMultipleRequest' with {0} requests.", request.Requests.Count().ToString())); var entities = string.Join(",", entitiesWithLastTimestamp.Keys); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Retrieving changes for entities = {0}.", entities)); var response = (ExecuteMultipleResponse)context.Service.Execute(request); if (response == null || response.Responses == null) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Got null response while processing the requests")); return null; } if (response.IsFaulted) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Got faulted response from '{0}' while processing atleast one of the message requests", response.ResponseName)); } var responseCollection = new Dictionary<string, RetrieveEntityChangesResponse>(); for (var i = 0; i < request.Requests.Count && i < response.Responses.Count; i++) { var entityChangeRequest = request.Requests[i] as RetrieveEntityChangesRequest; var resp = response.Responses[i]; if (resp.Fault != null) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("RetrieveEntityChangesRequest faulted for entity '{0}'. Message: '{1}' ", entityChangeRequest.EntityName, resp.Fault.Message)); continue; } responseCollection.Add(entityChangeRequest.EntityName, response.Responses[i].Response as RetrieveEntityChangesResponse); } return ParseBusinessEntityChangesResponse(responseCollection, context, websiteId); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString()); } return null; } /// <summary> /// Create request for getting RetrieveEntityChanges for entities /// </summary> /// <param name="entitiesWithLastTimestamp">Entities with last update timestamp, for which we shoud get updated records</param> /// <returns>ExecuteMultipleRequest for executing</returns> private ExecuteMultipleRequest ExecuteMultipleRequest(Dictionary<string, string> entitiesWithLastTimestamp) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Creating request for getting Retrieve entity changes for entities.")); var requests = entitiesWithLastTimestamp.Select(updatedEntity => new RetrieveEntityChangesRequest() { EntityName = updatedEntity.Key, DataVersion = updatedEntity.Value, Columns = GetColumnSet(updatedEntity.Key), PageInfo = new PagingInfo() }).ToList(); var requestWithResults = new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = true }, Requests = new OrganizationRequestCollection() }; requestWithResults.Requests.AddRange(requests); return requestWithResults; } /// <summary> /// Get Column Set /// </summary> /// <param name="entityName">entity Name</param> /// <returns>Return column set having only ID column or set it to pull all columns</returns> private ColumnSet GetColumnSet(string entityName) { string primaryKeyAttribute = this.TryGetPrimaryKey(entityName); ColumnSet columns = new ColumnSet(); if (string.IsNullOrEmpty(primaryKeyAttribute)) { columns.AllColumns = true; } else { columns.AddColumn(primaryKeyAttribute); SetAdditionalColumns(entityName, columns); } return columns; } /// <summary> /// Set the additional columns. Associate & disassociate message will have related entities. The primary key attribute related to /// related entities also needs to be added into the columns set /// </summary> /// <param name="entityName">Primary Entity</param> /// <param name="columns">Column set</param> private void SetAdditionalColumns(string entityName, ColumnSet columns) { //check the type of message for the respective entityName var message = this.processingEntities[entityName] as AssociateDisassociateMessage; //if the message is of AssociateDisassociateMessage type add related entities key attributes also. if (message != null) { //add related entity 1 AddColumn(columns, message.RelatedEntity1Name); //add related entity 2 AddColumn(columns, message.RelatedEntity2Name); } //add primary name attribute string primaryNameAttribute = this.TryGetPrimaryNameAttribute(entityName); if (!string.IsNullOrEmpty(primaryNameAttribute)) { columns.AddColumn(primaryNameAttribute); } // add website lookup attribute EntityTrackingInfo info; if (entityInfoList.TryGetValue(entityName, out info) && info.WebsiteLookupAttribute != null) { columns.AddColumn(info.WebsiteLookupAttribute); } } /// <summary> /// Add primary key attribute to column set /// </summary> /// <param name="columns">column set</param> /// <param name="relatedEntityName">related Entity Name</param> private void AddColumn(ColumnSet columns, string relatedEntityName) { string primaryKeyAttribute = this.TryGetPrimaryKey(relatedEntityName); if (!string.IsNullOrEmpty(primaryKeyAttribute)) { columns.AddColumn(primaryKeyAttribute); } } /// <summary> /// Parse CRM response to get list of updated entities with timestamps and list of updated records /// </summary> /// <param name="responseCollection">Dictionary for entityName and its RetrieveEntityChange response to parse</param> /// <returns>List of updated records</returns> private TimeBasedChangedData ParseBusinessEntityChangesResponse(Dictionary<string, RetrieveEntityChangesResponse> responseCollection, CrmDbContext context, Guid websiteId) { if (responseCollection == null || responseCollection.Count == 0) { return null; } var changedData = new TimeBasedChangedData { UpdatedEntitiesWithLastTimestamp = new Dictionary<string, string>(), UpdatedEntityRecords = new List<IChangedItem>() }; foreach (var kvp in responseCollection) { var entityName = kvp.Key; var dataToken = kvp.Value.EntityChanges.DataToken; ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RetrieveEntityChangesResponse received for entity: {0} with new data token: {1}", entityName, dataToken)); KeyValuePair<string, string>? entityNameWithTimestamp = new KeyValuePair<string, string>(entityName, dataToken); if (changedData.UpdatedEntitiesWithLastTimestamp.ContainsKey(entityNameWithTimestamp.Value.Key)) { continue; } changedData.UpdatedEntitiesWithLastTimestamp.Add(entityNameWithTimestamp.Value.Key, entityNameWithTimestamp.Value.Value); } changedData.UpdatedEntityRecords.AddRange(this.GetChangesRelatedToWebsite(responseCollection, context, websiteId)); return changedData; } /// <summary> /// Get changes that belongs to current website. /// </summary> /// <param name="responseCollection">Entity changes response collection.</param> /// <param name="context">Crm DB context.</param> /// <param name="websiteId">Current website id.</param> /// <returns>Changes that belongs to website.</returns> private IEnumerable<IChangedItem> GetChangesRelatedToWebsite(Dictionary<string, RetrieveEntityChangesResponse> responseCollection, CrmDbContext context, Guid websiteId) { var changedItemList = new List<IChangedItem>(); var groupedChanges = responseCollection .SelectMany(kvp => kvp.Value.EntityChanges.Changes) .GroupBy(change => this.GetEntityIdFromChangeItem(change)); foreach (var itemGroup in groupedChanges) { try { if (this.ChangesBelongsToWebsite(itemGroup, context, websiteId)) { changedItemList.AddRange(itemGroup); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Changes regarding entity (id: {itemGroup.Key.ToString()}) don't belong to website {websiteId.ToString()}"); } } catch (Exception ex) { WebEventSource.Log.GenericErrorException(ex); } } return changedItemList; } /// <summary> /// Gets entity id from changed item. /// </summary> /// <param name="item">Changed item.</param> /// <returns></returns> private Guid GetEntityIdFromChangeItem(IChangedItem item) { return item.Type == ChangeType.NewOrUpdated ? (item as NewOrUpdatedItem).NewOrUpdatedEntity.Id : (item as RemovedOrDeletedItem).RemovedItem.Id; } /// <summary> /// Gets entity name from changed item. /// </summary> /// <param name="item">Changed item.</param> /// <returns>Casted entity.</returns> private string GetEntityNameFromChangedItem(IChangedItem item) { return item.Type == ChangeType.NewOrUpdated ? (item as NewOrUpdatedItem).NewOrUpdatedEntity.LogicalName : (item as RemovedOrDeletedItem).RemovedItem.LogicalName; } /// <summary> /// Check that changes grouped by entity id belongs to website. /// </summary> /// <param name="groupedChanges">Changes grouped by entity id.</param> /// <param name="context">Crm DB context.</param> /// <param name="websiteId">Website id.</param> /// <returns></returns> private bool ChangesBelongsToWebsite(IGrouping<Guid, IChangedItem> groupedChanges, CrmDbContext context, Guid websiteId) { var entityId = groupedChanges.Key; var entityName = this.GetEntityNameFromChangedItem(groupedChanges.First()); if (string.Equals("adx_website", entityName, StringComparison.OrdinalIgnoreCase)) { return websiteId == entityId; } // if entity hasn't relationship with website or entity was deleted -> mark as `belongs to website` EntityTrackingInfo info; if (groupedChanges.Any(gc => gc.Type == ChangeType.RemoveOrDeleted) || !entityInfoList.TryGetValue(entityName, out info) || info.WebsiteLookupAttribute == null) { return true; } // trying to get website's id from changed items var itemWithWebsiteIdValue = groupedChanges .OfType<NewOrUpdatedItem>() .FirstOrDefault(item => item.NewOrUpdatedEntity.Contains(info.WebsiteLookupAttribute)); // if all changes doesn't contain website lookup attribute but we know that entity should have it then try to get value from service context var updatedEntity = itemWithWebsiteIdValue != null ? itemWithWebsiteIdValue.NewOrUpdatedEntity : context.Service.RetrieveSingle(new EntityReference(entityName, entityId), new ColumnSet(info.WebsiteLookupAttribute)); return updatedEntity?.GetAttributeValue<EntityReference>(info.WebsiteLookupAttribute)?.Id == websiteId; } /// <summary> /// Returns the primary key for the given entity /// </summary> /// <param name="entityName">entity to get the primary key for</param> /// <returns>primary key attribute name if found, otherwise null</returns> internal string TryGetPrimaryKey(string entityName) { EntityTrackingInfo trackingInfo = null; // if entity name is null return; if (string.IsNullOrEmpty(entityName)) { ADXTrace.Instance.TraceError(TraceCategory.Application, "TryGetPrimaryKey: the entity name is null"); return null; } else if (!entityInfoList.TryGetValue(entityName, out trackingInfo)) { var entityTrackingInfo = this.GetWebsiteLookupEntityTrackingInfo(entityName); if (entityTrackingInfo != null) { entityInfoList.AddOrUpdate(entityName, entityTrackingInfo, (name, info) => entityTrackingInfo); return entityTrackingInfo.EntityKeyAttribute; } return null; } return trackingInfo.EntityKeyAttribute; } /// <summary> /// Get <see cref="EntityTrackingInfo"/> for entity. /// </summary> /// <param name="entityName">Name of entity.</param> /// <returns>Info about entity or null.</returns> private EntityTrackingInfo GetWebsiteLookupEntityTrackingInfo(string entityName) { // ignore relationships for adx_website entity var isWebsiteEntity = string.Equals(entityName, "adx_website", StringComparison.OrdinalIgnoreCase); var metadata = isWebsiteEntity ? this.OrganizationServiceContext.GetEntityMetadata(entityName) : this.OrganizationServiceContext.GetEntityMetadata(entityName, EntityFilters.Attributes | EntityFilters.Relationships); if (metadata == null) { return null; } // try get relationship to a website var websiteRelationship = isWebsiteEntity ? null : metadata.ManyToOneRelationships.FirstOrDefault(r => string.Equals(r.ReferencedEntity, "adx_website", StringComparison.OrdinalIgnoreCase)); return new EntityTrackingInfo { EntityKeyAttribute = metadata.PrimaryIdAttribute, WebsiteLookupAttribute = websiteRelationship?.ReferencingAttribute.Equals("adx_websiteid", StringComparison.CurrentCultureIgnoreCase) == true ? "adx_websiteid" : null }; } /// <summary> /// Get the Name attribute of the entity. /// </summary> /// <param name="entityName">Entity to get the name </param> /// <returns>Entity's Name attribute</returns> private string TryGetPrimaryNameAttribute(string entityName) { // for particular entities, return the value of the primary name attribute string name; return targetNames.TryGetValue(entityName, out name) ? name : null; } /// <summary> /// Returns an instance of the OrganizationServiceContext /// </summary> public OrganizationServiceContext OrganizationServiceContext { get { return this.organizationServiceContext ?? (this.organizationServiceContext = PortalCrmConfigurationManager.CreateServiceContext()); } } /// <summary> /// Gets the Organization Id /// </summary> /// <returns>Organization Id</returns> public Guid OrganizationId { get { return this.organizationId = ((WhoAmIResponse)this.OrganizationServiceContext.Execute(new WhoAmIRequest())).OrganizationId; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Document = Lucene.Net.Documents.Document; using Fieldable = Lucene.Net.Documents.Fieldable; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using RAMOutputStream = Lucene.Net.Store.RAMOutputStream; namespace Lucene.Net.Index { sealed class FieldsWriter { internal const byte FIELD_IS_TOKENIZED = (byte) (0x1); internal const byte FIELD_IS_BINARY = (byte) (0x2); internal const byte FIELD_IS_COMPRESSED = (byte) (0x4); // Original format internal const int FORMAT = 0; // Changed strings to UTF8 internal const int FORMAT_VERSION_UTF8_LENGTH_IN_BYTES = 1; // NOTE: if you introduce a new format, make it 1 higher // than the current one, and always change this if you // switch to a new format! internal const int FORMAT_CURRENT = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES; private FieldInfos fieldInfos; private IndexOutput fieldsStream; private IndexOutput indexStream; private bool doClose; internal FieldsWriter(Directory d, System.String segment, FieldInfos fn) { fieldInfos = fn; bool success = false; string fieldsName = segment + "." + IndexFileNames.FIELDS_EXTENSION; try { fieldsStream = d.CreateOutput(fieldsName); fieldsStream.WriteInt(FORMAT_CURRENT); success = true; } finally { if (!success) { try { Close(); } catch (System.Exception) { // Suppress so we keep throwing the original exception } try { d.DeleteFile(fieldsName); } catch (System.Exception) { // Suppress so we keep throwing the original exception } } } success = false; string indexName = segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION; try { indexStream = d.CreateOutput(indexName); indexStream.WriteInt(FORMAT_CURRENT); success = true; } finally { if (!success) { try { Close(); } catch (System.IO.IOException) { } try { d.DeleteFile(fieldsName); } catch (System.Exception) { // Suppress so we keep throwing the original exception } try { d.DeleteFile(indexName); } catch (System.Exception) { // Suppress so we keep throwing the original exception } } } doClose = true; } internal FieldsWriter(IndexOutput fdx, IndexOutput fdt, FieldInfos fn) { fieldInfos = fn; fieldsStream = fdt; indexStream = fdx; doClose = false; } internal void SetFieldsStream(IndexOutput stream) { this.fieldsStream = stream; } // Writes the contents of buffer into the fields stream // and adds a new entry for this document into the index // stream. This assumes the buffer was already written // in the correct fields format. internal void FlushDocument(int numStoredFields, RAMOutputStream buffer) { indexStream.WriteLong(fieldsStream.GetFilePointer()); fieldsStream.WriteVInt(numStoredFields); buffer.WriteTo(fieldsStream); } internal void SkipDocument() { indexStream.WriteLong(fieldsStream.GetFilePointer()); fieldsStream.WriteVInt(0); } internal void Flush() { indexStream.Flush(); fieldsStream.Flush(); } internal void Close() { if (doClose) { try { if (fieldsStream != null) { try { fieldsStream.Close(); } finally { fieldsStream = null; } } } catch (System.IO.IOException ioe) { try { if (indexStream != null) { try { indexStream.Close(); } finally { indexStream = null; } } } catch (System.IO.IOException) { // Ignore so we throw only first IOException hit } throw ioe; } finally { if (indexStream != null) { try { indexStream.Close(); } finally { indexStream = null; } } } } } internal void WriteField(FieldInfo fi, Fieldable field) { // if the field as an instanceof FieldsReader.FieldForMerge, we're in merge mode // and field.binaryValue() already returns the compressed value for a field // with isCompressed()==true, so we disable compression in that case bool disableCompression = (field is FieldsReader.FieldForMerge); fieldsStream.WriteVInt(fi.number); byte bits = 0; if (field.IsTokenized()) bits |= FieldsWriter.FIELD_IS_TOKENIZED; if (field.IsBinary()) bits |= FieldsWriter.FIELD_IS_BINARY; if (field.IsCompressed()) bits |= FieldsWriter.FIELD_IS_COMPRESSED; fieldsStream.WriteByte(bits); if (field.IsCompressed()) { // compression is enabled for the current field byte[] data; int len; int offset; if (disableCompression) { // optimized case for merging, the data // is already compressed data = field.GetBinaryValue(); System.Diagnostics.Debug.Assert(data != null); len = field.GetBinaryLength(); offset = field.GetBinaryOffset(); } else { // check if it is a binary field if (field.IsBinary()) { data = Compress(field.GetBinaryValue(), field.GetBinaryOffset(), field.GetBinaryLength()); } else { byte[] x = System.Text.Encoding.UTF8.GetBytes(field.StringValue()); data = Compress(x, 0, x.Length); } len = data.Length; offset = 0; } fieldsStream.WriteVInt(len); fieldsStream.WriteBytes(data, offset, len); } else { // compression is disabled for the current field if (field.IsBinary()) { int length = field.GetBinaryLength(); fieldsStream.WriteVInt(length); fieldsStream.WriteBytes(field.BinaryValue(), field.GetBinaryOffset(), length); } else { fieldsStream.WriteString(field.StringValue()); } } } /// <summary>Bulk write a contiguous series of documents. The /// lengths array is the length (in bytes) of each raw /// document. The stream IndexInput is the /// fieldsStream from which we should bulk-copy all /// bytes. /// </summary> internal void AddRawDocuments(IndexInput stream, int[] lengths, int numDocs) { long position = fieldsStream.GetFilePointer(); long start = position; for (int i = 0; i < numDocs; i++) { indexStream.WriteLong(position); position += lengths[i]; } fieldsStream.CopyBytes(stream, position - start); System.Diagnostics.Debug.Assert(fieldsStream.GetFilePointer() == position); } internal void AddDocument(Document doc) { indexStream.WriteLong(fieldsStream.GetFilePointer()); int storedCount = 0; System.Collections.IEnumerator fieldIterator = doc.GetFields().GetEnumerator(); while (fieldIterator.MoveNext()) { Fieldable field = (Fieldable) fieldIterator.Current; if (field.IsStored()) storedCount++; } fieldsStream.WriteVInt(storedCount); fieldIterator = doc.GetFields().GetEnumerator(); while (fieldIterator.MoveNext()) { Fieldable field = (Fieldable) fieldIterator.Current; if (field.IsStored()) WriteField(fieldInfos.FieldInfo(field.Name()), field); } } private byte[] Compress(byte[] input, int offset, int length) { return SupportClass.CompressionSupport.Compress(input, offset, length); } } }
// 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.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.Text; using Microsoft.Extensions.Primitives; namespace HtcSharp.HttpModule.Http.Headers { // SourceTools-Start // Remote-File C:\ASP\src\Http\Headers\src\NameValueHeaderValue.cs // Start-At-Remote-Line 12 // SourceTools-End // According to the RFC, in places where a "parameter" is required, the value is mandatory // (e.g. Media-Type, Accept). However, we don't introduce a dedicated type for it. So NameValueHeaderValue supports // name-only values in addition to name/value pairs. public class NameValueHeaderValue { private static readonly HttpHeaderParser<NameValueHeaderValue> SingleValueParser = new GenericHeaderParser<NameValueHeaderValue>(false, GetNameValueLength); internal static readonly HttpHeaderParser<NameValueHeaderValue> MultipleValueParser = new GenericHeaderParser<NameValueHeaderValue>(true, GetNameValueLength); private StringSegment _name; private StringSegment _value; private bool _isReadOnly; private NameValueHeaderValue() { // Used by the parser to create a new instance of this type. } public NameValueHeaderValue(StringSegment name) : this(name, null) { } public NameValueHeaderValue(StringSegment name, StringSegment value) { CheckNameValueFormat(name, value); _name = name; _value = value; } public StringSegment Name { get { return _name; } } public StringSegment Value { get { return _value; } set { HeaderUtilities.ThrowIfReadOnly(IsReadOnly); CheckValueFormat(value); _value = value; } } public bool IsReadOnly { get { return _isReadOnly; } } /// <summary> /// Provides a copy of this object without the cost of re-validating the values. /// </summary> /// <returns>A copy.</returns> public NameValueHeaderValue Copy() { return new NameValueHeaderValue() {_name = _name, _value = _value}; } public NameValueHeaderValue CopyAsReadOnly() { if (IsReadOnly) { return this; } return new NameValueHeaderValue() {_name = _name, _value = _value, _isReadOnly = true}; } public override int GetHashCode() { Contract.Assert(_name != null); var nameHashCode = StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_name); if (!StringSegment.IsNullOrEmpty(_value)) { // If we have a quoted-string, then just use the hash code. If we have a token, convert to lowercase // and retrieve the hash code. if (_value[0] == '"') { return nameHashCode ^ _value.GetHashCode(); } return nameHashCode ^ StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_value); } return nameHashCode; } public override bool Equals(object obj) { var other = obj as NameValueHeaderValue; if (other == null) { return false; } if (!_name.Equals(other._name, StringComparison.OrdinalIgnoreCase)) { return false; } // RFC2616: 14.20: unquoted tokens should use case-INsensitive comparison; quoted-strings should use // case-sensitive comparison. The RFC doesn't mention how to compare quoted-strings outside the "Expect" // header. We treat all quoted-strings the same: case-sensitive comparison. if (StringSegment.IsNullOrEmpty(_value)) { return StringSegment.IsNullOrEmpty(other._value); } if (_value[0] == '"') { // We have a quoted string, so we need to do case-sensitive comparison. return (_value.Equals(other._value, StringComparison.Ordinal)); } else { return (_value.Equals(other._value, StringComparison.OrdinalIgnoreCase)); } } public StringSegment GetUnescapedValue() { if (!HeaderUtilities.IsQuoted(_value)) { return _value; } return HeaderUtilities.UnescapeAsQuotedString(_value); } public void SetAndEscapeValue(StringSegment value) { HeaderUtilities.ThrowIfReadOnly(IsReadOnly); if (StringSegment.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length)) { _value = value; } else { Value = HeaderUtilities.EscapeAsQuotedString(value); } } public static NameValueHeaderValue Parse(StringSegment input) { var index = 0; return SingleValueParser.ParseValue(input, ref index); } public static bool TryParse(StringSegment input, out NameValueHeaderValue parsedValue) { var index = 0; return SingleValueParser.TryParseValue(input, ref index, out parsedValue); } public static IList<NameValueHeaderValue> ParseList(IList<string> input) { return MultipleValueParser.ParseValues(input); } public static IList<NameValueHeaderValue> ParseStrictList(IList<string> input) { return MultipleValueParser.ParseStrictValues(input); } public static bool TryParseList(IList<string> input, out IList<NameValueHeaderValue> parsedValues) { return MultipleValueParser.TryParseValues(input, out parsedValues); } public static bool TryParseStrictList(IList<string> input, out IList<NameValueHeaderValue> parsedValues) { return MultipleValueParser.TryParseStrictValues(input, out parsedValues); } public override string ToString() { if (!StringSegment.IsNullOrEmpty(_value)) { return _name + "=" + _value; } return _name.ToString(); } internal static void ToString( IList<NameValueHeaderValue> values, char separator, bool leadingSeparator, StringBuilder destination) { Contract.Assert(destination != null); if ((values == null) || (values.Count == 0)) { return; } for (var i = 0; i < values.Count; i++) { if (leadingSeparator || (destination.Length > 0)) { destination.Append(separator); destination.Append(' '); } destination.Append(values[i].Name.AsSpan()); if (!StringSegment.IsNullOrEmpty(values[i].Value)) { destination.Append('='); destination.Append(values[i].Value.AsSpan()); } } } internal static string ToString(IList<NameValueHeaderValue> values, char separator, bool leadingSeparator) { if ((values == null) || (values.Count == 0)) { return null; } var sb = new StringBuilder(); ToString(values, separator, leadingSeparator, sb); return sb.ToString(); } internal static int GetHashCode(IList<NameValueHeaderValue> values) { if ((values == null) || (values.Count == 0)) { return 0; } var result = 0; for (var i = 0; i < values.Count; i++) { result = result ^ values[i].GetHashCode(); } return result; } private static int GetNameValueLength(StringSegment input, int startIndex, out NameValueHeaderValue parsedValue) { Contract.Requires(input != null); Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove // leading whitespaces. var nameLength = HttpRuleParser.GetTokenLength(input, startIndex); if (nameLength == 0) { return 0; } var name = input.Subsegment(startIndex, nameLength); var current = startIndex + nameLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the separator between name and value if ((current == input.Length) || (input[current] != '=')) { // We only have a name and that's OK. Return. parsedValue = new NameValueHeaderValue(); parsedValue._name = name; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return current - startIndex; } current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the value, i.e. <value> in name/value string "<name>=<value>" int valueLength = GetValueLength(input, current); // Value after the '=' may be empty // Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation. parsedValue = new NameValueHeaderValue(); parsedValue._name = name; parsedValue._value = input.Subsegment(current, valueLength); current = current + valueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return current - startIndex; } // Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3 // name/value pairs to 'nameValueCollection' if 'delimiter' equals ','. internal static int GetNameValueListLength( StringSegment input, int startIndex, char delimiter, IList<NameValueHeaderValue> nameValueCollection) { Contract.Requires(nameValueCollection != null); Contract.Requires(startIndex >= 0); if ((StringSegment.IsNullOrEmpty(input)) || (startIndex >= input.Length)) { return 0; } var current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); while (true) { NameValueHeaderValue parameter = null; var nameValueLength = GetNameValueLength(input, current, out parameter); if (nameValueLength == 0) { // There may be a trailing ';' return current - startIndex; } nameValueCollection.Add(parameter); current = current + nameValueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != delimiter)) { // We're done and we have at least one valid name/value pair. return current - startIndex; } // input[current] is 'delimiter'. Skip the delimiter and whitespaces and try to parse again. current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } public static NameValueHeaderValue Find(IList<NameValueHeaderValue> values, StringSegment name) { Contract.Requires((name != null) && (name.Length > 0)); if ((values == null) || (values.Count == 0)) { return null; } for (var i = 0; i < values.Count; i++) { var value = values[i]; if (value.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { return value; } } return null; } internal static int GetValueLength(StringSegment input, int startIndex) { Contract.Requires(input != null); if (startIndex >= input.Length) { return 0; } var valueLength = HttpRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { // A value can either be a token or a quoted string. Check if it is a quoted string. if (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed) { // We have an invalid value. Reset the name and return. return 0; } } return valueLength; } private static void CheckNameValueFormat(StringSegment name, StringSegment value) { HeaderUtilities.CheckValidToken(name, nameof(name)); CheckValueFormat(value); } private static void CheckValueFormat(StringSegment value) { // Either value is null/empty or a valid token/quoted string if (!(StringSegment.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length))) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "The header value is invalid: '{0}'", value)); } } private static NameValueHeaderValue CreateNameValue() { return new NameValueHeaderValue(); } } }
// ReSharper disable RedundantArgumentDefaultValue namespace Gu.State.Tests { using System.Collections.Generic; using System.Collections.ObjectModel; using NUnit.Framework; public static partial class DirtyTrackerTests { public static class ObservableCollectionOfInt { [Test] public static void CreateDifferentLength() { var x = new ObservableCollection<int> { 1 }; var y = new ObservableCollection<int> { 1, 2 }; using var tracker = Track.IsDirty(x, y); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [1] x: missing item y: 2", tracker.Diff.ToString(string.Empty, " ")); } [Test] public static void AddSameToBoth() { var x = new ObservableCollection<int>(); var y = new ObservableCollection<int>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Add(1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Add(1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void InsertXAt0() { var x = new ObservableCollection<int> { 1, 2, 3 }; var y = new ObservableCollection<int> { 1, 2, 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Insert(0, 0); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<int> [0] x: 0 y: 1 [1] x: 1 y: 2 [2] x: 2 y: 3 [3] x: 3 y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void InsertXAt1() { var x = new ObservableCollection<int> { 1, 2, 3 }; var y = new ObservableCollection<int> { 1, 2, 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Insert(1, 4); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<int> [1] x: 4 y: 2 [2] x: 2 y: 3 [3] x: 3 y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void InsertYAt0() { var x = new ObservableCollection<int> { 1, 2, 3 }; var y = new ObservableCollection<int> { 1, 2, 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); y.Insert(0, 0); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<int> [0] x: 1 y: 0 [1] x: 2 y: 1 [2] x: 3 y: 2 [3] x: missing item y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void InsertYAt1() { var x = new ObservableCollection<int> { 1, 2, 3 }; var y = new ObservableCollection<int> { 1, 2, 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); y.Insert(1, 4); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual($"ObservableCollection<int> [1] x: 2 y: 4 [2] x: 3 y: 2 [3] x: missing item y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void AddDifferent() { var x = new ObservableCollection<int>(); var y = new ObservableCollection<int>(); var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Add(1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: missing item", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Add(2); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.Add("Diff"); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void RemoveTheDifference1() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 1 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [1] x: 2 y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void RemoveTheDifference2() { var x = new ObservableCollection<int> { 1, 2, 3 }; var y = new ObservableCollection<int> { 1, 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [1] x: 2 y: 3 [2] x: 3 y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void Remove0StillDirty() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: 3 [1] x: 2 y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(0); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 2 y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void Remove1StillDirty() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 3 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: 3 [1] x: 2 y: missing item", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.RemoveAt(1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: 3", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void ClearBothWhenNotDirty() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 1, 2 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Clear(); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: missing item y: 1 [1] x: missing item y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Clear(); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void ClearBothWhenDirty() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 3, 4, 5 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: 3 [1] x: 2 y: 4 [2] x: missing item y: 5", tracker.Diff.ToString(string.Empty, " ")); CollectionAssert.IsEmpty(changes); x.Clear(); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: missing item y: 3 [1] x: missing item y: 4 [2] x: missing item y: 5", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Clear(); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveX1() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 1, 2 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Move(0, 1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 2 y: 1 [1] x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); x.Move(0, 1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveX2() { var x = new ObservableCollection<int> { 1, 2, 3, 4 }; var y = new ObservableCollection<int> { 1, 2, 3, 4 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Move(0, 2); Assert.AreEqual(true, tracker.IsDirty); var expected = "ObservableCollection<int> [0] x: 2 y: 1 [1] x: 3 y: 2 [2] x: 1 y: 3"; var actual = tracker.Diff.ToString(string.Empty, " "); Assert.AreEqual(expected, actual); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); x.Move(2, 0); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void MoveXThenY() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 1, 2 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x.Move(0, 1); Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 2 y: 1 [1] x: 1 y: 2", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y.Move(0, 1); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } [Test] public static void Replace() { var x = new ObservableCollection<int> { 1, 2 }; var y = new ObservableCollection<int> { 1, 2 }; var changes = new List<string>(); var expectedChanges = new List<string>(); using var tracker = Track.IsDirty(x, y, ReferenceHandling.Structural); tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); CollectionAssert.IsEmpty(changes); x[0] = 3; Assert.AreEqual(true, tracker.IsDirty); Assert.AreEqual("ObservableCollection<int> [0] x: 3 y: 1", tracker.Diff.ToString(string.Empty, " ")); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); y[0] = 3; Assert.AreEqual(false, tracker.IsDirty); Assert.AreEqual(null, tracker.Diff); expectedChanges.AddRange(new[] { "Diff", "IsDirty" }); CollectionAssert.AreEqual(expectedChanges, changes); } } } }
/* ==================================================================== 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. ==================================================================== */ /* * TestCellStyle.java * * Created on December 11, 2001, 5:51 PM */ namespace TestCases.HSSF.UserModel { using System; using System.IO; using NPOI.Util; using NPOI.HSSF.UserModel; using NUnit.Framework; using TestCases.HSSF; using NPOI.SS.UserModel; /** * Class to Test cell styling functionality * * @author Andrew C. Oliver */ [TestFixture] public class TestCellStyle { private static HSSFWorkbook OpenSample(String sampleFileName) { return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName); } /** Creates a new instance of TestCellStyle */ public TestCellStyle() { } /** * TEST NAME: Test Write Sheet Font <P> * OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with fonts.<P> * SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects * Last row, first row is Tested against the correct values (99,0).<P> * FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good. * NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P> * */ [Test] public void TestWriteSheetFont() { string filepath = TempFile.GetTempFilePath("TestWriteSheetFont", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = null; ICell c = null; IFont fnt = wb.CreateFont(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); fnt.Color=(NPOI.HSSF.Util.HSSFColor.Red.Index); fnt.Boldweight= (short)FontBoldWeight.Bold; cs.SetFont(fnt); for (short rownum = ( short ) 0; rownum < 100; rownum++) { r = s.CreateRow(rownum); // r.SetRowNum(( short ) rownum); for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) { c = r.CreateCell(cellnum); c.SetCellValue(rownum * 10000 + cellnum + ((( double ) rownum / 1000) + (( double ) cellnum / 10000))); c = r.CreateCell(cellnum + 1); c.SetCellValue("TEST"); c.CellStyle = (cs); } } wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99"); Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0"); // assert((s.LastRowNum == 99)); } /** * Tests that is creating a file with a date or an calendar works correctly. */ [Test] public void TestDataStyle() { string filepath = TempFile.GetTempFilePath("TestWriteSheetStyleDate", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); IRow row = s.CreateRow(0); // with Date: ICell cell = row.CreateCell(1); cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cell.CellStyle = (cs); cell.SetCellValue(DateTime.Now); // with Calendar: cell = row.CreateCell(2); cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cell.CellStyle = (cs); cell.SetCellValue(DateTime.Now); wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(0, s.LastRowNum, "LAST ROW "); Assert.AreEqual(0, s.FirstRowNum,"FIRST ROW "); } [Test] public void TestHashEquals() { HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle(); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); IRow row = s.CreateRow(0); ICell cell1 = row.CreateCell(1); ICell cell2 = row.CreateCell(2); cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy")); cs2.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy")); cell1.CellStyle = (cs1); cell1.SetCellValue(DateTime.Now); cell2.CellStyle = (cs2); cell2.SetCellValue(DateTime.Now); Assert.AreEqual(cs1.GetHashCode(), cs1.GetHashCode()); Assert.AreEqual(cs2.GetHashCode(), cs2.GetHashCode()); Assert.IsTrue(cs1.Equals(cs1)); Assert.IsTrue(cs2.Equals(cs2)); // Change cs1, hash will alter int hash1 = cs1.GetHashCode(); cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy")); Assert.IsFalse(hash1 == cs1.GetHashCode()); } /** * TEST NAME: Test Write Sheet Style <P> * OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with colors * and borders.<P> * SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects * Last row, first row is Tested against the correct values (99,0).<P> * FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good. * NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P> * */ [Test] public void TestWriteSheetStyle() { string filepath = TempFile.GetTempFilePath("TestWriteSheetStyle", ".xls"); FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate); HSSFWorkbook wb = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = null; ICell c = null; IFont fnt = wb.CreateFont(); NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle(); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); cs.BorderBottom= (BorderStyle.Thin); cs.BorderLeft= (BorderStyle.Thin); cs.BorderRight= (BorderStyle.Thin); cs.BorderTop= (BorderStyle.Thin); cs.FillForegroundColor= ( short ) 0xA; cs.FillPattern = FillPattern.SolidForeground; fnt.Color= ( short ) 0xf; fnt.IsItalic= (true); cs2.FillForegroundColor= ( short ) 0x0; cs2.FillPattern= FillPattern.SolidForeground; cs2.SetFont(fnt); for (short rownum = ( short ) 0; rownum < 100; rownum++) { r = s.CreateRow(rownum); // r.SetRowNum(( short ) rownum); for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) { c = r.CreateCell(cellnum); c.SetCellValue(rownum * 10000 + cellnum + ((( double ) rownum / 1000) + (( double ) cellnum / 10000))); c.CellStyle = (cs); c = r.CreateCell(cellnum + 1); c.SetCellValue("TEST"); c.CellStyle = (cs2); } } wb.Write(out1); out1.Close(); SanityChecker sanityChecker = new SanityChecker(); sanityChecker.CheckHSSFWorkbook(wb); Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99"); Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0"); // assert((s.LastRowNum == 99)); } /** * Cloning one NPOI.SS.UserModel.CellType onto Another, same * HSSFWorkbook */ [Test] public void TestCloneStyleSameWB() { HSSFWorkbook wb = new HSSFWorkbook(); IFont fnt = wb.CreateFont(); fnt.FontName=("TestingFont"); Assert.AreEqual(5, wb.NumberOfFonts); NPOI.SS.UserModel.ICellStyle orig = wb.CreateCellStyle(); orig.Alignment=(HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat=((short)18); Assert.AreEqual(HorizontalAlignment.Right,orig.Alignment); Assert.AreEqual(fnt,orig.GetFont(wb)); Assert.AreEqual(18,orig.DataFormat); NPOI.SS.UserModel.ICellStyle clone = wb.CreateCellStyle(); Assert.AreNotEqual(HorizontalAlignment.Right , clone.Alignment); Assert.AreNotEqual(fnt, clone.GetFont(wb)); Assert.AreNotEqual(18, clone.DataFormat); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt, clone.GetFont(wb)); Assert.AreEqual(18, clone.DataFormat); Assert.AreEqual(5, wb.NumberOfFonts); orig.Alignment = HorizontalAlignment.Left; Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); } /** * Cloning one NPOI.SS.UserModel.CellType onto Another, across * two different HSSFWorkbooks */ [Test] public void TestCloneStyleDiffWB() { HSSFWorkbook wbOrig = new HSSFWorkbook(); IFont fnt = wbOrig.CreateFont(); fnt.FontName=("TestingFont"); Assert.AreEqual(5, wbOrig.NumberOfFonts); IDataFormat fmt = wbOrig.CreateDataFormat(); fmt.GetFormat("MadeUpOne"); fmt.GetFormat("MadeUpTwo"); NPOI.SS.UserModel.ICellStyle orig = wbOrig.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat=(fmt.GetFormat("Test##")); Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt,orig.GetFont(wbOrig)); Assert.AreEqual(fmt.GetFormat("Test##") , orig.DataFormat); // Now a style on another workbook HSSFWorkbook wbClone = new HSSFWorkbook(); Assert.AreEqual(4, wbClone.NumberOfFonts); IDataFormat fmtClone = wbClone.CreateDataFormat(); NPOI.SS.UserModel.ICellStyle clone = wbClone.CreateCellStyle(); Assert.AreEqual(4, wbClone.NumberOfFonts); Assert.AreNotEqual(HorizontalAlignment.Right,clone.Alignment); Assert.AreNotEqual("TestingFont", clone.GetFont(wbClone).FontName); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual("TestingFont" ,clone.GetFont(wbClone).FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"),clone.DataFormat); Assert.AreNotEqual(fmtClone.GetFormat("Test##") , fmt.GetFormat("Test##")); Assert.AreEqual(5, wbClone.NumberOfFonts); } [Test] public void TestStyleNames() { HSSFWorkbook wb = OpenSample("WithExtendedStyles.xls"); NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0); ICell c1 = s.GetRow(0).GetCell(0); ICell c2 = s.GetRow(1).GetCell(0); ICell c3 = s.GetRow(2).GetCell(0); HSSFCellStyle cs1 = (HSSFCellStyle)c1.CellStyle; HSSFCellStyle cs2 = (HSSFCellStyle)c2.CellStyle; HSSFCellStyle cs3 = (HSSFCellStyle)c3.CellStyle; Assert.IsNotNull(cs1); Assert.IsNotNull(cs2); Assert.IsNotNull(cs3); // Check we got the styles we'd expect Assert.AreEqual(10, cs1.GetFont(wb).FontHeightInPoints); Assert.AreEqual(9, cs2.GetFont(wb).FontHeightInPoints); Assert.AreEqual(12, cs3.GetFont(wb).FontHeightInPoints); Assert.AreEqual(15, cs1.Index); Assert.AreEqual(23, cs2.Index); Assert.AreEqual(24, cs3.Index); Assert.IsNull(cs1.ParentStyle); Assert.IsNotNull(cs2.ParentStyle); Assert.IsNotNull(cs3.ParentStyle); Assert.AreEqual(21, cs2.ParentStyle.Index); Assert.AreEqual(22, cs3.ParentStyle.Index); // Now Check we can get style records for // the parent ones Assert.IsNull(wb.Workbook.GetStyleRecord(15)); Assert.IsNull(wb.Workbook.GetStyleRecord(23)); Assert.IsNull(wb.Workbook.GetStyleRecord(24)); Assert.IsNotNull(wb.Workbook.GetStyleRecord(21)); Assert.IsNotNull(wb.Workbook.GetStyleRecord(22)); // Now Check the style names Assert.AreEqual(null, cs1.UserStyleName); Assert.AreEqual(null, cs2.UserStyleName); Assert.AreEqual(null, cs3.UserStyleName); Assert.AreEqual("style1", cs2.ParentStyle.UserStyleName); Assert.AreEqual("style2", cs3.ParentStyle.UserStyleName); // now apply a named style to a new cell ICell c4 = s.GetRow(0).CreateCell(1); c4.CellStyle = (cs2); Assert.AreEqual("style1", ((HSSFCellStyle)c4.CellStyle).ParentStyle.UserStyleName); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public struct AF_RGBA { public double red, green, blue, alpha; public AF_RGBA(double red, double green, double blue, double alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } } public enum AFSDKPanelContent { AFSDKPanelContentDefault = 0, AFSDKPanelContentFeedbackOnly } public enum AFSDKPanelStyle { AFSDKPanelStyleDefault = 0, AFSDKPanelStyleFullscreen } public class AppsfireEngageSDK : MonoBehaviour { /* Interface to native implementation */ [DllImport ("__Internal")] private static extern void afsdk_handleBadgeCountLocally(bool handleLocally); [DllImport ("__Internal")] private static extern void afsdk_handleBadgeCountLocallyAndRemotely(bool handleLocallyAndRemotely); [DllImport ("__Internal")] private static extern bool afsdk_presentPanelForContentAndStyle(AFSDKPanelContent content, AFSDKPanelStyle style); [DllImport ("__Internal")] private static extern void afsdk_dismissPanel(); [DllImport ("__Internal")] private static extern bool afsdk_isDisplayed(); [DllImport ("__Internal")] private static extern bool afsdk_openSDKNotificationID(int notificationID); [DllImport ("__Internal")] private static extern void afsdk_setBackgroundAndTextColor(AF_RGBA backgroundColor, AF_RGBA textColor); [DllImport ("__Internal")] private static extern void afsdk_setCustomKeysValues(string attributes); [DllImport ("__Internal")] private static extern bool afsdk_setUserEmailAndModifiable(string email, bool modifiable); [DllImport ("__Internal")] private static extern void afsdk_showFeedbackButton(bool showButton); [DllImport ("__Internal")] private static extern int afsdk_numberOfPendingNotifications(); /*! * @brief Handle the badge count for this app locally (only on the device and only while the app is alive). * @since 1.0.3 * * @note Note that <handleBadgeCountLocally> overrides any settings established by <handleBadgeCountLocallyAndRemotely>, and vice versa. * * @param handleLocally A boolean to determine if the badge count should be handled locally. */ public static void HandleBadgeCountLocally(bool handleLocally) { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_handleBadgeCountLocally(handleLocally); } /*! * @brief Handle the badge count for this app remotely (Appsfire SDK will update the icon at all times, locally and remotely, even when app is closed). * @since 1.0.3 * * @note Note that <handleBadgeCountLocallyAndRemotely> overrides any settings established by <handleBadgeCountLocally>. * @note IMPORTANT: If you set this option to YES, you need to provide us with your Push Certificate. * For more information, visit your "Manage Apps" section on http://dashboard.appsfire.com/app/manage * * @param handleLocallyAndRemotely Boolean to determine if badge count should be handled locally and remotely. */ public static void HandleBadgeCountLocallyAndRemotely(bool handleLocallyAndRemotely) { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_handleBadgeCountLocallyAndRemotely(handleLocallyAndRemotely); } /*! * @brief Present the panel for notifications / feedback in a specific style * @since 2.0 * * @note Use this method for an easy way to present the Notification Wall. It'll use the window to display, and handle itself so you don't have anything to do except for calling the presentation method. * * @param content The default parameter (AFSDKPanelContentDefault) displays the Notification Wall. But if you choose to only display the feedback form (AFSDKPanelContentFeedbackOnly), the Notification Wall will be hidden. * @param style The panel can displayed in a modal fashion over your application (AFSDKPanelStyleDefault) or in full screen (AFSDKPanelStyleFullscreen). * * @return Returns false if a problem occures when trying to present the panel. */ public static bool PresentPanelForContentAndStyle(AFSDKPanelContent content, AFSDKPanelStyle style) { if (Application.platform == RuntimePlatform.IPhonePlayer) return afsdk_presentPanelForContentAndStyle(content, style); return false; } /*! * @brief Closes the Notification Wall and/or Feedback Form * * @note In the case you are handling the panel with a controller, you are responsible for dismissing it yourself. */ public static void DismissPanel() { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_dismissPanel(); } /*! * @brief Tells you if the SDK is displayed. * * @return `YES` if notifications panel or feedback screen is displayed, `NO` if none. */ public static bool IsDisplayed() { if (Application.platform == RuntimePlatform.IPhonePlayer) return afsdk_isDisplayed(); return false; } /*! * @brief Opens the SDK to a specific notification ID. * @since 1.1.4 * * @note Calls "SDKopenNotificationResult:" on delegate set by "setApplicationDelegate" if it exists. * * @param notificationID The notification ID you would like to open. Generally this ID is sent via a push to your app. */ public static void OpenSDKNotificationID(int notificationID) { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_openSDKNotificationID(notificationID); } /*! * @brief You can customize a bit the colors used for the user interface. It'll mainly affect the header and the footer of the panel that you present. * @since 2.0 * * @note You must specify both the background and text colors. * * @param backgroundColor The color used for the background. * @param textColor The color used for the text (over the specific background color). */ public static void SetBackgroundAndTextColor(AF_RGBA backgroundColor, AF_RGBA textColor) { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_setBackgroundAndTextColor(backgroundColor, textColor); } /*! * @brief Send data to SDK in key/value pairs. Strings matching any of your [KEYS] will be replaced by the respective value you send. * @since 2.0 * * @param customValues A dictionary containing the keys/values to replace. (See documentation for example) */ public static void SetCustomKeysValues(Dictionary<string, string> attributes) { if (Application.platform != RuntimePlatform.IPhonePlayer) return; string attributesString = ""; foreach(KeyValuePair<string, string> kvp in attributes) { attributesString += kvp.Key + "=/=" + kvp.Value + "\n"; } afsdk_setCustomKeysValues(attributesString); } /*! * @brief Set user email. * @since 1.1.0 * * @note If you know your user's email, call this function so that we avoid asking the user to enter his or her email when sending feedback. * * @param email The user's email * @param modifiable If `modifiable` is set to FALSE, the user won't be able to modify his/her email in the Feedback form. * * @return `YES` if no error was detected, `NO` if a problem occured (likely because email was invalid). */ public static bool SetUserEmailAndModifiable(string email, bool modifiable) { if (Application.platform == RuntimePlatform.IPhonePlayer) return afsdk_setUserEmailAndModifiable(email, modifiable); return false; } /*! * @brief Allow you to display or hide feedback button. * @since 1.1.5 * * @param showButton The boolean to tell if feedback button should be displayed or not. Default value is `YES`. */ public static void ShowFeedbackButton(bool showButton) { if (Application.platform == RuntimePlatform.IPhonePlayer) afsdk_showFeedbackButton(showButton); } /*! * @brief Returns the number of unread notifications that require attention. * * @return Return an integer that represent the number of unread notifications. * If SDK isn't initialized, this number will be 0. */ public static int NumberOfPendingNotifications() { if (Application.platform == RuntimePlatform.IPhonePlayer) return afsdk_numberOfPendingNotifications(); return 0; } }
using System; using System.IO; using System.Collections; using System.Drawing; namespace Fork { class Compiler { public static void writeShort(FileStream F, int x) { int chop = x % 65536; byte a = (byte)(chop / 256); byte b = (byte)(chop % 256); F.WriteByte(a); F.WriteByte(b); } public static void writeString(FileStream F, string x) { int len = x.Length; writeShort(F, len); for (int i = 0; i < len; i++) F.WriteByte((byte)(x[i])); } public static void Convert(string args0, string args1) { //FileStream F = File.Create(args0.Replace(".","_")+".pix", 1024); FileStream F = File.Create(args1, 1024); bool forceAlpha = false; byte Level = 0; /* if(args.Length >= 3) { if(args[2].ToLower().Equals("-noresize")) doNOTresize = true; } if(args.Length >= 4) { if(args[2].ToLower().Equals("-forcealpha")) { forceAlpha = true; Level = (byte)(Int32.Parse(args[3])); } } */ Bitmap C = new Bitmap(args0); bool hasAlpha = (args0.IndexOf(".png") > 0); writeString(F, args0); writeShort(F, C.Width); writeShort(F, C.Height); System.Console.WriteLine(" (" + C.Width + "," + C.Height + ")"); F.WriteByte(8); F.WriteByte(8); F.WriteByte(8); if (forceAlpha || hasAlpha) { F.WriteByte(8); } else { F.WriteByte(0); } Color Alpha = C.GetPixel(0, 0); for (int y = 0; y < C.Height; y++) { for (int x = 0; x < C.Width; x++) { Color P = C.GetPixel(x, y); if (forceAlpha || hasAlpha) { F.WriteByte(P.R); F.WriteByte(P.G); F.WriteByte(P.B); if (forceAlpha) { if (P.R == Alpha.R && P.G == Alpha.G & P.B == Alpha.B) F.WriteByte(Level); else F.WriteByte(255); } else { F.WriteByte(P.A); } } else { F.WriteByte(P.R); F.WriteByte(P.G); F.WriteByte(P.B); } } } F.Close(); } public static ArrayList _StoredFonts; public static ForkDOM.FontRef CompileFontRef(ForkDOM.FontRef ft) { ft._FontBitmap = new ForkDOM.ImageRef(); ft._Family = ft._Family.Trim(); foreach (ForkDOM.FontRef f in _StoredFonts) { if (f._Family.Equals(ft.Family)) { if (f._Bold == ft._Bold) { if (f._Size == ft._Size) { return f; } } } } Fork.FontCompiler.CompileFontRef(ft); _StoredFonts.Add(ft); return ft; } public static ArrayList CollectImageRefs(ForkDOM.Layer L) { ArrayList R = new ArrayList(); if (L._Controls == null) return R; foreach (ForkDOM.Control C in L._Controls) { if (C is ForkDOM.Image) { R.Add((C as ForkDOM.Image)._Bitmap); } if (C is ForkDOM.ImageButton) { R.Add((C as ForkDOM.ImageButton)._Bitmap); } if (C is ForkDOM.Label) { (C as ForkDOM.Label)._Font = CompileFontRef((C as ForkDOM.Label)._Font); R.Add((C as ForkDOM.Label)._Font._FontBitmap); } } return R; } public static ArrayList CollectImageRefs(ForkDOM.GuiSystem G) { ArrayList R = new ArrayList(); if (G.Layers == null) return R; foreach (ForkDOM.Layer L in G._Layers) { ArrayList S = CollectImageRefs(L); R.AddRange(S); } return R; } public static void Do(ForkDOM.GuiSystem GuiIn) { _StoredFonts = new ArrayList(); xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); GuiIn.WriteXML(writ); ForkDOM.GuiSystem Gui = ForkDOM.ForkDOM.BuildObjectTable(xmljr.XmlJrDom.Read(writ.GetXML(), null), null).LookUpObject(1) as ForkDOM.GuiSystem; ArrayList Tx = CollectImageRefs(Gui); // Build a Unique set, box pack that // then iterate over and copy results int Gutter = 2; ArrayList TxPages = new ArrayList(); BoxPacking bp = new BoxPacking(); Bitmap B; ArrayList UniTxNames = new ArrayList(); foreach (ForkDOM.ImageRef IR in Tx) { if (!UniTxNames.Contains(IR._TextureName)) { UniTxNames.Add(IR._TextureName); Console.WriteLine("Adding: " + IR._TextureName); B = new Bitmap(IR.TextureName); bp.AddBox(B.Width + 2 * Gutter, B.Height + 2 * Gutter, IR._TextureName); B.Dispose(); } } int Dim = 1024; ArrayList TexK = bp.FilloutBoxRandomly(Dim, Dim); string OutK = "gui_images_" + 0; TxPages.Add(OutK); B = new Bitmap(Dim, Dim, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics G = Graphics.FromImage(B); G.Clear(Color.Transparent); foreach (BoxPacking.Box Bx in TexK) { foreach (ForkDOM.ImageRef IR in Tx) { if (Bx.BMP.Equals(IR.TextureName)) { IR._TextureName = OutK; double at_x = (Bx.X + Gutter) / (double)Dim; double at_y = (Bx.Y + Gutter) / (double)Dim; double at_w = (Bx.Width - 2 * Gutter) / (double)Dim; double at_h = (Bx.Height - 2 * Gutter) / (double)Dim; IR._X = at_x + at_w * IR._X; IR._Y = at_y + at_h * IR._Y; IR._Width = at_w * IR._Width; IR._Height = at_h * IR._Height; IR._State_AssetId = 0; } } Bitmap C = new Bitmap(Bx.BMP); G.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1), Bx.X, Bx.Y, Bx.Width, Bx.Height); G.DrawImage(C, new Rectangle(Bx.X + Gutter, Bx.Y + Gutter, Bx.Width - 2 * Gutter, Bx.Height - 2 * Gutter)); C.Dispose(); } if (File.Exists(OutK + ".png")) File.Delete(OutK + ".png"); B.Save(OutK + ".png", System.Drawing.Imaging.ImageFormat.Png); G.Dispose(); B.Dispose(); Convert(OutK + ".png", OutK + ".pix"); Gui._Textures = new ForkDOM.GuiTexture[TxPages.Count]; int wr = 0; foreach (string s in TxPages) { Gui._Textures[wr] = new ForkDOM.GuiTexture(); Gui._Textures[wr]._Name = (string)(TxPages[wr]) + ".pix"; wr++; } xmljr.XmlJrWriter writ2 = new xmljr.XmlJrWriter(null); Gui.WriteXML(writ2); StreamWriter sw = new StreamWriter("compiled_gui.xml"); sw.Write(writ2.GetXML()); sw.Flush(); sw.Close(); } } }
/* 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 System.Collections.Generic; using System.IO; using DriveProxy.Utils; namespace DriveProxy.API { partial class DriveService { internal class FileInfoLock : IDisposable { private readonly string _fileId; private readonly string _filePath; private readonly State _state; public FileInfoLock(State state, string fileId, string filePath, System.IO.FileStream fileStream = null) { try { _state = state; _fileId = fileId; _filePath = filePath; FileStream = fileStream; } catch (Exception exception) { Log.Error(exception); } } public string FileId { get { return _fileId; } } public string FilePath { get { return _filePath; } } public FileStream FileStream { get; set; } public void Dispose() { try { _state.UnlockFile(this); } catch (Exception exception) { Log.Error(exception); } } } internal class State : IDisposable { public delegate void EventHandler(State sender); public delegate void FileLockHandler(State sender, FileInfoLock fileInfoLock); public delegate void StreamHandler(State sender, DriveService.Stream stream); protected bool _CalledOnStartedProcessing = false; protected List<Item> _Items = null; protected Mutex _Mutex = null; protected Item _ProcessItem = null; protected bool _Processing = false; protected State() { } protected List<Item> Items { get { return _Items ?? (_Items = new List<Item>()); } } protected Mutex Mutex { get { return _Mutex ?? (_Mutex = new Mutex()); } } public bool Processing { get { return _Processing; } } public void Dispose() { try { } catch (Exception exception) { Log.Error(exception, false); } } public static State Create() { return Factory.GetInstance(); } public static event EventHandler OnStartedProcessing = null; public static event EventHandler OnFinishedProcessing = null; public event FileLockHandler OnLockFile = null; public event FileLockHandler OnUnlockFile = null; public bool IsFileLocked(string fileId, string filePath) { try { Item lockedItem = null; return IsFileLocked(fileId, filePath, ref lockedItem); } catch (Exception exception) { Log.Error(exception); return false; } } protected bool IsFileLocked(string fileId, string filePath, ref Item lockedItem) { try { Mutex.Wait(); try { foreach (Item item in Items) { if (item.Stream != null) { continue; } if (item.IsLocked(fileId, filePath)) { lockedItem = item; return true; } } return false; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); return false; } } public FileInfoLock LockFile(string fileId, string filePath) { try { return LockFile(null, fileId, filePath); } catch (Exception exception) { Log.Error(exception); return null; } } protected FileInfoLock LockFile(DriveService.Stream stream, string fileId, string filePath) { try { Mutex.Wait(); try { var fileInfoLock = new FileInfoLock(this, fileId, filePath); Items.Add(new Item(fileInfoLock, stream)); if (OnLockFile != null) { OnLockFile(this, fileInfoLock); } return fileInfoLock; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, true, false); return null; } } public FileInfoLock LockFile(string fileId, string filePath, System.IO.FileMode fileMode, System.IO.FileAccess fileAccess, System.IO.FileShare fileShare) { try { return LockFile(null, fileId, filePath, fileMode, fileAccess, fileShare); } catch (Exception exception) { Log.Error(exception); return null; } } protected FileInfoLock LockFile(DriveService.Stream stream, string fileId, string filePath, System.IO.FileMode fileMode, System.IO.FileAccess fileAccess, System.IO.FileShare fileShare) { try { Mutex.Wait(); try { System.IO.FileStream fileStream = null; Exception lastException = null; for (int i = 0; i < 10; i++) { try { // Open file will try and execute for 1 sec, // for this function we will wait up to 10 sec fileStream = OpenFile(filePath, fileMode, fileAccess, fileShare); lastException = null; break; } catch (Exception exception) { lastException = exception; } System.Threading.Thread.Sleep(100); } if (lastException != null) { throw lastException; } FileInfoLock fileInfoLock = null; try { fileInfoLock = LockFile(stream, fileId, filePath); fileInfoLock.FileStream = fileStream; } catch (Exception exception) { if (fileStream != null) { fileStream.Dispose(); fileStream = null; } throw exception; } return fileInfoLock; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, true, false); return null; } } public void UnlockFile(FileInfoLock fileInfoLock) { try { Mutex.Wait(); try { if (fileInfoLock.FileStream != null) { fileInfoLock.FileStream.Dispose(); fileInfoLock.FileStream = null; } int index = 0; bool found = false; foreach (Item item in Items) { if (item.FileInfoLock == fileInfoLock) { found = true; Items.RemoveAt(index); break; } index++; } if (!found) { return; } if (OnUnlockFile != null) { OnUnlockFile(this, fileInfoLock); } } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); } } public static event StreamHandler OnQueuedStream = null; public static event StreamHandler OnFinishedStream = null; public bool IsStreamLocked(string fileId, string filePath, ref DriveService.Stream stream) { try { Item lockedItem = null; bool result = IsStreamLocked(fileId, filePath, ref lockedItem); if (result) { stream = lockedItem.Stream; } return result; } catch (Exception exception) { Log.Error(exception); return false; } } protected bool IsStreamLocked(string fileId, string filePath, ref Item lockedItem) { try { Mutex.Wait(); try { foreach (Item item in Items) { if (item.Stream == null) { continue; } if (item.IsLocked(fileId, filePath)) { lockedItem = item; return true; } } return false; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); return false; } } public void QueueStream(DriveService.Stream stream) { try { QueueStreams(new[] {stream}); } catch (Exception exception) { Log.Error(exception); } } public void QueueStreams(IEnumerable<DriveService.Stream> streams) { try { Mutex.Wait(); try { foreach (DriveService.Stream stream in streams) { bool found = false; foreach (Item item in Items) { if (item.Stream == stream) { found = true; break; } } if (!found) { DriveService.Stream.Factory.Queue(stream); Items.Add(new Item(stream)); if (stream.Visible) { try { if (OnQueuedStream != null) { OnQueuedStream(this, stream); } } catch { } } } } TryStartProcessing(); } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); } } public FileInfoLock LockStream(DriveService.Stream stream, string filePath) { try { return LockFile(stream, stream.FileId, filePath); } catch (Exception exception) { Log.Error(exception); return null; } } public FileInfoLock LockStream(DriveService.Stream stream, string filePath, System.IO.FileMode fileMode, System.IO.FileAccess fileAccess, System.IO.FileShare fileShare) { try { return LockFile(stream, stream.FileId, filePath, fileMode, fileAccess, fileShare); } catch (Exception exception) { Log.Error(exception); return null; } } public void FinishStream(DriveService.Stream stream) { try { Mutex.Wait(); try { int index = 0; bool found = false; foreach (Item item in Items) { if (item.Stream == stream) { found = true; Items.RemoveAt(index); break; } index++; } if (!found) { return; } DriveService.Stream.Factory.Dispose(stream); if (stream.Visible) { try { if (OnFinishedStream != null) { OnFinishedStream(this, stream); } } catch { } } TryFinishProcessing(); } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); } } private bool TryStartProcessing() { try { foreach (Item item in Items) { if (TryStartProcessing(item)) { return true; } } return false; } catch (Exception exception) { Log.Error(exception); return false; } } private bool TryStartProcessing(Item item) { try { System.Windows.Forms.Application.DoEvents(); if (item.Stream != null) { if (item.Stream.Cancelled) { DriveService.Stream.Factory.Dispose(item.Stream); QueueStream(item.Stream); return false; } if (item.Stream.Queued) { if (_ProcessItem == item) { Debugger.Break(); } _Processing = true; _ProcessItem = item; if (!_CalledOnStartedProcessing && item.Stream.Visible) { if (OnStartedProcessing != null) { _CalledOnStartedProcessing = true; try { OnStartedProcessing(this); } catch (Exception exception) { Log.Error(exception, false); } } } DriveService.Stream.Factory.Start(item.Stream); return true; } } return false; } catch (Exception exception) { Log.Error(exception); return false; } } private bool TryFinishProcessing() { try { if (TryStartProcessing()) { return false; } _Processing = false; if (_CalledOnStartedProcessing) { if (OnFinishedProcessing != null) { try { OnFinishedProcessing(this); } catch (Exception exception) { Log.Error(exception, false); } } } _ProcessItem = null; _CalledOnStartedProcessing = false; return true; } catch (Exception exception) { Log.Error(exception); return false; } } private class Factory { private static State _State; public static State GetInstance() { try { return _State ?? (_State = new State()); } catch (Exception exception) { Log.Error(exception); return null; } } } protected class Item { public FileInfoLock FileInfoLock = null; public DriveService.Stream Stream = null; public Item(FileInfoLock fileInfoLock, DriveService.Stream stream) { FileInfoLock = fileInfoLock; Stream = stream; } public Item(DriveService.Stream stream) { Stream = stream; } public bool IsLocked(string fileId, string filePath) { if (FileInfoLock != null) { if (!String.IsNullOrEmpty(fileId)) { if (FileInfoLock.FileId == fileId) { return true; } } else { if (String.Equals(FileInfoLock.FilePath, filePath, StringComparison.CurrentCultureIgnoreCase)) { return true; } } } return false; } } } } }
// <copyright file="ExampleMain.cs"> // Copyright (c) 2011 Christopher A. Watford // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> // <author>Christopher A. Watford [christopher.watford@gmail.com]</author> using System; using System.IO; using System.IO.Compression; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using NDesk.Options; using SierraEcg.IO; using System.Reflection; namespace SierraEcg { class ExampleMain { static XNamespace ns = "http://www3.medical.philips.com"; #region Runtime Configuration class Configuration { private List<string> statements = new List<string>(); public bool RemovePatientInformation { get; set; } public bool RemoveDeviceInformation { get; set; } public bool AddDecodedByStatement { get; set; } public bool ShowHelp { get; set; } public IEnumerable<string> Statements { get { return this.statements; } } public void AddStatement(string statement) { this.statements.Add(statement); } } #endregion Runtime Configuration public static void Main(string[] args) { var config = new Configuration() { AddDecodedByStatement = true }; var optionSet = new OptionSet() { { "s|statement=", "Add an interpretive statement (may use more than once)", arg => config.AddStatement(arg) }, { "no-patient-info", "Remove patient specific information", _ => config.RemovePatientInformation = true }, { "no-device-info", "Remove device specific information", _ => config.RemoveDeviceInformation = true }, { "no-watermark", "Do not add 'Decoded by...' statement", _ => config.AddDecodedByStatement = false }, { "?|h|help", "Show this message", _ => config.ShowHelp = true }, }; var extra = optionSet.Parse(args); if (!extra.Any() || config.ShowHelp) { Console.Error.WriteLine("XliDecompressor.exe [OPTIONS] <input files (XML, TGZ, GZ, TAR)>"); optionSet.WriteOptionDescriptions(Console.Error); Environment.Exit(-1); } else { foreach (string file in extra) { bool tar = false; bool gzip = false; var ext = Path.GetExtension(file).ToUpperInvariant(); switch (ext) { case ".TGZ": tar = true; gzip = true; break; case ".GZ": gzip = true; tar = file.EndsWith(".TAR.GZ"); break; case ".TAR": tar = true; break; } try { Stream stream = File.OpenRead(file); if (gzip) { stream = new GZipStream(stream, CompressionMode.Decompress); } if (tar) { using (var reader = new TarFile(stream)) { Func<string, bool> isLikelyXmlFile = fn => 0 == String.Compare(Path.GetExtension(fn), ".XML", ignoreCase: true); // Look through the TGZ/TAR.GZ file for any XML file foreach (var entry in reader.EnumerateEntries(entry => isLikelyXmlFile(entry.Name))) { Console.WriteLine("[Info] Extracting: {0}", entry.Name); var xdoc = XDocument.Load(reader.Current); if (xdoc.Descendants(ns + "parsedwaveforms").Any()) { xdoc = UpdateFile(xdoc, config); var output = Path.ChangeExtension(Path.GetFileName(entry.Name), ".decomp.xml"); Console.WriteLine("[Info] Saving: {0}", output); xdoc.Save(output); } } } } else { var xdoc = UpdateFile(XDocument.Load(stream), config); var output = Path.ChangeExtension(Path.GetFileName(file), ".decomp.xml"); Console.WriteLine("[Info] Saving: {0}", output); xdoc.Save(output); } } catch (Exception ex) { Console.Error.WriteLine("[Error] Could not decompress '{0}'", file); Console.Error.WriteLine("{0}", ex); Environment.ExitCode = -2; } } } } /// <summary> /// Updates a Sierra ECG XML file, removing any XLI compression used. /// </summary> /// <param name="xdoc">XML document containing the Sierra ECG XML file.</param> /// <param name="statements">Additional interpretive statements to add to the ECG.</param> /// <param name="addDecodedBy"><see langword="true"/> if we should watermark the ECG with /// the name of the program which decoded it; otherwise <see langword="false"/>.</param> static XDocument UpdateFile(XDocument xdoc, Configuration config) { xdoc = SierraEcgFile.Preprocess(xdoc); var lastStatement = xdoc.Element(ns + "restingecgdata") .Element(ns + "interpretations") .Elements(ns + "interpretation") .Last() .Elements(ns + "statement") .LastOrDefault(); if (lastStatement != null) { foreach (var statement in config.Statements) { var parts = statement.Split(';'); lastStatement.AddAfterSelf(CreateStatement(parts.First(), parts.LastOrDefault())); } // Add a statement advising how the data was decoded if (config.AddDecodedByStatement) { var version = Assembly.GetExecutingAssembly().GetName().Version; lastStatement.AddAfterSelf(CreateStatement("Decoded by XliDecompressor " + version, DateTime.Now.ToString())); } } if (config.RemovePatientInformation) { var patientData = xdoc.Root.Element(ns + "patient") .Element(ns + "generalpatientdata"); if (patientData != null) { var patientId = patientData.Element(ns + "patientid"); if (patientId != null) { patientId.ReplaceWith(new XElement(ns + "patientid", 0)); } var name = patientData.Element(ns + "name"); if (name != null) { name.ReplaceWith( new XElement( ns + "name", new XElement(ns + "lastname"), new XElement(ns + "firstname"))); } } var userdefines = xdoc.Root.Element(ns + "userdefines"); if (userdefines != null) { foreach (var userdefine in userdefines.Elements(ns + "userdefine")) { var label = userdefine.Element(ns + "label"); if (label != null && 0 == String.Compare((string)label, "Incident Id", true)) { var value = userdefine.Element(ns + "value"); if (value != null) { value.ReplaceWith(new XElement(ns + "value", 0)); } } } } } if (config.RemoveDeviceInformation) { var machine = xdoc.Root.Element(ns + "dataacquisition") .Element(ns + "machine"); if (machine != null) { machine.SetAttributeValue("machineid", 0); machine.SetAttributeValue("detaildescription", String.Empty); } var deviceInfo = xdoc.Root.Element(ns + "dataacquisition") .Element(ns + "acquirer"); if (deviceInfo != null) { deviceInfo.ReplaceWith( new XElement( ns + "acquirer", new XElement(ns + "operatorid"), new XElement(ns + "departmentid"), new XElement(ns + "institutionname"), new XElement(ns + "institutionlocationid"))); } } return xdoc; } /// <summary> /// Creates a &lt;statement&gt; element to add to an ECG. /// </summary> /// <param name="left">Left hand side message for the statement.</param> /// <param name="right">Right hand side message for the statement.</param> /// <returns>A new &lt;statement&gt; element to add to the interpretive statements block.</returns> static XElement CreateStatement(string left, string right) { return new XElement( ns + "statement", new XElement(ns + "statementcode"), new XElement(ns + "leftstatement", left), new XElement(ns + "rightstatement", right)); } } }
//------------------------------------------------------------------------------ // <copyright file="SourceCodeGenerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTestCodeGen { using System; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using Microsoft.CSharp; using MSUnittest = Microsoft.VisualStudio.TestTools.UnitTesting; internal static class GodeGeneratorConst { public const string RootNameSpace = "DMLibTest.Generated"; public const string ClassInitMethodName = "GeneratedClassInit"; public const string ClassCleanupMethodName = "GeneratedClassCleanup"; public const string TestInitMethodName = "GeneratedTestInit"; public const string TestCleanupMethodName = "GeneratedTestCleanup"; } internal class SourceCodeGenerator { private const string SourceFileExtention = ".cs"; private const string GeneratedSuffix = "_Generated"; private string outputPath; public SourceCodeGenerator(string outputPath) { this.outputPath = outputPath; } public void GenerateSourceCode(MultiDirectionTestClass testClass) { string sourceFileName = this.GetSourceFileName(testClass); if (testClass.MultiDirectionMethods.Count == 0) { Console.WriteLine("{0} has no multiple direction test case. Skip code generating...", testClass.ClassType.Name); return; } Console.WriteLine("Generating code for {0}", testClass.ClassType.Name); CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace rootNameSpace = new CodeNamespace(GodeGeneratorConst.RootNameSpace); this.AddImport(rootNameSpace); rootNameSpace.Types.Add(GetGeneratedClass(testClass)); compileUnit.Namespaces.Add(rootNameSpace); this.WriteCodeToFile(compileUnit, Path.Combine(this.outputPath, sourceFileName)); } private void AddImport(CodeNamespace nameSpace) { nameSpace.Imports.Add(new CodeNamespaceImport("DMLibTestCodeGen")); nameSpace.Imports.Add(new CodeNamespaceImport("Microsoft.VisualStudio.TestTools.UnitTesting")); nameSpace.Imports.Add(new CodeNamespaceImport("MS.Test.Common.MsTestLib")); nameSpace.Imports.Add(new CodeNamespaceImport("System")); } private CodeTypeDeclaration GetGeneratedClass(MultiDirectionTestClass testClass) { CodeTypeDeclaration result = new CodeTypeDeclaration(this.GetGeneratedClassName(testClass)); result.Attributes = MemberAttributes.Public; result.BaseTypes.Add(testClass.ClassType); if (FrameworkType.DNetCore == Program.FrameWorkType) { AddXunitLifecycleCode(testClass.ClassType.Name, result); } else if (FrameworkType.DNet == Program.FrameWorkType) // Add initialize and cleanup method for MSTest { CodeAttributeDeclaration testClassAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(MSUnittest.TestClassAttribute))); result.CustomAttributes.Add(testClassAttribute); result.Members.Add(this.GetInitCleanupMethod(typeof(MSUnittest.ClassInitializeAttribute), testClass)); result.Members.Add(this.GetInitCleanupMethod(typeof(MSUnittest.ClassCleanupAttribute), testClass)); } // No need to generate TestInitialize and TestCleanup Method. // Generated class can inherit from base class. // Expand multiple direction test case foreach (MultiDirectionTestMethod testMethod in testClass.MultiDirectionMethods) { this.AddGeneratedMethod(result, testMethod); } return result; } private static void AddXunitLifecycleCode(string className, CodeTypeDeclaration classDeclaration) { // Add IClassFixture for class-level initialization and cleanup, and // CollectionAttribute to mimic MsTest's assembly-level intialization and cleanup. // (http://xunit.github.io/docs/shared-context.html) classDeclaration.BaseTypes.Add($"Xunit.IClassFixture<{className}Fixture>"); var globalCollectionAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(Xunit.CollectionAttribute)), new CodeAttributeArgument(new CodeSnippetExpression("Collections.Global"))); classDeclaration.CustomAttributes.Add(globalCollectionAttribute); // Add a logger field to hold a reference to XunitLogger, which will // redirect output from MsTestLib's Test class to xUnit's logger const string loggerFieldname = "logger"; var loggerField = new CodeMemberField { Attributes = MemberAttributes.Private, Name = loggerFieldname, Type = new CodeTypeReference("XunitLogger") }; classDeclaration.Members.Add(loggerField); var loggerFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), loggerFieldname); const string parameterName = "outputHelper"; var constructor = new CodeConstructor(); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Xunit.Abstractions.ITestOutputHelper), parameterName)); constructor.Statements.Add(new CodeAssignStatement(loggerFieldReference, new CodeObjectCreateExpression(new CodeTypeReference("XunitLogger"), new CodeSnippetExpression(parameterName)))); constructor.Statements.Add(new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression("Test.Logger.Loggers"), "Add"), loggerFieldReference)); constructor.Attributes = MemberAttributes.Public; classDeclaration.Members.Add(constructor); // Add a Dispose method to ensure the xUnit logger reference doesn't outlive the test class var dispose = new CodeMemberMethod { Attributes = MemberAttributes.Override | MemberAttributes.Family, Name = "Dispose", ReturnType = new CodeTypeReference(typeof(void)), }; dispose.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "disposing")); dispose.Statements.Add(new CodeMethodInvokeExpression( new CodeBaseReferenceExpression(), "Dispose", new CodeSnippetExpression("true"))); dispose.Statements.Add(new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression("Test.Logger.Loggers"), "Remove"), loggerFieldReference)); classDeclaration.Members.Add(dispose); } private CodeMemberMethod GetInitCleanupMethod(Type methodAttributeType, MultiDirectionTestClass testClass) { bool isStatic = false; string generatedMetholdName = string.Empty; string methodToInvokeName = string.Empty; CodeParameterDeclarationExpression parameterDec = null; Type acctualAttributeType = methodAttributeType; if (methodAttributeType == typeof(MSUnittest.ClassInitializeAttribute)) { isStatic = true; generatedMetholdName = GodeGeneratorConst.ClassInitMethodName; methodToInvokeName = testClass.ClassInit.Name; parameterDec = new CodeParameterDeclarationExpression(typeof(MSUnittest.TestContext), "testContext"); } else if (methodAttributeType == typeof(MSUnittest.ClassCleanupAttribute)) { isStatic = true; generatedMetholdName = GodeGeneratorConst.ClassCleanupMethodName; methodToInvokeName = testClass.ClassCleanup.Name; } else { throw new ArgumentException("methodAttributeType"); } CodeMemberMethod result = new CodeMemberMethod(); result.Name = generatedMetholdName; // Add parameter list if needed if (parameterDec != null) { result.Parameters.Add(parameterDec); } CodeExpression callBase = null; if (isStatic) { result.Attributes = MemberAttributes.Public | MemberAttributes.Static; callBase = new CodeTypeReferenceExpression(testClass.ClassType.FullName); } else { result.Attributes = MemberAttributes.Public | MemberAttributes.Final; callBase = new CodeBaseReferenceExpression(); } // Add methold attribute CodeAttributeDeclaration methodAttribute = new CodeAttributeDeclaration( new CodeTypeReference(acctualAttributeType)); result.CustomAttributes.Add(methodAttribute); // Add invoke statement CodeMethodInvokeExpression invokeExp = null; if (parameterDec != null) { CodeVariableReferenceExpression sourceParameter = new CodeVariableReferenceExpression(parameterDec.Name); invokeExp = new CodeMethodInvokeExpression(callBase, methodToInvokeName, sourceParameter); } else { invokeExp = new CodeMethodInvokeExpression(callBase, methodToInvokeName); } result.Statements.Add(invokeExp); return result; } private void AddGeneratedMethod(CodeTypeDeclaration generatedClass, MultiDirectionTestMethod testMethod) { foreach (var transferDirection in testMethod.GetTransferDirections()) { string generatedMethodName = this.GetGeneratedMethodName(testMethod, transferDirection); CodeMemberMethod generatedMethod = new CodeMemberMethod(); generatedMethod.Name = generatedMethodName; generatedMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; // Add TestCategoryAttribute to the generated method this.AddTestCategoryAttributes(generatedMethod, testMethod); this.AddTestCategoryAttribute(generatedMethod, MultiDirectionTag.MultiDirection); foreach (var tag in transferDirection.GetTags()) { this.AddTestCategoryAttribute(generatedMethod, tag); } CodeAttributeDeclaration testMethodAttribute = null; testMethodAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(MSUnittest.TestMethodAttribute))); generatedMethod.CustomAttributes.Add(testMethodAttribute); if (Program.FrameWorkType == FrameworkType.DNetCore) { // add TestStartEndAttribute to ensure Test.Start and Test.End will be called as expected generatedMethod.CustomAttributes.Add(new CodeAttributeDeclaration("TestStartEnd")); } foreach (var statement in TransferDirectionExtensions.EnumerateUpdateContextStatements(transferDirection as DMLibTransferDirection)) { generatedMethod.Statements.Add(statement); } CodeMethodReferenceExpression callee = new CodeMethodReferenceExpression( new CodeBaseReferenceExpression(), testMethod.MethodInfoObj.Name); CodeMethodInvokeExpression invokeExp = new CodeMethodInvokeExpression(callee); generatedMethod.Statements.Add(invokeExp); generatedClass.Members.Add(generatedMethod); } } private void AddTestCategoryAttributes(CodeMemberMethod method, MultiDirectionTestMethod testMethod) { foreach (var customAttribute in testMethod.MethodInfoObj.CustomAttributes) { if (customAttribute.AttributeType == typeof(MSUnittest.TestCategoryAttribute)) { if (customAttribute.ConstructorArguments.Count != 1) { // Unrecognized attribute, skip continue; } this.AddTestCategoryAttribute( method, new CodeSnippetExpression(customAttribute.ConstructorArguments[0].ToString())); } } } private void AddTestCategoryAttribute(CodeMemberMethod method, string tagName) { this.AddTestCategoryAttribute(method, new CodePrimitiveExpression(tagName)); } private void AddTestCategoryAttribute(CodeMemberMethod method, CodeExpression expression) { CodeAttributeArgument testCategoryTag = new CodeAttributeArgument(expression); CodeAttributeDeclaration testCategoryAttribute = null; testCategoryAttribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(MSUnittest.TestCategoryAttribute)), testCategoryTag); method.CustomAttributes.Add(testCategoryAttribute); } private string GetSourceFileName(MultiDirectionTestClass testClass) { return this.GetGeneratedClassName(testClass) + SourceFileExtention; } private string GetGeneratedClassName(MultiDirectionTestClass testClass) { return testClass.ClassType.Name + GeneratedSuffix; } private string GetGeneratedMethodName(MultiDirectionTestMethod testMethod, TestMethodDirection transferDirection) { // [MethodName]_[DirectionSuffix] return String.Format("{0}_{1}", testMethod.MethodInfoObj.Name, transferDirection.GetTestMethodNameSuffix()); } private void WriteCodeToFile(CodeCompileUnit compileUnit, string sourceFileName) { CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter(sourceFileName, false)) { using (IndentedTextWriter tw = new IndentedTextWriter(sw, " ")) { provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); } } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Query; using UnityEngine.Events; using UnityEngine; using UnityEngine.SceneManagement; namespace Leap.Unity { public static class Hands { private static LeapProvider s_provider; private static GameObject s_leapRig; static Hands() { InitStatic(); SceneManager.activeSceneChanged += InitStaticOnNewScene; } private static void InitStaticOnNewScene(Scene unused, Scene unused2) { InitStatic(); } private static void InitStatic() { s_provider = GameObject.FindObjectOfType<LeapProvider>(); if (s_provider == null) return; Camera providerCamera = s_provider.GetComponentInParent<Camera>(); if (providerCamera == null) return; if (providerCamera.transform.parent == null) return; s_leapRig = providerCamera.transform.parent.gameObject; } /// <summary> /// Static convenience accessor for the Leap camera rig. This is the parent /// of the Camera that contains a LeapProvider in one of its children, /// or null if there is no such GameObject. /// </summary> public static GameObject Rig { get { if (s_leapRig == null) { InitStatic(); if (s_leapRig == null) { Debug.LogWarning("Camera has no parent; Rig will return null."); } } return s_leapRig; } } /// <summary> /// Static convenience accessor for the LeapProvider. /// </summary> public static LeapProvider Provider { get { if (s_provider == null) { InitStatic(); if (s_provider == null) { Debug.LogWarning("No LeapProvider found in the scene."); } } return s_provider; } } [System.Serializable] public class HandEvent : UnityEvent<Hand> { } /// <summary> /// Returns the first hand of the argument Chirality in the current frame, /// otherwise returns null if no such hand is found. /// </summary> public static Hand Get(Chirality chirality) { if (chirality == Chirality.Left) return Left; else return Right; } /// <summary> /// As Get, but returns the FixedUpdate (physics timestep) hand as opposed to the Update hand. /// </summary> public static Hand GetFixed(Chirality chirality) { if (chirality == Chirality.Left) return FixedLeft; else return FixedRight; } /// <summary> /// Returns the first left hand found by Leap in the current frame, otherwise /// returns null if no such hand is found. /// </summary> public static Hand Left { get { if (Provider == null) return null; if (Provider.CurrentFrame == null) return null; return Provider.CurrentFrame.Hands.Query().FirstOrDefault(hand => hand.IsLeft); } } /// <summary> /// Returns the first right hand found by Leap in the current frame, otherwise /// returns null if no such hand is found. /// </summary> public static Hand Right { get { if (Provider == null) return null; if (Provider.CurrentFrame == null) return null; else return Provider.CurrentFrame.Hands.Query().FirstOrDefault(hand => hand.IsRight); } } /// <summary> /// Returns the first left hand found by Leap in the current fixed frame, otherwise /// returns null if no such hand is found. The fixed frame is aligned with the physics timestep. /// </summary> public static Hand FixedLeft { get { if (Provider == null) return null; if (Provider.CurrentFixedFrame == null) return null; return Provider.CurrentFixedFrame.Hands.Query().FirstOrDefault(hand => hand.IsLeft); } } /// <summary> /// Returns the first right hand found by Leap in the current fixed frame, otherwise /// returns null if no such hand is found. The fixed frame is aligned with the physics timestep. /// </summary> public static Hand FixedRight { get { if (Provider == null) return null; if (Provider.CurrentFixedFrame == null) return null; else return Provider.CurrentFixedFrame.Hands.Query().FirstOrDefault(hand => hand.IsRight); } } /// Shorthand for hand.Fingers[(int)Leap.Finger.FingerType.TYPE_THUMB], /// or, alternatively, hand.Fingers[0]. /// </summary> public static Finger GetThumb(this Hand hand) { return hand.Fingers[(int)Leap.Finger.FingerType.TYPE_THUMB]; } /// <summary> /// Shorthand for hand.Fingers[(int)Leap.Finger.FingerType.TYPE_INDEX], /// or, alternatively, hand.Fingers[1]. /// </summary> public static Finger GetIndex(this Hand hand) { return hand.Fingers[(int)Leap.Finger.FingerType.TYPE_INDEX]; } /// <summary> /// Shorthand for hand.Fingers[(int)Leap.Finger.FingerType.TYPE_MIDDLE], /// or, alternatively, hand.Fingers[2]. /// </summary> public static Finger GetMiddle(this Hand hand) { return hand.Fingers[(int)Leap.Finger.FingerType.TYPE_MIDDLE]; } /// <summary> /// Shorthand for hand.Fingers[(int)Leap.Finger.FingerType.TYPE_RING], /// or, alternatively, hand.Fingers[3]. /// </summary> public static Finger GetRing(this Hand hand) { return hand.Fingers[(int)Leap.Finger.FingerType.TYPE_RING]; } /// <summary> /// Shorthand for hand.Fingers[(int)Leap.Finger.FingerType.TYPE_PINKY], /// or, alternatively, hand.Fingers[4]. /// </summary> public static Finger GetPinky(this Hand hand) { return hand.Fingers[(int)Leap.Finger.FingerType.TYPE_PINKY]; } /// <summary> /// Returns the direction the Hand's palm is facing. For the other two palm-basis /// directions, see RadialAxis and DistalAxis. /// /// The direction out of the back of the hand would be called the dorsal axis. /// </summary> public static Vector3 PalmarAxis(this Hand hand) { return -hand.Basis.yBasis.ToVector3(); } /// <summary> /// Returns the the direction towards the thumb that is perpendicular to the palmar /// and distal axes. Left and right hands will return opposing directions. /// /// The direction away from the thumb would be called the ulnar axis. /// </summary> public static Vector3 RadialAxis(this Hand hand) { if (hand.IsRight) { return -hand.Basis.xBasis.ToVector3(); } else { return hand.Basis.xBasis.ToVector3(); } } /// <summary> /// Returns the direction towards the fingers that is perpendicular to the palmar /// and radial axes. /// /// The direction towards the wrist would be called the proximal axis. /// </summary> public static Vector3 DistalAxis (this Hand hand) { return hand.Basis.zBasis.ToVector3(); } /// <summary> /// Returns whether the pinch strength for the hand is greater than 0.8. /// For more reliable pinch behavior, try applying hysteresis to the PinchStrength property. /// </summary> public static bool IsPinching(this Hand hand) { return hand.PinchStrength > 0.8F; } /// <summary> /// Returns approximately where the thumb and index finger will be if they are pinched together. /// </summary> public static Vector3 GetPinchPosition(this Hand hand) { Vector indexPosition = hand.Fingers[(int)Finger.FingerType.TYPE_INDEX].TipPosition; Vector thumbPosition = hand.Fingers[(int)Finger.FingerType.TYPE_THUMB].TipPosition; return (2 * thumbPosition + indexPosition).ToVector3() * 0.333333F; } /// <summary> /// Returns a decent approximation of where the hand is pinching, or where it will pinch, /// even if the index and thumb tips are far apart. /// /// In general, this will be more stable than GetPinchPosition(). /// </summary> public static Vector3 GetPredictedPinchPosition(this Hand hand) { Vector3 indexTip = hand.GetIndex().TipPosition.ToVector3(); Vector3 thumbTip = hand.GetThumb().TipPosition.ToVector3(); // The predicted pinch point is a rigid point in hand-space linearly offset by the // index finger knuckle position, scaled by the index finger's length, and lightly // influenced by the actual thumb and index tip positions. Vector3 indexKnuckle = hand.Fingers[1].bones[1].PrevJoint.ToVector3(); float indexLength = hand.Fingers[1].Length; Vector3 radialAxis = hand.RadialAxis(); float thumbInfluence = Vector3.Dot((thumbTip - indexKnuckle).normalized, radialAxis).Map(0F, 1F, 0.5F, 0F); Vector3 predictedPinchPoint = indexKnuckle + hand.PalmarAxis() * indexLength * 0.85F + hand.DistalAxis() * indexLength * 0.20F + radialAxis * indexLength * 0.20F; predictedPinchPoint = Vector3.Lerp(predictedPinchPoint, thumbTip, thumbInfluence); predictedPinchPoint = Vector3.Lerp(predictedPinchPoint, indexTip, 0.15F); return predictedPinchPoint; } /// <summary> /// Returns whether this vector faces from a given world position towards another world position within a maximum angle of error. /// </summary> public static bool IsFacing(this Vector3 facingVector, Vector3 fromWorldPosition, Vector3 towardsWorldPosition, float maxOffsetAngleAllowed) { Vector3 actualVectorTowardsWorldPosition = (towardsWorldPosition - fromWorldPosition).normalized; return Vector3.Angle(facingVector, actualVectorTowardsWorldPosition) <= maxOffsetAngleAllowed; } /// <summary> /// Returns a confidence value from 0 to 1 indicating how strongly the Hand is making a fist. /// </summary> public static float GetFistStrength(this Hand hand) { return (Vector3.Dot(hand.Fingers[1].Direction.ToVector3(), -hand.DistalAxis() ) + Vector3.Dot(hand.Fingers[2].Direction.ToVector3(), -hand.DistalAxis() ) + Vector3.Dot(hand.Fingers[3].Direction.ToVector3(), -hand.DistalAxis() ) + Vector3.Dot(hand.Fingers[4].Direction.ToVector3(), -hand.DistalAxis() ) + Vector3.Dot(hand.Fingers[0].Direction.ToVector3(), -hand.RadialAxis() ) ).Map(-5, 5, 0, 1); } /// <summary> /// Transforms a bone by a position and rotation. /// </summary> public static void Transform(this Bone bone, Vector3 position, Quaternion rotation) { bone.Transform(new LeapTransform(position.ToVector(), rotation.ToLeapQuaternion())); } /// <summary> /// Transforms a finger by a position and rotation. /// </summary> public static void Transform(this Finger finger, Vector3 position, Quaternion rotation) { finger.Transform(new LeapTransform(position.ToVector(), rotation.ToLeapQuaternion())); } /// <summary> /// Transforms a hand by a position and rotation. /// </summary> public static void Transform(this Hand hand, Vector3 position, Quaternion rotation) { hand.Transform(new LeapTransform(position.ToVector(), rotation.ToLeapQuaternion())); } /// <summary> /// Transforms a frame by a position and rotation. /// </summary> public static void Transform(this Frame frame, Vector3 position, Quaternion rotation) { frame.Transform(new LeapTransform(position.ToVector(), rotation.ToLeapQuaternion())); } /// <summary> /// Transforms a bone to a position and rotation. /// </summary> public static void SetTransform(this Bone bone, Vector3 position, Quaternion rotation) { bone.Transform(Vector3.zero, (rotation * Quaternion.Inverse(bone.Rotation.ToQuaternion()))); bone.Transform(position - bone.PrevJoint.ToVector3(), Quaternion.identity); } /// <summary> /// Transforms a finger to a position and rotation by its fingertip. /// </summary> public static void SetTipTransform(this Finger finger, Vector3 position, Quaternion rotation) { finger.Transform(Vector3.zero, (rotation * Quaternion.Inverse(finger.bones[3].Rotation.ToQuaternion()))); finger.Transform(position - finger.bones[3].NextJoint.ToVector3(), Quaternion.identity); } /// <summary> /// Transforms a hand to a position and rotation. /// </summary> public static void SetTransform(this Hand hand, Vector3 position, Quaternion rotation) { hand.Transform(Vector3.zero, (rotation * Quaternion.Inverse(hand.Rotation.ToQuaternion()))); hand.Transform(position - hand.PalmPosition.ToVector3(), Quaternion.identity); } } }
// <copyright file="IlutpTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Reflection; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using MathNet.Numerics.LinearAlgebra.Single.Solvers; using MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Solvers.Preconditioners { /// <summary> /// Incomplete LU with IlutpPreconditioner test with drop tolerance and partial pivoting. /// </summary> [TestFixture, Category("LASolver")] public sealed class IlutpPreconditionerTest : PreconditionerTest { /// <summary> /// The drop tolerance. /// </summary> double _dropTolerance = 0.1; /// <summary> /// The fill level. /// </summary> double _fillLevel = 1.0; /// <summary> /// The pivot tolerance. /// </summary> double _pivotTolerance = 1.0; /// <summary> /// Setup default parameters. /// </summary> [SetUp] public void Setup() { _dropTolerance = 0.1; _fillLevel = 1.0; _pivotTolerance = 1.0; } /// <summary> /// Invoke method from Ilutp class. /// </summary> /// <typeparam name="T">Type of the return value.</typeparam> /// <param name="ilutp">Ilutp instance.</param> /// <param name="methodName">Method name.</param> /// <returns>Result of the method invocation.</returns> static T GetMethod<T>(ILUTPPreconditioner ilutp, string methodName) { var type = ilutp.GetType(); var methodInfo = type.GetMethod( methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, CallingConventions.Standard, new Type[0], null); var obj = methodInfo.Invoke(ilutp, null); return (T) obj; } /// <summary> /// Get upper triangle. /// </summary> /// <param name="ilutp">Ilutp instance.</param> /// <returns>Upper triangle.</returns> static SparseMatrix GetUpperTriangle(ILUTPPreconditioner ilutp) { return GetMethod<SparseMatrix>(ilutp, "UpperTriangle"); } /// <summary> /// Get lower triangle. /// </summary> /// <param name="ilutp">Ilutp instance.</param> /// <returns>Lower triangle.</returns> static SparseMatrix GetLowerTriangle(ILUTPPreconditioner ilutp) { return GetMethod<SparseMatrix>(ilutp, "LowerTriangle"); } /// <summary> /// Get pivots. /// </summary> /// <param name="ilutp">Ilutp instance.</param> /// <returns>Pivots array.</returns> static int[] GetPivots(ILUTPPreconditioner ilutp) { return GetMethod<int[]>(ilutp, "Pivots"); } /// <summary> /// Create reverse unit matrix. /// </summary> /// <param name="size">Matrix order.</param> /// <returns>Reverse Unit matrix.</returns> static SparseMatrix CreateReverseUnitMatrix(int size) { var matrix = new SparseMatrix(size); for (var i = 0; i < size; i++) { matrix[i, size - 1 - i] = 2; } return matrix; } /// <summary> /// Create preconditioner (internal) /// </summary> /// <returns>Ilutp instance.</returns> ILUTPPreconditioner InternalCreatePreconditioner() { var result = new ILUTPPreconditioner { DropTolerance = _dropTolerance, FillLevel = _fillLevel, PivotTolerance = _pivotTolerance }; return result; } /// <summary> /// Create preconditioner. /// </summary> /// <returns>New preconditioner instance.</returns> internal override IPreconditioner<float> CreatePreconditioner() { _pivotTolerance = 0; _dropTolerance = 0.0; _fillLevel = 100; return InternalCreatePreconditioner(); } /// <summary> /// Check the result. /// </summary> /// <param name="preconditioner">Specific preconditioner.</param> /// <param name="matrix">Source matrix.</param> /// <param name="vector">Initial vector.</param> /// <param name="result">Result vector.</param> protected override void CheckResult(IPreconditioner<float> preconditioner, SparseMatrix matrix, Vector<float> vector, Vector<float> result) { Assert.AreEqual(typeof (ILUTPPreconditioner), preconditioner.GetType(), "#01"); // Compute M * result = product // compare vector and product. Should be equal var product = new DenseVector(result.Count); matrix.Multiply(result, product); for (var i = 0; i < product.Count; i++) { Assert.IsTrue(((double) vector[i]).AlmostEqualNumbersBetween(product[i], -Epsilon.Magnitude()), "#02-" + i); } } /// <summary> /// Solve returning old vector without pivoting. /// </summary> [Test] public void SolveReturningOldVectorWithoutPivoting() { const int Size = 10; var newMatrix = CreateUnitMatrix(Size); var vector = CreateStandardBcVector(Size); // set the pivot tolerance to zero so we don't pivot _pivotTolerance = 0.0; _dropTolerance = 0.0; _fillLevel = 100; var preconditioner = CreatePreconditioner(); preconditioner.Initialize(newMatrix); var result = new DenseVector(vector.Count); preconditioner.Approximate(vector, result); CheckResult(preconditioner, newMatrix, vector, result); } /// <summary> /// Solve returning old vector with pivoting. /// </summary> [Test] public void SolveReturningOldVectorWithPivoting() { const int Size = 10; var newMatrix = CreateUnitMatrix(Size); var vector = CreateStandardBcVector(Size); // Set the pivot tolerance to 1 so we always pivot (if necessary) _pivotTolerance = 1.0; _dropTolerance = 0.0; _fillLevel = 100; var preconditioner = CreatePreconditioner(); preconditioner.Initialize(newMatrix); var result = new DenseVector(vector.Count); preconditioner.Approximate(vector, result); CheckResult(preconditioner, newMatrix, vector, result); } /// <summary> /// Compare with original dense matrix without pivoting. /// </summary> [Test] public void CompareWithOriginalDenseMatrixWithoutPivoting() { var sparseMatrix = new SparseMatrix(3); sparseMatrix[0, 0] = -1; sparseMatrix[0, 1] = 5; sparseMatrix[0, 2] = 6; sparseMatrix[1, 0] = 3; sparseMatrix[1, 1] = -6; sparseMatrix[1, 2] = 1; sparseMatrix[2, 0] = 6; sparseMatrix[2, 1] = 8; sparseMatrix[2, 2] = 9; var ilu = new ILUTPPreconditioner { PivotTolerance = 0.0, DropTolerance = 0, FillLevel = 10 }; ilu.Initialize(sparseMatrix); var l = GetLowerTriangle(ilu); // Assert l is lower triagonal for (var i = 0; i < l.RowCount; i++) { for (var j = i + 1; j < l.RowCount; j++) { Assert.IsTrue(0.0.AlmostEqualNumbersBetween(l[i, j], -Epsilon.Magnitude()), "#01-" + i + "-" + j); } } var u = GetUpperTriangle(ilu); // Assert u is upper triagonal for (var i = 0; i < u.RowCount; i++) { for (var j = 0; j < i; j++) { Assert.IsTrue(0.0.AlmostEqualNumbersBetween(u[i, j], -Epsilon.Magnitude()), "#02-" + i + "-" + j); } } var original = l.Multiply(u); for (var i = 0; i < sparseMatrix.RowCount; i++) { for (var j = 0; j < sparseMatrix.ColumnCount; j++) { Assert.IsTrue(((double) sparseMatrix[i, j]).AlmostEqualRelative(original[i, j], 5), "#03-" + i + "-" + j); } } } /// <summary> /// Compare with original dense matrix with pivoting. /// </summary> [Test] public void CompareWithOriginalDenseMatrixWithPivoting() { var sparseMatrix = new SparseMatrix(3); sparseMatrix[0, 0] = -1; sparseMatrix[0, 1] = 5; sparseMatrix[0, 2] = 6; sparseMatrix[1, 0] = 3; sparseMatrix[1, 1] = -6; sparseMatrix[1, 2] = 1; sparseMatrix[2, 0] = 6; sparseMatrix[2, 1] = 8; sparseMatrix[2, 2] = 9; var ilu = new ILUTPPreconditioner { PivotTolerance = 1.0, DropTolerance = 0, FillLevel = 10 }; ilu.Initialize(sparseMatrix); var l = GetLowerTriangle(ilu); var u = GetUpperTriangle(ilu); var pivots = GetPivots(ilu); var p = new SparseMatrix(l.RowCount); for (var i = 0; i < p.RowCount; i++) { p[i, pivots[i]] = 1.0f; } var temp = l.Multiply(u); var original = temp.Multiply(p); for (var i = 0; i < sparseMatrix.RowCount; i++) { for (var j = 0; j < sparseMatrix.ColumnCount; j++) { Assert.IsTrue(((double) sparseMatrix[i, j]).AlmostEqualNumbersBetween(original[i, j], -Epsilon.Magnitude()), "#01-" + i + "-" + j); } } } /// <summary> /// Solve with pivoting. /// </summary> [Test] public void SolveWithPivoting() { const int Size = 10; var newMatrix = CreateReverseUnitMatrix(Size); var vector = CreateStandardBcVector(Size); var preconditioner = new ILUTPPreconditioner { PivotTolerance = 1.0, DropTolerance = 0, FillLevel = 10 }; preconditioner.Initialize(newMatrix); var result = new DenseVector(vector.Count); preconditioner.Approximate(vector, result); CheckResult(preconditioner, newMatrix, vector, result); } } }
namespace Nancy.Testing.Tests { using System; using System.Linq; using CsQuery; using Nancy.Testing; using Xunit; public class AssertExtensionsTests { private readonly QueryWrapper query; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public AssertExtensionsTests() { var document = CQ.Create(@"<html><head></head><body><div id='testId' class='myClass' attribute1 attribute2='value2'>Test</div><div class='anotherClass'>Tes</div><span class='class'>some contents</span><span class='class'>This has contents</span></body></html>"); this.query = new QueryWrapper(document); } [Fact] public void Should_throw_assertexception_when_id_does_not_exist() { // Given, When var result = Record.Exception(() => this.query["#notThere"].ShouldExist()); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void Should_not_throw_exception_when_id_does_exist() { // Given, When var result = Record.Exception(() => this.query["#testId"].ShouldExist()); // Then Assert.Null(result); } [Fact] public void Should_detect_nonexistence() { // Given, When var result = Record.Exception(() => this.query["#jamesIsAwesome"].ShouldNotExist()); // Then Assert.Null(result); } [Fact] public void Should_not_throw_exception_when_id_that_should_only_exists_once_only_exists_once() { // Given, When var result = Record.Exception(() => this.query["#testId"].ShouldExistOnce()); // Then Assert.Null(result); } [Fact] public void ShouldExistOnce_ExistsOnce_ReturnsSingleItemAndConnector() { // Given, When var result = this.query["#testId"].ShouldExistOnce(); // Then Assert.IsType<AndConnector<NodeWrapper>>(result); } [Fact] public void ShouldExistsExactly2_Exists2_ReturnsResultAndConnector() { // Given, when var result = this.query[".class"].ShouldExistExactly(2); // Then Assert.IsType<AndConnector<QueryWrapper>>(result); } [Fact] public void ShouldExistsExactly3_Exists2_ReturnsResultAndConnector() { // When var result = Record.Exception(() => this.query[".class"].ShouldExistExactly(3)); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldExistOnce_DoesNotExist_ShouldThrowAssert() { // Given, When var result = Record.Exception(() => this.query["#notHere"].ShouldExistOnce()); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldExistOnce_ExistsMoreThanOnce_ShouldThrowAssert() { // Given, When var result = Record.Exception(() => this.query["div"].ShouldExistOnce()); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldBeClass_ZeroElements_ShouldThrowAssert() { // Given var queryWrapper = this.query["#missing"]; // When var result = Record.Exception(() => queryWrapper.ShouldBeOfClass("nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldBeClass_SingleElementNotThatClass_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldBeOfClass("nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldBeClass_SingleElementWithThatClass_ShouldNotThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldBeOfClass("myClass")); // Then Assert.Null(result); } [Fact] public void ShouldBeClass_MultipleElementsOneNotThatClass_ShouldThrowAssert() { // Given var htmlNodes = this.query["div"]; // When var result = Record.Exception(() => htmlNodes.ShouldBeOfClass("myClass")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldBeClass_MultipleElementsAllThatClass_ShouldNotThrowAssert() { // Given var htmlNodes = this.query["span"]; // When var result = Record.Exception(() => htmlNodes.ShouldBeOfClass("class")); // Then Assert.Null(result); } [Fact] public void AllShouldContain_ZeroElements_ShouldThrowAssert() { // Given var queryWrapper = this.query["#missing"]; // When var result = Record.Exception(() => queryWrapper.AllShouldContain("Anything")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void AnyShouldContain_ZeroElements_ShouldThrowAssert() { // Given var queryWrapper = this.query["#missing"]; // When var result = Record.Exception(() => queryWrapper.AnyShouldContain("Anything")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContain_SingleElementThatContainsText_ShouldNotThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContain("Test")); // Then Assert.Null(result); } [Fact] public void ShouldContain_SingleElementWithTextInDifferentCase_ShouldHonorCompareType() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContain("test", StringComparison.OrdinalIgnoreCase)); // Then Assert.Null(result); } [Fact] public void ShouldContain_SingleElementDoesntContainText_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContain("nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void AllShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert() { // Given var htmlNodes = this.query["span"]; // When var result = Record.Exception(() => htmlNodes.AllShouldContain("contents")); // Then Assert.Null(result); } [Fact] public void AnyShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert() { // Given var htmlNodes = this.query["span"]; // When var result = Record.Exception(() => htmlNodes.AnyShouldContain("contents")); // Then Assert.Null(result); } [Fact] public void AllShouldContain_MultipleElementsOneNotContainingText_ShouldThrowAssert() { // Given var htmlNodes = this.query["div"]; // When var result = Record.Exception(() => htmlNodes.AllShouldContain("Test")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void AnyShouldContain_MultipleElementsOneNotContainingText_ShouldntThrowAssert() { // Given var htmlNodes = this.query["div"]; // When var result = Record.Exception(() => htmlNodes.AnyShouldContain("Test")); // Then Assert.Null(result); } [Fact] public void ShouldContainAttribute_ZeroElements_ShouldThrowAssert() { // Given var queryWrapper = this.query["#missing"]; // When var result = Record.Exception(() => queryWrapper.ShouldContainAttribute("nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_ZeroElementsNameAndValue_ShouldThrowAssert() { // Given var queryWrapper = this.query["#missing"]; // When var result = Record.Exception(() => queryWrapper.ShouldContainAttribute("nope", "nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_SingleElementNotContainingAttribute_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_SingleElementNotContainingAttributeAndValue_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("nope", "nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_SingleElementContainingAttributeWithoutValueButShouldContainValue_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1", "nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_SingleElementContainingAttributeWithDifferentValue_ShouldThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2", "nope")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_SingleElementContainingAttribute_ShouldNotThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1")); // Then Assert.Null(result); } [Fact] public void ShouldContainAttribute_SingleElementContainingAttributeAndValueButIngoringValue_ShouldNotThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2")); // Then Assert.Null(result); } [Fact] public void ShouldContainAttribute_SingleElementContainingAttributeAndValue_ShouldNotThrowAssert() { // Given var htmlNode = this.query["#testId"].First(); // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2", "value2")); // Then Assert.Null(result); } [Fact] public void ShouldContainAttribute_MultipleElementsOneNotContainingAttribute_ShouldThrowAssert() { // Given var htmlNode = this.query["div"]; // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_MultipleElementsOneNotContainingAttributeAndValue_ShouldThrowAssert() { // Given var htmlNode = this.query["div"]; // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class", "myClass")); // Then Assert.IsAssignableFrom<AssertException>(result); } [Fact] public void ShouldContainAttribute_MultipleElementsContainingAttribute_ShouldNotThrowAssert() { // Given var htmlNode = this.query["div"]; // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class")); // Then Assert.Null(result); } [Fact] public void ShouldContainAttribute_MultipleElementsContainingAttributeAndValue_ShouldNotThrowAssert() { // Given var htmlNode = this.query["span"]; // When var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class", "class")); // Then Assert.Null(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 System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Runtime.InteropServices; using System.Diagnostics; using System.Globalization; namespace System.Net.WebSockets { internal class WinHttpWebSocket : WebSocket { #region Constants // TODO: This code needs to be shared with WinHttpClientHandler private const string HeaderNameCookie = "Cookie"; private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol"; #endregion // TODO (Issue 2503): move System.Net.* strings to resources as appropriate. // NOTE: All WinHTTP operations must be called while holding the _operation.Lock. // It is critical that no handle gets closed while a WinHTTP function is running. private WebSocketCloseStatus? _closeStatus = null; private string _closeStatusDescription = null; private string _subProtocol = null; private bool _disposed = false; private WinHttpWebSocketState _operation = new WinHttpWebSocketState(); // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedSendPinnedBuffer; private GCHandle _cachedReceivePinnedBuffer; public WinHttpWebSocket() { } #region Properties public override WebSocketCloseStatus? CloseStatus { get { return _closeStatus; } } public override string CloseStatusDescription { get { return _closeStatusDescription; } } public override WebSocketState State { get { return _operation.State; } } public override string SubProtocol { get { return _subProtocol; } } #endregion readonly static WebSocketState[] s_validConnectStates = { WebSocketState.None }; readonly static WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting }; public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { _operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { lock (_operation.Lock) { _operation.CheckValidState(s_validConnectingStates); // Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort. // // TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the // state is still valid to continue operation. _operation.SessionHandle = InitializeWinHttp(options); _operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback( _operation.SessionHandle, uri.IdnHost, (ushort)uri.Port, 0); ThrowOnInvalidHandle(_operation.ConnectionHandle); bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss; _operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback( _operation.ConnectionHandle, "GET", uri.PathAndQuery, null, Interop.WinHttp.WINHTTP_NO_REFERER, null, secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0); ThrowOnInvalidHandle(_operation.RequestHandle); if (!Interop.WinHttp.WinHttpSetOption( _operation.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, IntPtr.Zero, 0)) { WinHttpException.ThrowExceptionUsingLastError(); } // We need the address of the IntPtr to the GCHandle. IntPtr context = _operation.ToIntPtr(); IntPtr contextAddress; unsafe { contextAddress = (IntPtr)(void*)&context; } if (!Interop.WinHttp.WinHttpSetOption( _operation.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE, contextAddress, (uint)IntPtr.Size)) { WinHttpException.ThrowExceptionUsingLastError(); } if (Interop.WinHttp.WinHttpSetStatusCallback( _operation.RequestHandle, WinHttpWebSocketCallback.s_StaticCallbackDelegate, Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK) { WinHttpException.ThrowExceptionUsingLastError(); } _operation.RequestHandle.AttachCallback(); AddRequestHeaders(uri, options); _operation.TcsUpgrade = new TaskCompletionSource<bool>(); } await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false); await InternalReceiveWsUpgradeResponse().ConfigureAwait(false); lock (_operation.Lock) { VerifyUpgradeResponse(); ThrowOnInvalidConnectState(); _operation.WebSocketHandle = Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero); ThrowOnInvalidHandle(_operation.WebSocketHandle); // We need the address of the IntPtr to the GCHandle. IntPtr context = _operation.ToIntPtr(); IntPtr contextAddress; unsafe { contextAddress = (IntPtr)(void*)&context; } if (!Interop.WinHttp.WinHttpSetOption( _operation.WebSocketHandle, Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE, contextAddress, (uint)IntPtr.Size)) { WinHttpException.ThrowExceptionUsingLastError(); } _operation.WebSocketHandle.AttachCallback(); _operation.UpdateState(WebSocketState.Open); if (_operation.RequestHandle != null) { _operation.RequestHandle.Dispose(); // RequestHandle will be set to null in the callback. } _operation.TcsUpgrade = null; ctr.Dispose(); } } } // Requires lock taken. private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options) { Interop.WinHttp.SafeWinHttpHandle sessionHandle; sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, null, null, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); ThrowOnInvalidHandle(sessionHandle); uint optionAssuredNonBlockingTrue = 1; // TRUE if (!Interop.WinHttp.WinHttpSetOption( sessionHandle, Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS, ref optionAssuredNonBlockingTrue, (uint)Marshal.SizeOf<uint>())) { WinHttpException.ThrowExceptionUsingLastError(); } return sessionHandle; } private Task<bool> InternalSendWsUpgradeRequestAsync() { lock (_operation.Lock) { ThrowOnInvalidConnectState(); if (!Interop.WinHttp.WinHttpSendRequest( _operation.RequestHandle, Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS, 0, IntPtr.Zero, 0, 0, _operation.ToIntPtr())) { WinHttpException.ThrowExceptionUsingLastError(); } } return _operation.TcsUpgrade.Task; } private Task<bool> InternalReceiveWsUpgradeResponse() { // TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback. lock (_operation.Lock) { ThrowOnInvalidConnectState(); _operation.TcsUpgrade = new TaskCompletionSource<bool>(); if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } } return _operation.TcsUpgrade.Task; } private void ThrowOnInvalidConnectState() { // A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages. if (_operation.State != WebSocketState.Connecting) { throw new WebSocketException(SR.net_webstatus_ConnectFailure); } } private readonly static WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived }; public override Task SendAsync( ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { _operation.InterlockedCheckValidStates(s_validSendStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage); // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer.Array) { if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _cachedSendPinnedBuffer = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); } bool sendOperationAlreadyPending = false; if (_operation.PendingWriteOperation == false) { lock (_operation.Lock) { _operation.CheckValidState(s_validSendStates); if (_operation.PendingWriteOperation == false) { _operation.PendingWriteOperation = true; _operation.TcsSend = new TaskCompletionSource<bool>(); uint ret = Interop.WinHttp.WinHttpWebSocketSend( _operation.WebSocketHandle, bufferType, buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero, (uint)buffer.Count); if (Interop.WinHttp.ERROR_SUCCESS != ret) { throw WinHttpException.CreateExceptionUsingError((int)ret); } } else { sendOperationAlreadyPending = true; } } } else { sendOperationAlreadyPending = true; } if (sendOperationAlreadyPending) { var exception = new InvalidOperationException( SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync")); _operation.TcsSend.TrySetException(exception); Abort(); } return _operation.TcsSend.Task; } } private readonly static WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent }; private readonly static WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived }; public override async Task<WebSocketReceiveResult> ReceiveAsync( ArraySegment<byte> buffer, CancellationToken cancellationToken) { _operation.InterlockedCheckValidStates(s_validReceiveStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedReceivePinnedBuffer.IsAllocated || _cachedReceivePinnedBuffer.Target != buffer.Array) { if (_cachedReceivePinnedBuffer.IsAllocated) { _cachedReceivePinnedBuffer.Free(); } _cachedReceivePinnedBuffer = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); } await InternalReceiveAsync(buffer).ConfigureAwait(false); // Check for abort. _operation.InterlockedCheckValidStates(s_validAfterReceiveStates); WebSocketMessageType bufferType; bool endOfMessage; bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage); int bytesTransferred = 0; checked { bytesTransferred = (int)_operation.BytesTransferred; } WebSocketReceiveResult ret; if (bufferType == WebSocketMessageType.Close) { UpdateServerCloseStatus(); ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription); } else { ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage); } return ret; } } private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer) { bool receiveOperationAlreadyPending = false; if (_operation.PendingReadOperation == false) { lock (_operation.Lock) { if (_operation.PendingReadOperation == false) { _operation.CheckValidState(s_validReceiveStates); _operation.TcsReceive = new TaskCompletionSource<bool>(); _operation.PendingReadOperation = true; uint bytesRead = 0; Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0; uint status = Interop.WinHttp.WinHttpWebSocketReceive( _operation.WebSocketHandle, Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset), (uint)buffer.Count, out bytesRead, // Unused in async mode: ignore. out winHttpBufferType); // Unused in async mode: ignore. if (Interop.WinHttp.ERROR_SUCCESS != status) { throw WinHttpException.CreateExceptionUsingError((int)status); } } else { receiveOperationAlreadyPending = true; } } } else { receiveOperationAlreadyPending = true; } if (receiveOperationAlreadyPending) { var exception = new InvalidOperationException( SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync")); _operation.TcsReceive.TrySetException(exception); Abort(); } return _operation.TcsReceive.Task; } private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent }; public override async Task CloseAsync( WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { _operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { _operation.TcsClose = new TaskCompletionSource<bool>(); await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false); UpdateServerCloseStatus(); } } private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription) { uint ret; _operation.TcsClose = new TaskCompletionSource<bool>(); lock (_operation.Lock) { _operation.CheckValidState(s_validCloseStates); if (!string.IsNullOrEmpty(statusDescription)) { byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription); ret = Interop.WinHttp.WinHttpWebSocketClose( _operation.WebSocketHandle, (ushort)closeStatus, statusDescriptionBuffer, (uint)statusDescriptionBuffer.Length); } else { ret = Interop.WinHttp.WinHttpWebSocketClose( _operation.WebSocketHandle, (ushort)closeStatus, IntPtr.Zero, 0); } if (ret != Interop.WinHttp.ERROR_SUCCESS) { throw WinHttpException.CreateExceptionUsingError((int)ret); } } return _operation.TcsClose.Task; } private void UpdateServerCloseStatus() { uint ret; ushort serverStatus; var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength]; uint closeDescriptionConsumed; lock (_operation.Lock) { ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus( _operation.WebSocketHandle, out serverStatus, closeDescription, (uint)closeDescription.Length, out closeDescriptionConsumed); if (ret != Interop.WinHttp.ERROR_SUCCESS) { throw WinHttpException.CreateExceptionUsingError((int)ret); } _closeStatus = (WebSocketCloseStatus)serverStatus; _closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed); } } private readonly static WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived }; private readonly static WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent }; public override Task CloseOutputAsync( WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { _operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { lock (_operation.Lock) { _operation.CheckValidState(s_validCloseOutputStatesAfterUpdate); uint ret; _operation.TcsCloseOutput = new TaskCompletionSource<bool>(); if (!string.IsNullOrEmpty(statusDescription)) { byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription); ret = Interop.WinHttp.WinHttpWebSocketShutdown( _operation.WebSocketHandle, (ushort)closeStatus, statusDescriptionBuffer, (uint)statusDescriptionBuffer.Length); } else { ret = Interop.WinHttp.WinHttpWebSocketShutdown( _operation.WebSocketHandle, (ushort)closeStatus, IntPtr.Zero, 0); } if (ret != Interop.WinHttp.ERROR_SUCCESS) { throw WinHttpException.CreateExceptionUsingError((int)ret); } } return _operation.TcsCloseOutput.Task; } } private void VerifyUpgradeResponse() { // Check the status code var statusCode = GetHttpStatusCode(); if (statusCode != HttpStatusCode.SwitchingProtocols) { Abort(); return; } _subProtocol = GetResponseHeaderStringInfo(HeaderNameWebSocketProtocol); } private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options) { var requestHeadersBuffer = new StringBuilder(); // Manually add cookies. if (options.Cookies != null) { string cookieHeader = GetCookieHeader(uri, options.Cookies); if (!string.IsNullOrEmpty(cookieHeader)) { requestHeadersBuffer.AppendLine(cookieHeader); } } // Serialize general request headers. requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString()); var subProtocols = options.RequestedSubProtocols; if (subProtocols.Count > 0) { requestHeadersBuffer.AppendLine(string.Format("{0}: {1}", HeaderNameWebSocketProtocol, string.Join(", ", subProtocols))); } // Add request headers to WinHTTP request handle. if (!Interop.WinHttp.WinHttpAddRequestHeaders( _operation.RequestHandle, requestHeadersBuffer, (uint)requestHeadersBuffer.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD)) { WinHttpException.ThrowExceptionUsingLastError(); } } private static string GetCookieHeader(Uri uri, CookieContainer cookies) { string cookieHeader = null; Debug.Assert(cookies != null); string cookieValues = cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookieValues)) { cookieHeader = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", HeaderNameCookie, cookieValues); } return cookieHeader; } private HttpStatusCode GetHttpStatusCode() { uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; uint result = 0; uint resultSize = sizeof(uint); if (!Interop.WinHttp.WinHttpQueryHeaders( _operation.RequestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, ref result, ref resultSize, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } return (HttpStatusCode)result; } private string GetResponseHeaderStringInfo(string headerName) { uint bytesNeeded = 0; bool results = false; // Call WinHttpQueryHeaders once to obtain the size of the buffer needed. The size is returned in // bytes but the API actually returns Unicode characters. if (!Interop.WinHttp.WinHttpQueryHeaders( _operation.RequestHandle, Interop.WinHttp.WINHTTP_QUERY_CUSTOM, headerName, null, ref bytesNeeded, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { return null; } if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { throw WinHttpException.CreateExceptionUsingError(lastError); } } int charsNeeded = (int)bytesNeeded / sizeof(char); var buffer = new StringBuilder(charsNeeded, charsNeeded); results = Interop.WinHttp.WinHttpQueryHeaders( _operation.RequestHandle, Interop.WinHttp.WINHTTP_QUERY_CUSTOM, headerName, buffer, ref bytesNeeded, IntPtr.Zero); if (!results) { WinHttpException.ThrowExceptionUsingLastError(); } return buffer.ToString(); } public override void Dispose() { if (!_disposed) { lock (_operation.Lock) { // Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp // function is running at the same time. if (!_disposed) { _operation.Dispose(); // TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further // operations will be made to the send/receive buffers. if (_cachedReceivePinnedBuffer.IsAllocated) { _cachedReceivePinnedBuffer.Free(); } if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _disposed = true; } } } // No need to suppress finalization since the finalizer is not overridden. } public override void Abort() { lock (_operation.Lock) { if ((State != WebSocketState.None) && (State != WebSocketState.Connecting)) { _operation.UpdateState(WebSocketState.Aborted); } else { // ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted. _operation.UpdateState(WebSocketState.Closed); } Dispose(); } CancelAllOperations(); } private void CancelAllOperations() { if (_operation.TcsClose != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsClose.TrySetException(exception); } if (_operation.TcsCloseOutput != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsCloseOutput.TrySetException(exception); } if (_operation.TcsReceive != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsReceive.TrySetException(exception); } if (_operation.TcsSend != null) { var exception = new OperationCanceledException(); _operation.TcsSend.TrySetException(exception); } if (_operation.TcsUpgrade != null) { var exception = new WebSocketException(SR.net_webstatus_ConnectFailure); _operation.TcsUpgrade.TrySetException(exception); } } private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value) { if (value.IsInvalid) { Abort(); throw new WebSocketException( SR.net_webstatus_ConnectFailure, WinHttpException.CreateExceptionUsingLastError()); } } private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { Abort(); cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenRegistration cancellationRegistration = cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this); return cancellationRegistration; } } }
// ----------------------------------------------------------- // // This file was generated, please do not modify. // // ----------------------------------------------------------- namespace EmptyKeys.UserInterface.Generated { using System; using System.CodeDom.Compiler; using System.Collections.ObjectModel; using EmptyKeys.UserInterface; using EmptyKeys.UserInterface.Charts; using EmptyKeys.UserInterface.Data; using EmptyKeys.UserInterface.Controls; using EmptyKeys.UserInterface.Controls.Primitives; using EmptyKeys.UserInterface.Input; using EmptyKeys.UserInterface.Media; using EmptyKeys.UserInterface.Media.Animation; using EmptyKeys.UserInterface.Media.Imaging; using EmptyKeys.UserInterface.Shapes; using EmptyKeys.UserInterface.Renderers; using EmptyKeys.UserInterface.Themes; [GeneratedCodeAttribute("Empty Keys UI Generator", "1.11.0.0")] public partial class TankSelectionPromptWithCountdown : UIRoot { private Grid e_0; private StackPanel e_1; private TextBlock Subscript; private StackPanel e_2; private StackPanel TankSelectionArea; private TextBlock e_3; private ScrollViewer e_4; private StackPanel TankOptions; private Button ConfirmButton; private StackPanel e_5; private TextBlock e_6; private TextBlock e_7; private StackPanel ReadyArea; private TextBlock e_8; private TextBlock e_9; private Button UnReadyButton; public TankSelectionPromptWithCountdown() : base() { this.Initialize(); } public TankSelectionPromptWithCountdown(int width, int height) : base(width, height) { this.Initialize(); } private void Initialize() { Style style = RootStyle.CreateRootStyle(); style.TargetType = this.GetType(); this.Style = style; this.InitializeComponent(); } private void InitializeComponent() { this.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); InitializeElementResources(this); // e_0 element this.e_0 = new Grid(); this.Content = this.e_0; this.e_0.Name = "e_0"; this.e_0.Background = new SolidColorBrush(new ColorW(0, 0, 0, 127)); // e_1 element this.e_1 = new StackPanel(); this.e_0.Children.Add(this.e_1); this.e_1.Name = "e_1"; this.e_1.Margin = new Thickness(0F, 20F, 0F, 0F); this.e_1.HorizontalAlignment = HorizontalAlignment.Center; this.e_1.VerticalAlignment = VerticalAlignment.Top; // Subscript element this.Subscript = new TextBlock(); this.e_1.Children.Add(this.Subscript); this.Subscript.Name = "Subscript"; this.Subscript.HorizontalAlignment = HorizontalAlignment.Center; this.Subscript.Foreground = new SolidColorBrush(new ColorW(211, 211, 211, 255)); this.Subscript.Text = "0 seconds remaining to choose"; this.Subscript.Padding = new Thickness(10F, 10F, 10F, 10F); this.Subscript.FontFamily = new FontFamily("JHUF"); this.Subscript.FontSize = 48F; // e_2 element this.e_2 = new StackPanel(); this.e_0.Children.Add(this.e_2); this.e_2.Name = "e_2"; this.e_2.HorizontalAlignment = HorizontalAlignment.Center; this.e_2.VerticalAlignment = VerticalAlignment.Center; // TankSelectionArea element this.TankSelectionArea = new StackPanel(); this.e_2.Children.Add(this.TankSelectionArea); this.TankSelectionArea.Name = "TankSelectionArea"; this.TankSelectionArea.Margin = new Thickness(0F, 0F, 0F, 0F); this.TankSelectionArea.HorizontalAlignment = HorizontalAlignment.Center; this.TankSelectionArea.VerticalAlignment = VerticalAlignment.Center; // e_3 element this.e_3 = new TextBlock(); this.TankSelectionArea.Children.Add(this.e_3); this.e_3.Name = "e_3"; this.e_3.HorizontalAlignment = HorizontalAlignment.Center; this.e_3.Foreground = new SolidColorBrush(new ColorW(211, 211, 211, 255)); this.e_3.Text = "Select a tank"; this.e_3.Padding = new Thickness(10F, 10F, 10F, 10F); this.e_3.FontFamily = new FontFamily("JHUF"); this.e_3.FontSize = 24F; // e_4 element this.e_4 = new ScrollViewer(); this.TankSelectionArea.Children.Add(this.e_4); this.e_4.Name = "e_4"; this.e_4.Height = 200F; this.e_4.Width = 420F; this.e_4.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; this.e_4.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; // TankOptions element this.TankOptions = new StackPanel(); this.e_4.Content = this.TankOptions; this.TankOptions.Name = "TankOptions"; // ConfirmButton element this.ConfirmButton = new Button(); this.TankSelectionArea.Children.Add(this.ConfirmButton); this.ConfirmButton.Name = "ConfirmButton"; this.ConfirmButton.HorizontalAlignment = HorizontalAlignment.Stretch; this.ConfirmButton.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); this.ConfirmButton.Padding = new Thickness(10F, 10F, 10F, 10F); this.ConfirmButton.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255)); this.ConfirmButton.FontFamily = new FontFamily("JHUF"); this.ConfirmButton.FontSize = 24F; this.ConfirmButton.Content = "I\'m ready"; // e_5 element this.e_5 = new StackPanel(); this.TankSelectionArea.Children.Add(this.e_5); this.e_5.Name = "e_5"; this.e_5.Visibility = Visibility.Collapsed; // e_6 element this.e_6 = new TextBlock(); this.e_5.Children.Add(this.e_6); this.e_6.Name = "e_6"; this.e_6.MaxWidth = 420F; this.e_6.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255)); this.e_6.Padding = new Thickness(10F, 10F, 10F, 10F); this.e_6.FontFamily = new FontFamily("JHUF"); this.e_6.FontSize = 20F; // e_7 element this.e_7 = new TextBlock(); this.e_5.Children.Add(this.e_7); this.e_7.Name = "e_7"; this.e_7.MaxWidth = 420F; this.e_7.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255)); this.e_7.Padding = new Thickness(10F, 10F, 10F, 10F); this.e_7.FontFamily = new FontFamily("JHUF"); this.e_7.FontSize = 16F; // ReadyArea element this.ReadyArea = new StackPanel(); this.e_2.Children.Add(this.ReadyArea); this.ReadyArea.Name = "ReadyArea"; this.ReadyArea.Visibility = Visibility.Collapsed; // e_8 element this.e_8 = new TextBlock(); this.ReadyArea.Children.Add(this.e_8); this.e_8.Name = "e_8"; this.e_8.HorizontalAlignment = HorizontalAlignment.Center; this.e_8.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255)); this.e_8.Text = "You\'re ready to go!"; this.e_8.FontFamily = new FontFamily("JHUF"); this.e_8.FontSize = 48F; // e_9 element this.e_9 = new TextBlock(); this.ReadyArea.Children.Add(this.e_9); this.e_9.Name = "e_9"; this.e_9.HorizontalAlignment = HorizontalAlignment.Center; this.e_9.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255)); this.e_9.Text = "We\'re just waiting for some other players..."; this.e_9.Padding = new Thickness(20F, 20F, 20F, 20F); this.e_9.FontFamily = new FontFamily("JHUF"); this.e_9.FontSize = 24F; // UnReadyButton element this.UnReadyButton = new Button(); this.ReadyArea.Children.Add(this.UnReadyButton); this.UnReadyButton.Name = "UnReadyButton"; this.UnReadyButton.HorizontalAlignment = HorizontalAlignment.Center; this.UnReadyButton.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); this.UnReadyButton.Padding = new Thickness(10F, 10F, 10F, 10F); this.UnReadyButton.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255)); this.UnReadyButton.FontFamily = new FontFamily("JHUF"); this.UnReadyButton.FontSize = 24F; this.UnReadyButton.Content = "I lied. I\'m not ready."; FontManager.Instance.AddFont("JHUF", 36F, FontStyle.Regular, "JHUF_27_Regular"); FontManager.Instance.AddFont("JHUF", 18F, FontStyle.Regular, "JHUF_13.5_Regular"); FontManager.Instance.AddFont("JHUF", 24F, FontStyle.Regular, "JHUF_18_Regular"); FontManager.Instance.AddFont("JHUF", 72F, FontStyle.Regular, "JHUF_54_Regular"); FontManager.Instance.AddFont("JHUF", 96F, FontStyle.Regular, "JHUF_72_Regular"); FontManager.Instance.AddFont("JHUF", 48F, FontStyle.Regular, "JHUF_36_Regular"); FontManager.Instance.AddFont("JHUF", 20F, FontStyle.Regular, "JHUF_15_Regular"); FontManager.Instance.AddFont("JHUF", 40F, FontStyle.Regular, "JHUF_30_Regular"); FontManager.Instance.AddFont("JHUF", 32F, FontStyle.Regular, "JHUF_24_Regular"); FontManager.Instance.AddFont("JHUF", 30F, FontStyle.Regular, "JHUF_22.5_Regular"); FontManager.Instance.AddFont("JHUF", 16F, FontStyle.Regular, "JHUF_12_Regular"); } private static void InitializeElementResources(UIElement elem) { elem.Resources.MergedDictionaries.Add(UITemplateDictionary.Instance); } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using JsonFx.Model; using JsonFx.Serialization; namespace JsonFx.Bson { public partial class BsonReader { /// <summary> /// Generates a sequence of tokens from BSON bytes /// </summary> public class BsonTokenizer : IBinaryTokenizer<ModelTokenType> { #region Constants // error messages private const string ErrorUnexpectedElementType = "Unexpected element type ({0})"; private static readonly BinaryReader NullBinaryReader = new BinaryReader(Stream.Null, Encoding.UTF8); #endregion Constants #region Fields private BinaryReader Reader = BsonTokenizer.NullBinaryReader; #endregion Fields #region Properties /// <summary> /// Gets the current position of the underlying stream /// </summary> public long Index { get { return this.Reader.BaseStream.Position; } } #endregion Properties #region Scanning Methods private static void ReadDocument(List<Token<ModelTokenType>> tokens, BinaryReader reader, bool isArray) { if (reader.PeekChar() < 0) { return; } long start = reader.BaseStream.Position; int size = reader.ReadInt32(); tokens.Add(isArray ? ModelGrammar.TokenArrayBeginUnnamed : ModelGrammar.TokenObjectBeginUnnamed); while (reader.BaseStream.Position-start < size-1) { BsonTokenizer.ReadElement(tokens, reader, isArray); } if (reader.ReadByte() != 0x00) { throw new DeserializationException(BsonWriter.ErrorUnterminated, start); } tokens.Add(isArray ? ModelGrammar.TokenArrayEnd : ModelGrammar.TokenObjectEnd); } private static void ReadElement(List<Token<ModelTokenType>> tokens, BinaryReader reader, bool isArrayItem) { BsonElementType elemType = (BsonElementType)reader.ReadByte(); string ename = BsonTokenizer.ReadCString(reader); if (!isArrayItem) { tokens.Add(ModelGrammar.TokenProperty(ename)); } switch (elemType) { case BsonElementType.Double: { double value = reader.ReadDouble(); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.String: { string value = BsonTokenizer.ReadString(reader); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.JavaScriptCode: { BsonJavaScriptCode value = (BsonJavaScriptCode)BsonTokenizer.ReadString(reader); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.Symbol: { BsonSymbol value = (BsonSymbol)BsonTokenizer.ReadString(reader); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.Document: { BsonTokenizer.ReadDocument(tokens, reader, false); break; } case BsonElementType.Array: { BsonTokenizer.ReadDocument(tokens, reader, true); break; } case BsonElementType.Binary: { BsonTokenizer.ReadBinary(tokens, reader); break; } case BsonElementType.ObjectID: { byte[] value = reader.ReadBytes(BsonWriter.SizeOfObjectID); tokens.Add(ModelGrammar.TokenPrimitive(new BsonObjectID(value))); break; } case BsonElementType.Boolean: { bool value = reader.ReadByte() != BsonWriter.FalseByte; tokens.Add(value ? ModelGrammar.TokenTrue : ModelGrammar.TokenFalse); break; } case BsonElementType.DateTimeUtc: { DateTime value = BsonWriter.UnixEpoch.AddMilliseconds(reader.ReadInt64()); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.RegExp: { string pattern = BsonTokenizer.ReadCString(reader); string optionsStr = BsonTokenizer.ReadCString(reader); RegexOptions options = RegexOptions.ECMAScript; for (int i=optionsStr.Length-1; i>=0; i--) { char ch = optionsStr[i]; switch (ch) { case 'g': { // TODO: ensure correct encoding of ^$ //options |= RegexOptions.Multiline; break; } case 'i': { options |= RegexOptions.IgnoreCase; break; } case 'm': { options |= RegexOptions.Multiline; break; } } } Regex regex = new Regex(pattern, options); tokens.Add(ModelGrammar.TokenPrimitive(regex)); break; } case BsonElementType.DBPointer: { string value1 = BsonTokenizer.ReadString(reader); byte[] value2 = reader.ReadBytes(BsonWriter.SizeOfObjectID); BsonDBPointer pointer = new BsonDBPointer { Namespace=value1, ObjectID=new BsonObjectID(value2) }; tokens.Add(ModelGrammar.TokenPrimitive(pointer)); break; } case BsonElementType.CodeWithScope: { int size = reader.ReadInt32(); string value = BsonTokenizer.ReadString(reader); tokens.Add(ModelGrammar.TokenPrimitive(value)); BsonTokenizer.ReadDocument(tokens, reader, false); break; } case BsonElementType.Int32: { int value = reader.ReadInt32(); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.TimeStamp: { long value = reader.ReadInt64(); // TODO: convert to TimeSpan? tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.Int64: { long value = reader.ReadInt64(); tokens.Add(ModelGrammar.TokenPrimitive(value)); break; } case BsonElementType.Undefined: case BsonElementType.Null: case BsonElementType.MinKey: case BsonElementType.MaxKey: { // no data value break; } default: { throw new DeserializationException( String.Format(BsonTokenizer.ErrorUnexpectedElementType, elemType), reader.BaseStream.Position); } } } private static void ReadBinary(List<Token<ModelTokenType>> tokens, BinaryReader reader) { int size = reader.ReadInt32(); BsonBinarySubtype subtype = (BsonBinarySubtype)reader.ReadByte(); byte[] buffer = reader.ReadBytes(size); object value; switch (subtype) { case BsonBinarySubtype.MD5: { if (size != 16) { goto default; } value = new BsonMD5(buffer); break; } case BsonBinarySubtype.UUID: { if (size != 16) { goto default; } value = new Guid(buffer); break; } case BsonBinarySubtype.BinaryOld: { // Binary (Old): // "The structure of the binary data (this byte* array in the binary non-terminal) must be an int32 followed by a (byte*)." // http://bsonspec.org/#/specification size = BitConverter.ToInt32(buffer, 0); // trim Int32 size off front of array byte[] temp = new byte[size]; Buffer.BlockCopy(buffer, 4, temp, 0, size); // since obsolete, convert to generic value = new BsonBinary(BsonBinarySubtype.Generic, temp); break; } case BsonBinarySubtype.Function: case BsonBinarySubtype.Generic: case BsonBinarySubtype.UserDefined: default: { // TODO: convert Function accordingly value = new BsonBinary(subtype, buffer); break; } } tokens.Add(ModelGrammar.TokenPrimitive(value)); } private static string ReadString(BinaryReader reader) { int size = reader.ReadInt32(); char[] buffer = reader.ReadChars(size); // trim null char return new String(buffer, 0, size-BsonWriter.SizeOfByte); } private static string ReadCString(BinaryReader reader) { // TODO: rebuild this using byte[] buffered reads StringBuilder buffer = new StringBuilder(); char ch; while ('\0' != (ch = reader.ReadChar())) { buffer.Append(ch); } return buffer.ToString(); } #endregion Scanning Methods #region IBinaryTokenizer<ModelTokenType> Members /// <summary> /// Gets a token sequence from the TextReader /// </summary> /// <param name="reader"></param> /// <returns></returns> public IEnumerable<Token<ModelTokenType>> GetTokens(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } return this.GetTokens(new BinaryReader(stream, Encoding.UTF8)); } /// <summary> /// Gets a token sequence from the string /// </summary> /// <param name="text"></param> /// <returns></returns> public IEnumerable<Token<ModelTokenType>> GetTokens(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } return this.GetTokens(new MemoryStream(bytes, false)); } /// <summary> /// Gets a token sequence from the reader /// </summary> /// <param name="reader"></param> /// <returns></returns> protected IEnumerable<Token<ModelTokenType>> GetTokens(BinaryReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } this.Reader = reader; using (reader) { List<Token<ModelTokenType>> tokens = new List<Token<ModelTokenType>>(); BsonTokenizer.ReadDocument(tokens, reader, false); this.Reader = BsonTokenizer.NullBinaryReader; return tokens; }; } #endregion IBinaryTokenizer<ModelTokenType> Members #region IDisposable Members public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { ((IDisposable)this.Reader).Dispose(); } } #endregion IDisposable Members } } }
using System; using NUnit.Framework; using Underscore.Function; namespace Underscore.Test.Boolean { // Generated using /codegen/boolean_negate_test.py [TestFixture] public class NegateTest { private NegateComponent component; [SetUp] public void Initialize() { component = new NegateComponent(); } [Test] public void Function_Boolean_Negate_NoArguments_TrueInput() { Func<bool> toNegate = () => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated()); } [Test] public void Function_Boolean_Negate_NoArguments_FalseInput() { Func<bool> toNegate = () => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated()); } [Test] public void Function_Boolean_Negate_1Argument_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, bool> toNegate = (a) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj)); } [Test] public void Function_Boolean_Negate_1Argument_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, bool> toNegate = (a) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj)); } [Test] public void Function_Boolean_Negate_2Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, bool> toNegate = (a, b) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj)); } [Test] public void Function_Boolean_Negate_2Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, bool> toNegate = (a, b) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj)); } [Test] public void Function_Boolean_Negate_3Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, bool> toNegate = (a, b, c) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj)); } [Test] public void Function_Boolean_Negate_3Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, bool> toNegate = (a, b, c) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj)); } [Test] public void Function_Boolean_Negate_4Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, bool> toNegate = (a, b, c, d) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_4Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, bool> toNegate = (a, b, c, d) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_5Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, bool> toNegate = (a, b, c, d, e) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_5Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, bool> toNegate = (a, b, c, d, e) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_6Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_6Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_7Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_7Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_8Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_8Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_9Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_9Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_10Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_10Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_11Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_11Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_12Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_12Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_13Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_13Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_14Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_14Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_15Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_15Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_16Arguments_TrueInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => true; var negated = _.Function.Negate(toNegate); Assert.IsFalse(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } [Test] public void Function_Boolean_Negate_16Arguments_FalseInput() { // this is just used to fill params var obj = new object(); Func<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, bool> toNegate = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => false; var negated = _.Function.Negate(toNegate); Assert.IsTrue(negated(obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj)); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { internal class SocketManager { private readonly LRU<IPEndPoint, Socket> cache; private TimeSpan connectionTimeout; private const int MAX_SOCKETS = 200; internal SocketManager(IMessagingConfiguration config) { connectionTimeout = config.OpenConnectionTimeout; cache = new LRU<IPEndPoint, Socket>(MAX_SOCKETS, config.MaxSocketAge, SendingSocketCreator); cache.RaiseFlushEvent += FlushHandler; } /// <summary> /// Creates a socket bound to an address for use accepting connections. /// This is for use by client gateways and other acceptors. /// </summary> /// <param name="address">The address to bind to.</param> /// <returns>The new socket, appropriately bound.</returns> internal static Socket GetAcceptingSocketForEndpoint(IPEndPoint address) { var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { // Prep the socket so it will reset on close s.LingerState = new LingerOption(true, 0); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // And bind it to the address s.Bind(address); } catch (Exception) { CloseSocket(s); throw; } return s; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool CheckSendingSocket(IPEndPoint target) { return cache.ContainsKey(target); } internal Socket GetSendingSocket(IPEndPoint target) { return cache.Get(target); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Socket SendingSocketCreator(IPEndPoint target) { var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { Connect(s, target, connectionTimeout); // Prep the socket so it will reset on close and won't Nagle s.LingerState = new LingerOption(true, 0); s.NoDelay = true; WriteConnectionPreamble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket // Start an asynch receive off of the socket to detect closure var receiveAsyncEventArgs = new SocketAsyncEventArgs { BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[4]) }, UserToken = new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this) }; receiveAsyncEventArgs.Completed += ReceiveCallback; bool receiveCompleted = s.ReceiveAsync(receiveAsyncEventArgs); NetworkingStatisticsGroup.OnOpenedSendingSocket(); if (!receiveCompleted) { ReceiveCallback(this, receiveAsyncEventArgs); } } catch (Exception) { try { s.Dispose(); } catch (Exception) { // ignore } throw; } return s; } internal static void WriteConnectionPreamble(Socket socket, GrainId grainId) { int size = 0; byte[] grainIdByteArray = null; if (grainId != null) { grainIdByteArray = grainId.ToByteArray(); size += grainIdByteArray.Length; } ByteArrayBuilder sizeArray = new ByteArrayBuilder(); sizeArray.Append(size); socket.Send(sizeArray.ToBytes()); // The size of the data that is coming next. //socket.Send(guid.ToByteArray()); // The guid of client/silo id if (grainId != null) { // No need to send in a loop. // From MSDN: If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent, // unless a time-out was set by using Socket.SendTimeout. // If the time-out value was exceeded, the Send call will throw a SocketException. socket.Send(grainIdByteArray); // The grainId of the client } } // We start an asynch receive, with this callback, off of every send socket. // Since we should never see data coming in on these sockets, having the receive complete means that // the socket is in an unknown state and we should close it and try again. private static void ReceiveCallback(object sender, SocketAsyncEventArgs socketAsyncEventArgs) { var t = socketAsyncEventArgs.UserToken as Tuple<Socket, IPEndPoint, SocketManager>; try { t?.Item3.InvalidateEntry(t.Item2); } catch (Exception ex) { LogManager.GetLogger("SocketManager", LoggerType.Runtime).Error(ErrorCode.Messaging_Socket_ReceiveError, $"ReceiveCallback: {t?.Item2}", ex); } finally { socketAsyncEventArgs.Dispose(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s")] internal void ReturnSendingSocket(Socket s) { // Do nothing -- the socket will get cleaned up when it gets flushed from the cache } private static void FlushHandler(Object sender, LRU<IPEndPoint, Socket>.FlushEventArgs args) { if (args.Value == null) return; CloseSocket(args.Value); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void InvalidateEntry(IPEndPoint target) { Socket socket; if (!cache.RemoveKey(target, out socket)) return; CloseSocket(socket); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // Note that this method assumes that there are no other threads accessing this object while this method runs. // Since this is true for the MessageCenter's use of this object, we don't lock around all calls to avoid the overhead. internal void Stop() { // Clear() on an LRU<> calls the flush handler on every item, so no need to manually close the sockets. cache.Clear(); } /// <summary> /// Connect the socket to the target endpoint /// </summary> /// <param name="s">The socket</param> /// <param name="endPoint">The target endpoint</param> /// <param name="connectionTimeout">The timeout value to use when opening the connection</param> /// <exception cref="TimeoutException">When the connection could not be established in time</exception> internal static void Connect(Socket s, IPEndPoint endPoint, TimeSpan connectionTimeout) { var signal = new AutoResetEvent(false); var e = new SocketAsyncEventArgs(); e.RemoteEndPoint = endPoint; e.Completed += (sender, eventArgs) => signal.Set(); s.ConnectAsync(e); if (!signal.WaitOne(connectionTimeout)) throw new TimeoutException($"Connection to {endPoint} could not be established in {connectionTimeout}"); if (e.SocketError != SocketError.Success || !s.Connected) throw new OrleansException($"Could not connect to {endPoint}: {e.SocketError}"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static void CloseSocket(Socket s) { if (s == null) { return; } try { s.Shutdown(SocketShutdown.Both); } catch (ObjectDisposedException) { // Socket is already closed -- we're done here return; } catch (Exception) { // Ignore } #if !NETSTANDARD try { s.Disconnect(false); } catch (Exception) { // Ignore } #endif try { s.Dispose(); } catch (Exception) { // Ignore } } } }
// 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.Threading; interface IGen<T> { void Target(object p); T Dummy(T t); } struct GenInt : IGen<int> { public int Dummy(int t) { return t; } public void Target(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest() { ManualResetEvent evt = new ManualResetEvent(false); IGen<int> obj = new GenInt(); TimerCallback tcb = new TimerCallback(obj.Target); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } struct GenDouble : IGen<double> { public double Dummy(double t) { return t; } public void Target(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest() { ManualResetEvent evt = new ManualResetEvent(false); IGen<double> obj = new GenDouble(); TimerCallback tcb = new TimerCallback(obj.Target); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } struct GenString : IGen<string> { public string Dummy(string t) { return t; } public void Target(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest() { ManualResetEvent evt = new ManualResetEvent(false); IGen<string> obj = new GenString(); TimerCallback tcb = new TimerCallback(obj.Target); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } struct GenObject : IGen<object> { public object Dummy(object t) { return t; } public void Target(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest() { ManualResetEvent evt = new ManualResetEvent(false); IGen<object> obj = new GenObject(); TimerCallback tcb = new TimerCallback(obj.Target); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } struct GenGuid : IGen<Guid> { public Guid Dummy(Guid t) { return t; } public void Target(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest() { ManualResetEvent evt = new ManualResetEvent(false); IGen<Guid> obj = new GenGuid(); TimerCallback tcb = new TimerCallback(obj.Target); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } public class Test { public static int delay = 0; public static int period = 2; public static int nThreads = 5; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { GenInt.ThreadPoolTest(); GenDouble.ThreadPoolTest(); GenString.ThreadPoolTest(); GenObject.ThreadPoolTest(); GenGuid.ThreadPoolTest(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. 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 additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Globalization; using fyiReporting.RdlDesign.Resources; namespace fyiReporting.RdlDesign { /// <summary> /// FontCtl /// </summary> internal class FontCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; private bool fHorzAlign, fFormat, fDirection, fWritingMode, fTextDecoration; private bool fColor, fVerticalAlign, fFontStyle, fFontWeight, fFontSize, fFontFamily; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label lFont; private System.Windows.Forms.Button bFont; private System.Windows.Forms.ComboBox cbHorzAlign; private System.Windows.Forms.ComboBox cbFormat; private System.Windows.Forms.ComboBox cbDirection; private System.Windows.Forms.ComboBox cbWritingMode; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbTextDecoration; private System.Windows.Forms.Button bColor; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox cbColor; private System.Windows.Forms.ComboBox cbVerticalAlign; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cbFontStyle; private System.Windows.Forms.ComboBox cbFontWeight; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox cbFontSize; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox cbFontFamily; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button bFamily; private System.Windows.Forms.Button bStyle; private System.Windows.Forms.Button bColorEx; private System.Windows.Forms.Button bSize; private System.Windows.Forms.Button bWeight; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button bAlignment; private System.Windows.Forms.Button bDirection; private System.Windows.Forms.Button bVertical; private System.Windows.Forms.Button bWrtMode; private System.Windows.Forms.Button bFormat; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private string[] _names; internal FontCtl(DesignXmlDraw dxDraw, string[] names, List<XmlNode> styles) { _ReportItems = styles; _Draw = dxDraw; _names = names; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitTextStyles(); } private void InitTextStyles() { cbColor.Items.AddRange(StaticLists.ColorList); cbFormat.Items.AddRange(StaticLists.FormatList); XmlNode sNode = _ReportItems[0]; if (_names != null) { sNode = _Draw.FindCreateNextInHierarchy(sNode, _names); } sNode = _Draw.GetCreateNamedChildNode(sNode, "Style"); string sFontStyle="Normal"; string sFontFamily="Arial"; string sFontWeight="Normal"; string sFontSize="10pt"; string sTextDecoration="None"; string sHorzAlign="General"; string sVerticalAlign="Top"; string sColor="Black"; string sFormat=""; string sDirection="LTR"; string sWritingMode="lr-tb"; foreach (XmlNode lNode in sNode) { if (lNode.NodeType != XmlNodeType.Element) continue; switch (lNode.Name) { case "FontStyle": sFontStyle = lNode.InnerText; break; case "FontFamily": sFontFamily = lNode.InnerText; break; case "FontWeight": sFontWeight = lNode.InnerText; break; case "FontSize": sFontSize = lNode.InnerText; break; case "TextDecoration": sTextDecoration = lNode.InnerText; break; case "TextAlign": sHorzAlign = lNode.InnerText; break; case "VerticalAlign": sVerticalAlign = lNode.InnerText; break; case "Color": sColor = lNode.InnerText; break; case "Format": sFormat = lNode.InnerText; break; case "Direction": sDirection = lNode.InnerText; break; case "WritingMode": sWritingMode = lNode.InnerText; break; } } // Population Font Family dropdown foreach (FontFamily ff in FontFamily.Families) { cbFontFamily.Items.Add(ff.Name); } this.cbFontStyle.Text = sFontStyle; this.cbFontFamily.Text = sFontFamily; this.cbFontWeight.Text = sFontWeight; this.cbFontSize.Text = sFontSize; this.cbTextDecoration.Text = sTextDecoration; this.cbHorzAlign.Text = sHorzAlign; this.cbVerticalAlign.Text = sVerticalAlign; this.cbColor.Text = sColor; this.cbFormat.Text = sFormat; this.cbDirection.Text = sDirection; this.cbWritingMode.Text = sWritingMode; fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration = fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = false; return; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FontCtl)); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.lFont = new System.Windows.Forms.Label(); this.bFont = new System.Windows.Forms.Button(); this.cbVerticalAlign = new System.Windows.Forms.ComboBox(); this.cbHorzAlign = new System.Windows.Forms.ComboBox(); this.cbFormat = new System.Windows.Forms.ComboBox(); this.cbDirection = new System.Windows.Forms.ComboBox(); this.cbWritingMode = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.cbTextDecoration = new System.Windows.Forms.ComboBox(); this.bColor = new System.Windows.Forms.Button(); this.label9 = new System.Windows.Forms.Label(); this.cbColor = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.cbFontStyle = new System.Windows.Forms.ComboBox(); this.cbFontWeight = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.cbFontSize = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.cbFontFamily = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button2 = new System.Windows.Forms.Button(); this.bWeight = new System.Windows.Forms.Button(); this.bSize = new System.Windows.Forms.Button(); this.bColorEx = new System.Windows.Forms.Button(); this.bStyle = new System.Windows.Forms.Button(); this.bFamily = new System.Windows.Forms.Button(); this.bAlignment = new System.Windows.Forms.Button(); this.bDirection = new System.Windows.Forms.Button(); this.bVertical = new System.Windows.Forms.Button(); this.bWrtMode = new System.Windows.Forms.Button(); this.bFormat = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // lFont // resources.ApplyResources(this.lFont, "lFont"); this.lFont.Name = "lFont"; // // bFont // resources.ApplyResources(this.bFont, "bFont"); this.bFont.Name = "bFont"; this.bFont.Click += new System.EventHandler(this.bFont_Click); // // cbVerticalAlign // resources.ApplyResources(this.cbVerticalAlign, "cbVerticalAlign"); this.cbVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbVerticalAlign.Items.AddRange(new object[] { resources.GetString("cbVerticalAlign.Items"), resources.GetString("cbVerticalAlign.Items1"), resources.GetString("cbVerticalAlign.Items2")}); this.cbVerticalAlign.Name = "cbVerticalAlign"; this.cbVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged); this.cbVerticalAlign.TextChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged); // // cbHorzAlign // resources.ApplyResources(this.cbHorzAlign, "cbHorzAlign"); this.cbHorzAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbHorzAlign.Items.AddRange(new object[] { resources.GetString("cbHorzAlign.Items"), resources.GetString("cbHorzAlign.Items1"), resources.GetString("cbHorzAlign.Items2"), resources.GetString("cbHorzAlign.Items3")}); this.cbHorzAlign.Name = "cbHorzAlign"; this.cbHorzAlign.SelectedIndexChanged += new System.EventHandler(this.cbHorzAlign_TextChanged); this.cbHorzAlign.TextChanged += new System.EventHandler(this.cbHorzAlign_TextChanged); // // cbFormat // resources.ApplyResources(this.cbFormat, "cbFormat"); this.cbFormat.Name = "cbFormat"; this.cbFormat.TextChanged += new System.EventHandler(this.cbFormat_TextChanged); // // cbDirection // resources.ApplyResources(this.cbDirection, "cbDirection"); this.cbDirection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDirection.Items.AddRange(new object[] { resources.GetString("cbDirection.Items"), resources.GetString("cbDirection.Items1")}); this.cbDirection.Name = "cbDirection"; this.cbDirection.SelectedIndexChanged += new System.EventHandler(this.cbDirection_TextChanged); this.cbDirection.TextChanged += new System.EventHandler(this.cbDirection_TextChanged); // // cbWritingMode // resources.ApplyResources(this.cbWritingMode, "cbWritingMode"); this.cbWritingMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbWritingMode.Items.AddRange(new object[] { resources.GetString("cbWritingMode.Items"), resources.GetString("cbWritingMode.Items1")}); this.cbWritingMode.Name = "cbWritingMode"; this.cbWritingMode.SelectedIndexChanged += new System.EventHandler(this.cbWritingMode_TextChanged); this.cbWritingMode.TextChanged += new System.EventHandler(this.cbWritingMode_TextChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // cbTextDecoration // resources.ApplyResources(this.cbTextDecoration, "cbTextDecoration"); this.cbTextDecoration.Items.AddRange(new object[] { resources.GetString("cbTextDecoration.Items"), resources.GetString("cbTextDecoration.Items1"), resources.GetString("cbTextDecoration.Items2"), resources.GetString("cbTextDecoration.Items3")}); this.cbTextDecoration.Name = "cbTextDecoration"; this.cbTextDecoration.SelectedIndexChanged += new System.EventHandler(this.cbTextDecoration_TextChanged); this.cbTextDecoration.TextChanged += new System.EventHandler(this.cbTextDecoration_TextChanged); // // bColor // resources.ApplyResources(this.bColor, "bColor"); this.bColor.Name = "bColor"; this.bColor.Click += new System.EventHandler(this.bColor_Click); // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // cbColor // resources.ApplyResources(this.cbColor, "cbColor"); this.cbColor.Name = "cbColor"; this.cbColor.TextChanged += new System.EventHandler(this.cbColor_TextChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // cbFontStyle // resources.ApplyResources(this.cbFontStyle, "cbFontStyle"); this.cbFontStyle.Items.AddRange(new object[] { resources.GetString("cbFontStyle.Items"), resources.GetString("cbFontStyle.Items1")}); this.cbFontStyle.Name = "cbFontStyle"; this.cbFontStyle.TextChanged += new System.EventHandler(this.cbFontStyle_TextChanged); // // cbFontWeight // resources.ApplyResources(this.cbFontWeight, "cbFontWeight"); this.cbFontWeight.Items.AddRange(new object[] { resources.GetString("cbFontWeight.Items"), resources.GetString("cbFontWeight.Items1"), resources.GetString("cbFontWeight.Items2"), resources.GetString("cbFontWeight.Items3"), resources.GetString("cbFontWeight.Items4"), resources.GetString("cbFontWeight.Items5"), resources.GetString("cbFontWeight.Items6"), resources.GetString("cbFontWeight.Items7"), resources.GetString("cbFontWeight.Items8"), resources.GetString("cbFontWeight.Items9"), resources.GetString("cbFontWeight.Items10"), resources.GetString("cbFontWeight.Items11"), resources.GetString("cbFontWeight.Items12")}); this.cbFontWeight.Name = "cbFontWeight"; this.cbFontWeight.TextChanged += new System.EventHandler(this.cbFontWeight_TextChanged); // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // cbFontSize // resources.ApplyResources(this.cbFontSize, "cbFontSize"); this.cbFontSize.Items.AddRange(new object[] { resources.GetString("cbFontSize.Items"), resources.GetString("cbFontSize.Items1"), resources.GetString("cbFontSize.Items2"), resources.GetString("cbFontSize.Items3"), resources.GetString("cbFontSize.Items4"), resources.GetString("cbFontSize.Items5"), resources.GetString("cbFontSize.Items6"), resources.GetString("cbFontSize.Items7"), resources.GetString("cbFontSize.Items8"), resources.GetString("cbFontSize.Items9"), resources.GetString("cbFontSize.Items10"), resources.GetString("cbFontSize.Items11"), resources.GetString("cbFontSize.Items12"), resources.GetString("cbFontSize.Items13"), resources.GetString("cbFontSize.Items14"), resources.GetString("cbFontSize.Items15")}); this.cbFontSize.Name = "cbFontSize"; this.cbFontSize.TextChanged += new System.EventHandler(this.cbFontSize_TextChanged); // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // cbFontFamily // resources.ApplyResources(this.cbFontFamily, "cbFontFamily"); this.cbFontFamily.Items.AddRange(new object[] { resources.GetString("cbFontFamily.Items")}); this.cbFontFamily.Name = "cbFontFamily"; this.cbFontFamily.TextChanged += new System.EventHandler(this.cbFontFamily_TextChanged); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.cbFontFamily); this.groupBox1.Controls.Add(this.cbTextDecoration); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.bWeight); this.groupBox1.Controls.Add(this.bSize); this.groupBox1.Controls.Add(this.bColorEx); this.groupBox1.Controls.Add(this.bStyle); this.groupBox1.Controls.Add(this.bFamily); this.groupBox1.Controls.Add(this.lFont); this.groupBox1.Controls.Add(this.bFont); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.bColor); this.groupBox1.Controls.Add(this.label9); this.groupBox1.Controls.Add(this.cbColor); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.cbFontStyle); this.groupBox1.Controls.Add(this.cbFontWeight); this.groupBox1.Controls.Add(this.label10); this.groupBox1.Controls.Add(this.cbFontSize); this.groupBox1.Controls.Add(this.label11); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // button2 // resources.ApplyResources(this.button2, "button2"); this.button2.Name = "button2"; this.button2.Tag = "decoration"; this.button2.Click += new System.EventHandler(this.bExpr_Click); // // bWeight // resources.ApplyResources(this.bWeight, "bWeight"); this.bWeight.Name = "bWeight"; this.bWeight.Tag = "weight"; this.bWeight.Click += new System.EventHandler(this.bExpr_Click); // // bSize // resources.ApplyResources(this.bSize, "bSize"); this.bSize.Name = "bSize"; this.bSize.Tag = "size"; this.bSize.Click += new System.EventHandler(this.bExpr_Click); // // bColorEx // resources.ApplyResources(this.bColorEx, "bColorEx"); this.bColorEx.Name = "bColorEx"; this.bColorEx.Tag = "color"; this.bColorEx.Click += new System.EventHandler(this.bExpr_Click); // // bStyle // resources.ApplyResources(this.bStyle, "bStyle"); this.bStyle.Name = "bStyle"; this.bStyle.Tag = "style"; this.bStyle.Click += new System.EventHandler(this.bExpr_Click); // // bFamily // resources.ApplyResources(this.bFamily, "bFamily"); this.bFamily.Name = "bFamily"; this.bFamily.Tag = "family"; this.bFamily.Click += new System.EventHandler(this.bExpr_Click); // // bAlignment // resources.ApplyResources(this.bAlignment, "bAlignment"); this.bAlignment.Name = "bAlignment"; this.bAlignment.Tag = "halign"; this.bAlignment.Click += new System.EventHandler(this.bExpr_Click); // // bDirection // resources.ApplyResources(this.bDirection, "bDirection"); this.bDirection.Name = "bDirection"; this.bDirection.Tag = "direction"; this.bDirection.Click += new System.EventHandler(this.bExpr_Click); // // bVertical // resources.ApplyResources(this.bVertical, "bVertical"); this.bVertical.Name = "bVertical"; this.bVertical.Tag = "valign"; this.bVertical.Click += new System.EventHandler(this.bExpr_Click); // // bWrtMode // resources.ApplyResources(this.bWrtMode, "bWrtMode"); this.bWrtMode.Name = "bWrtMode"; this.bWrtMode.Tag = "writing"; this.bWrtMode.Click += new System.EventHandler(this.bExpr_Click); // // bFormat // resources.ApplyResources(this.bFormat, "bFormat"); this.bFormat.Name = "bFormat"; this.bFormat.Tag = "format"; this.bFormat.Click += new System.EventHandler(this.bExpr_Click); // // FontCtl // resources.ApplyResources(this, "$this"); this.Controls.Add(this.bFormat); this.Controls.Add(this.bWrtMode); this.Controls.Add(this.bVertical); this.Controls.Add(this.bDirection); this.Controls.Add(this.bAlignment); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cbWritingMode); this.Controls.Add(this.cbDirection); this.Controls.Add(this.cbFormat); this.Controls.Add(this.cbHorzAlign); this.Controls.Add(this.cbVerticalAlign); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Name = "FontCtl"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion public bool IsValid() { if (fFontSize) { try { if (!this.cbFontSize.Text.Trim().StartsWith("=")) DesignerUtility.ValidateSize(this.cbFontSize.Text, false, false); } catch (Exception e) { MessageBox.Show(e.Message, Strings.FontCtl_Show_InvalidFontSize); return false; } } return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration = fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = false; } public void ApplyChanges(XmlNode node) { if (_names != null) { node = _Draw.FindCreateNextInHierarchy(node, _names); } XmlNode sNode = _Draw.GetCreateNamedChildNode(node, "Style"); if (fFontStyle) _Draw.SetElement(sNode, "FontStyle", cbFontStyle.Text); if (fFontFamily) _Draw.SetElement(sNode, "FontFamily", cbFontFamily.Text); if (fFontWeight) _Draw.SetElement(sNode, "FontWeight", cbFontWeight.Text); if (fFontSize) { float size=10; size = DesignXmlDraw.GetSize(cbFontSize.Text); if (size <= 0) { size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt if (size <= 0) // still no good size = 10; // just set default value } string rs = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.#}pt", size); _Draw.SetElement(sNode, "FontSize", rs); // force to string } if (fTextDecoration) _Draw.SetElement(sNode, "TextDecoration", cbTextDecoration.Text); if (fHorzAlign) _Draw.SetElement(sNode, "TextAlign", cbHorzAlign.Text); if (fVerticalAlign) _Draw.SetElement(sNode, "VerticalAlign", cbVerticalAlign.Text); if (fColor) _Draw.SetElement(sNode, "Color", cbColor.Text); if (fFormat) { if (cbFormat.Text.Length == 0) // Don't put out a format if no format value _Draw.RemoveElement(sNode, "Format"); else _Draw.SetElement(sNode, "Format", cbFormat.Text); } if (fDirection) _Draw.SetElement(sNode, "Direction", cbDirection.Text); if (fWritingMode) _Draw.SetElement(sNode, "WritingMode", cbWritingMode.Text); return; } private void bFont_Click(object sender, System.EventArgs e) { FontDialog fd = new FontDialog(); fd.ShowColor = true; // STYLE System.Drawing.FontStyle fs = 0; if (cbFontStyle.Text == "Italic") fs |= System.Drawing.FontStyle.Italic; if (cbTextDecoration.Text == "Underline") fs |= FontStyle.Underline; else if (cbTextDecoration.Text == "LineThrough") fs |= FontStyle.Strikeout; // WEIGHT switch (cbFontWeight.Text) { case "Bold": case "Bolder": case "500": case "600": case "700": case "800": case "900": fs |= System.Drawing.FontStyle.Bold; break; default: break; } float size=10; size = DesignXmlDraw.GetSize(cbFontSize.Text); if (size <= 0) { size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt if (size <= 0) // still no good size = 10; // just set default value } Font drawFont = new Font(cbFontFamily.Text, size, fs); // si.FontSize already in points fd.Font = drawFont; fd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black); try { DialogResult dr = fd.ShowDialog(); if (dr != DialogResult.OK) { drawFont.Dispose(); return; } // Apply all the font info cbFontWeight.Text = fd.Font.Bold ? "Bold" : "Normal"; cbFontStyle.Text = fd.Font.Italic ? "Italic" : "Normal"; cbFontFamily.Text = fd.Font.FontFamily.Name; cbFontSize.Text = fd.Font.Size.ToString() + "pt"; cbColor.Text = ColorTranslator.ToHtml(fd.Color); if (fd.Font.Underline) this.cbTextDecoration.Text = "Underline"; else if (fd.Font.Strikeout) this.cbTextDecoration.Text = "LineThrough"; else this.cbTextDecoration.Text = "None"; drawFont.Dispose(); } finally { fd.Dispose(); } return; } private void bColor_Click(object sender, System.EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AnyColor = true; cd.FullOpen = true; cd.CustomColors = RdlDesigner.GetCustomColors(); cd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black); try { if (cd.ShowDialog() != DialogResult.OK) return; RdlDesigner.SetCustomColors(cd.CustomColors); if (sender == this.bColor) cbColor.Text = ColorTranslator.ToHtml(cd.Color); } finally { cd.Dispose(); } return; } private void cbFontFamily_TextChanged(object sender, System.EventArgs e) { fFontFamily = true; } private void cbFontSize_TextChanged(object sender, System.EventArgs e) { fFontSize = true; } private void cbFontStyle_TextChanged(object sender, System.EventArgs e) { fFontStyle = true; } private void cbFontWeight_TextChanged(object sender, System.EventArgs e) { fFontWeight = true; } private void cbColor_TextChanged(object sender, System.EventArgs e) { fColor = true; } private void cbTextDecoration_TextChanged(object sender, System.EventArgs e) { fTextDecoration = true; } private void cbHorzAlign_TextChanged(object sender, System.EventArgs e) { fHorzAlign = true; } private void cbVerticalAlign_TextChanged(object sender, System.EventArgs e) { fVerticalAlign = true; } private void cbDirection_TextChanged(object sender, System.EventArgs e) { fDirection = true; } private void cbWritingMode_TextChanged(object sender, System.EventArgs e) { fWritingMode = true; } private void cbFormat_TextChanged(object sender, System.EventArgs e) { fFormat = true; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; bool bColor=false; switch (b.Tag as string) { case "family": c = cbFontFamily; break; case "style": c = cbFontStyle; break; case "color": c = cbColor; bColor = true; break; case "size": c = cbFontSize; break; case "weight": c = cbFontWeight; break; case "decoration": c = cbTextDecoration; break; case "halign": c = cbHorzAlign; break; case "valign": c = cbVerticalAlign; break; case "direction": c = cbDirection; break; case "writing": c = cbWritingMode; break; case "format": c = cbFormat; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } finally { ee.Dispose(); } return; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.AspNet.PortalBus { using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Adxstudio.Xrm.AspNet.Cms; using Adxstudio.Xrm.IO; using Adxstudio.Xrm.Web; using global::Owin; using Microsoft.Owin; using Microsoft.Owin.BuilderProperties; using Microsoft.Practices.TransientFaultHandling; using Newtonsoft.Json; /// <summary> /// Settings related to the <see cref="AppDataPortalBusProvider{TMessage}"/>. /// </summary> /// <typeparam name="TMessage"></typeparam> public class AppDataPortalBusOptions<TMessage> { public string AppDataPath { get; set; } public string InstanceId { get; set; } public TimeSpan Timeout { get; set; } public RetryPolicy RetryPolicy { get; set; } public AppDataPortalBusOptions(WebAppSettings webAppSettings) { var retryStrategy = new Incremental(5, new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 1)); this.AppDataPath = "~/App_Data/Adxstudio.Xrm.AspNet.PortalBus/" + typeof(TMessage).Name; this.InstanceId = webAppSettings.InstanceId; this.Timeout = TimeSpan.FromMinutes(5); this.RetryPolicy = retryStrategy.CreateRetryPolicy(); } } /// <summary> /// A portal bus that uses a shared filesystem (App_Data) folder for sending messages to remote instances. /// </summary> /// <typeparam name="TMessage"></typeparam> public class AppDataPortalBusProvider<TMessage> : PortalBusProvider<TMessage> { private static readonly JsonSerializer _serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore }; protected string AppDataFullPath { get; private set; } protected AppDataPortalBusOptions<TMessage> Options { get; private set; } public AppDataPortalBusProvider(IAppBuilder app, AppDataPortalBusOptions<TMessage> options) : base(app) { this.AppDataFullPath = options.AppDataPath.StartsWith("~/") ? System.Web.Hosting.HostingEnvironment.MapPath(options.AppDataPath) : options.AppDataPath; this.Options = options; this.RegisterAppDisposing(app); this.Subscribe(); } protected void RegisterAppDisposing(IAppBuilder app) { var properties = new AppProperties(app.Properties); var token = properties.OnAppDisposing; if (token != CancellationToken.None) { token.Register(this.OnAppDisposing); } } protected virtual void OnAppDisposing() { var subscriptionPath = Path.Combine(this.AppDataFullPath, this.Options.InstanceId); if (this.Options.RetryPolicy.DirectoryExists(subscriptionPath)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Delete: subscriptionPath={0}", subscriptionPath)); this.Options.RetryPolicy.DirectoryDelete(subscriptionPath, true); } } #region Subscribe Members protected void Subscribe() { // watch for renamed files which indicates messages ready for handling var buffer = new BufferBlock<string>(); var subscriptionPath = this.GetSubscriptionPath(); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Subscribe: subscriptionPath={0}", subscriptionPath)); try { var watcher = this.Options.RetryPolicy.CreateFileSystemWatcher(subscriptionPath); watcher.Renamed += (sender, args) => buffer.Post(args.FullPath); watcher.Error += async (sender, args) => await this.OnSubscriptionErrorAsync(args.GetException()).WithCurrentCulture(); } catch (Exception e) { WebEventSource.Log.GenericErrorException(e); if (this.Options.RetryPolicy.DirectoryExists(subscriptionPath)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Delete: subscriptionPath={0}", subscriptionPath)); this.Options.RetryPolicy.DirectoryDelete(subscriptionPath, true); } throw; } var action = new ActionBlock<string>(this.OnSubscriptionChangedAsync).AsObserver(); buffer.AsObservable().Subscribe(action); } protected virtual string GetSubscriptionPath() { var subscriptionPath = Path.Combine(this.AppDataFullPath, this.Options.InstanceId); if (this.Options.RetryPolicy.DirectoryExists(subscriptionPath)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Exists: subscriptionPath={0}", subscriptionPath)); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Create: subscriptionPath={0}", subscriptionPath)); this.Options.RetryPolicy.DirectoryCreate(subscriptionPath); } return subscriptionPath; } protected virtual IOwinContext GetOwinContext() { return new OwinContext(); } protected virtual Task OnSubscriptionErrorAsync(Exception error) { WebEventSource.Log.GenericErrorException(new Exception("Subscription error: InstanceId: " + this.Options.InstanceId, error)); return Task.FromResult(0); } protected virtual async Task OnSubscriptionChangedAsync(string messagePath) { try { if (!this.Options.RetryPolicy.FileExists(messagePath)) return; var context = this.GetOwinContext(); var message = this.Deserialize(messagePath) as IPortalBusMessage; if (message != null && message.Validate(context, this.Protector)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("messagePath={0}", messagePath)); await message.InvokeAsync(context).WithCurrentCulture(); } // clean up the file this.Options.RetryPolicy.FileDelete(messagePath); } catch (Exception e) { WebEventSource.Log.GenericErrorException(new Exception("Subscription error: InstanceId: " + this.Options.InstanceId, e)); } } protected virtual TMessage Deserialize(string messagePath) { using (var reader = this.Options.RetryPolicy.OpenText(messagePath)) using (var jr = new JsonTextReader(reader)) { return _serializer.Deserialize<TMessage>(jr); } } #endregion #region Send Members protected override async Task SendRemoteAsync(IOwinContext context, TMessage message) { if (!this.Options.RetryPolicy.DirectoryExists(this.AppDataFullPath)) { return; } var directory = this.Options.RetryPolicy.GetDirectory(this.AppDataFullPath); var subscriptions = this.Options.RetryPolicy.GetDirectories(directory, "*") .Where(subscription => !string.Equals(subscription.Name, this.Options.InstanceId)); foreach (var subscription in subscriptions) { await this.WriteMessage(this.Options.Timeout, subscription.FullName, message).WithCurrentCulture(); } } protected virtual Task WriteMessage(TimeSpan timeout, string subscriptionPath, TMessage message) { // clean up expired files var directory = this.Options.RetryPolicy.GetDirectory(subscriptionPath); var expired = this.Options.RetryPolicy.GetFiles(directory, "*.msg") .Where(file => file.LastAccessTimeUtc + timeout < DateTime.UtcNow) .ToArray(); foreach (var file in expired) { try { this.Options.RetryPolicy.FileDelete(file); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString()); } } var name = GetFilename(message); var tempPath = Path.Combine(subscriptionPath, name + ".lock.msg"); var messagePath = Path.Combine(subscriptionPath, name + ".msg"); // write to a temporary file using (var fs = this.Options.RetryPolicy.Open(tempPath, FileMode.CreateNew)) using (var sw = new StreamWriter(fs)) using (var jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; _serializer.Serialize(jw, message); } // rename to the destination file this.Options.RetryPolicy.FileMove(tempPath, messagePath); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("messagePath={0}", messagePath)); return Task.FromResult(0); } private static string GetFilename(TMessage message) { var pbm = message as PortalBusMessage; return pbm != null && !string.IsNullOrWhiteSpace(pbm.Id) ? pbm.Id : Guid.NewGuid().ToString(); } #endregion } }
// Copyright 2018 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 Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201809; using System; using System.Collections.Generic; using System.Text; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example gets the changes in the account during the last 24 /// hours. /// </summary> public class GetAccountChanges : ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { GetAccountChanges codeExample = new GetAccountChanges(); Console.WriteLine(codeExample.Description); try { codeExample.Run(new AdWordsUser()); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example gets the changes in the account during the last 24 hours."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (CustomerSyncService customerSyncService = (CustomerSyncService) user.GetService(AdWordsService.v201809.CustomerSyncService)) { // The date time string should be of the form yyyyMMdd HHmmss zzz string minDateTime = DateTime.Now.AddDays(-1).ToUniversalTime().ToString("yyyyMMdd HHmmss") + " UTC"; string maxDateTime = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd HHmmss") + " UTC"; // Create date time range. DateTimeRange dateTimeRange = new DateTimeRange { min = minDateTime, max = maxDateTime }; try { // Create the selector. CustomerSyncSelector selector = new CustomerSyncSelector { dateTimeRange = dateTimeRange, campaignIds = GetAllCampaignIds(user) }; // Get all account changes for campaign. CustomerChangeData accountChanges = customerSyncService.get(selector); // Display the changes. if (accountChanges != null && accountChanges.changedCampaigns != null) { Console.WriteLine("Displaying changes up to: {0}", accountChanges.lastChangeTimestamp); foreach (CampaignChangeData campaignChanges in accountChanges .changedCampaigns) { Console.WriteLine("Campaign with id \"{0}\" was changed:", campaignChanges.campaignId); Console.WriteLine(" Campaign changed status: {0}", campaignChanges.campaignChangeStatus); if (campaignChanges.campaignChangeStatus != ChangeStatus.NEW) { Console.WriteLine(" Added campaign criteria: {0}", GetFormattedList(campaignChanges.addedCampaignCriteria)); Console.WriteLine(" Removed campaign criteria: {0}", GetFormattedList(campaignChanges.removedCampaignCriteria)); if (campaignChanges.changedAdGroups != null) { foreach (AdGroupChangeData adGroupChanges in campaignChanges .changedAdGroups) { Console.WriteLine(" Ad group with id \"{0}\" was changed:", adGroupChanges.adGroupId); Console.WriteLine(" Ad group changed status: {0}", adGroupChanges.adGroupChangeStatus); if (adGroupChanges.adGroupChangeStatus != ChangeStatus.NEW) { Console.WriteLine(" Ads changed: {0}", GetFormattedList(adGroupChanges.changedAds)); Console.WriteLine(" Criteria changed: {0}", GetFormattedList(adGroupChanges.changedCriteria)); Console.WriteLine(" Criteria removed: {0}", GetFormattedList(adGroupChanges.removedCriteria)); } } } } Console.WriteLine(); } } else { Console.WriteLine("No account changes were found."); } } catch (Exception e) { throw new System.ApplicationException("Failed to get account changes.", e); } } } /// <summary> /// Formats a list of ids as a comma separated string. /// </summary> /// <param name="ids">The list of ids.</param> /// <returns>The comma separed formatted string, enclosed in square braces. /// </returns> private string GetFormattedList(long[] ids) { StringBuilder builder = new StringBuilder(); if (ids != null) { foreach (long id in ids) { builder.AppendFormat("{0}, ", id); } } return "[" + builder.ToString().TrimEnd(',', ' ') + "]"; } /// <summary> /// Gets all campaign ids in the account. /// </summary> /// <param name="user">The user for which campaigns are retrieved.</param> /// <returns>The list of campaign ids.</returns> private long[] GetAllCampaignIds(AdWordsUser user) { // Get the CampaignService. using (CampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201809.CampaignService)) { List<long> allCampaigns = new List<long>(); // Create the selector. Selector selector = new Selector() { fields = new string[] { Campaign.Fields.Id } }; // Get all campaigns. CampaignPage page = campaignService.get(selector); // Return the results. if (page != null && page.entries != null) { foreach (Campaign campaign in page.entries) { allCampaigns.Add(campaign.id); } } return allCampaigns.ToArray(); } } } }
/**************************************** Simple Sprite Combine Copyright 2016 Unluck Software www.chemicalbliss.com *****************************************/ using UnityEngine; using System; using System.IO; using System.Text; using UnityEditor; using UnityEditor.Sprites; using System.Collections.Generic; using System.Collections; [CustomEditor(typeof(SimpleSpriteCombine))] public class SimpleSpriteCombineEditor : Editor { public SimpleSpriteCombine sTarget; GUIStyle buttonStyle; GUIStyle buttonStyle2; GUIStyle infoStyle; public void OnEnable() { sTarget = ((SimpleSpriteCombine)target); } public SpriteRenderer[] FindSpriteRenderers() { SpriteRenderer[] renderers = null; renderers = ((SimpleSpriteCombine)target).transform.GetComponentsInChildren<SpriteRenderer>(); return renderers; } public void ReleaseSprites() { if (sTarget.combined) DestroyImmediate(sTarget.combined); ToggleRenderers(true); sTarget.editorOnlyTagged = false; } public void CopyExcludedFromCombine() { SpriteRenderer[] renderers = FindSpriteRenderers(); if (sTarget.copyTargetExcluded) DestroyImmediate(sTarget.copyTargetExcluded); sTarget.copyTargetExcluded = new GameObject(); sTarget.copyTargetExcluded.transform.parent = sTarget.copyTarget.transform; sTarget.copyTargetExcluded.name = "Excluded [SSC Clones]"; for (int i = 0; i < renderers.Length; i++) { if (CheckExcludeFromCombine(renderers[i].gameObject)) { GameObject g = Instantiate(renderers[i].gameObject); g.transform.parent = sTarget.copyTargetExcluded.transform; } } sTarget.copyTargetExcluded.transform.localPosition = Vector3.zero; } public bool CheckExcludeFromCombine(GameObject go, bool checkPos = false) { if (sTarget.excludeFromCombine == null) return false; for (int i = 0; i < sTarget.excludeFromCombine.Length; i++) { if (checkPos && go.transform.localPosition == sTarget.excludeFromCombine[i].transform.localPosition) { return true; } else if (go == sTarget.excludeFromCombine[i]) { return true; } } return false; } public void CombineSprites() { GameObject holder = new GameObject(); holder.transform.position = sTarget.transform.position; holder.transform.rotation = sTarget.transform.rotation; holder.transform.localScale = sTarget.transform.localScale; holder.transform.parent = sTarget.transform; SpriteRenderer[] renderers = FindSpriteRenderers(); List<Material> materials = new List<Material>(); for (int i = 0; i < renderers.Length; i++) { if (renderers[i].sprite == null) continue; GameObject go = new GameObject(); go.transform.position = renderers[i].transform.position; go.transform.localScale = renderers[i].transform.localScale; go.transform.rotation = renderers[i].transform.rotation; go.transform.parent = holder.transform; MeshFilter mf = go.AddComponent<MeshFilter>(); mf.sharedMesh = ConvertSprite(renderers[i]); MeshRenderer mr = go.AddComponent<MeshRenderer>(); for (int j = 0; j < materials.Count; j++) { if (renderers[i].sprite.texture == materials[j].mainTexture) { mr.sharedMaterial = materials[j]; break; } } if(mr.sharedMaterial == null) { Material m = null; if (sTarget.useCutoutShader) { m = new Material(Shader.Find("Unlit/Transparent Cutout")); } else { m = new Material(Shader.Find("Sprites/Default")); } materials.Add(m); m.name = sTarget.transform.name + " material (" + materials.Count.ToString()+ ")"; m.mainTexture = renderers[i].sprite.texture; mr.material = m; } } CombineMeshes(); DestroyImmediate(holder); } //Returns a meshFilter[] list of all renderer enabled meshfilters(so that it does not merge disabled meshes, useful when there are invisible box colliders) public MeshFilter[] FindEnabledMeshes() { MeshFilter[] renderers = null; int count = 0; renderers = sTarget.transform.GetComponentsInChildren<MeshFilter>(); //count all the enabled meshrenderers in children for (int i = 0; i < renderers.Length; i++) { if ((renderers[i].GetComponent<MeshRenderer>() != null) && renderers[i].GetComponent<MeshRenderer>().enabled) count++; } MeshFilter[] meshfilters = new MeshFilter[count];//creates a new array with the correct length count = 0; //adds all enabled meshes to the array for (int ii = 0; ii < renderers.Length; ii++) { if ((renderers[ii].GetComponent<MeshRenderer>() != null) && renderers[ii].GetComponent<MeshRenderer>().enabled) { meshfilters[count] = renderers[ii]; count++; } } return meshfilters; } public void CombineMeshes() { GameObject combo = new GameObject(); combo.name = "_Combined Mesh [" + name + "]"; combo.gameObject.AddComponent<MeshFilter>(); combo.gameObject.AddComponent<MeshRenderer>(); MeshFilter[] meshFilters = null; meshFilters = FindEnabledMeshes(); ArrayList materials = new ArrayList(); ArrayList combineInstanceArrays = new ArrayList(); sTarget.combinedGameOjects = new GameObject[meshFilters.Length]; for (int i = 0; i < meshFilters.Length; i++) { sTarget.combinedGameOjects[i] = meshFilters[i].gameObject; MeshRenderer meshRenderer = meshFilters[i].GetComponent<MeshRenderer>(); meshFilters[i].transform.gameObject.GetComponent<Renderer>().enabled = false; if (meshFilters[i].sharedMesh == null) { Debug.LogWarning("SimpleMeshCombine : " + meshFilters[i].gameObject + " [Mesh Filter] has no [Mesh], mesh will not be included in combine.."); break; } for (int o = 0; o < meshFilters[i].sharedMesh.subMeshCount; o++) { if (meshRenderer == null) { Debug.LogWarning("SimpleMeshCombine : " + meshFilters[i].gameObject + "has a [Mesh Filter] but no [Mesh Renderer], mesh will not be included in combine."); break; } if (o < meshRenderer.sharedMaterials.Length && o < meshFilters[i].sharedMesh.subMeshCount) { int materialArrayIndex = Contains(materials, meshRenderer.sharedMaterials[o]); if (materialArrayIndex == -1) { materials.Add(meshRenderer.sharedMaterials[o]); materialArrayIndex = materials.Count - 1; } combineInstanceArrays.Add(new ArrayList()); CombineInstance combineInstance = new CombineInstance(); combineInstance.transform = meshRenderer.transform.localToWorldMatrix; combineInstance.subMeshIndex = o; combineInstance.mesh = meshFilters[i].sharedMesh; (combineInstanceArrays[materialArrayIndex] as ArrayList).Add(combineInstance); } else { Debug.LogWarning("Simple Mesh Combine: GameObject [ " + meshRenderer.gameObject.name + " ] is missing a material (Mesh or sub-mesh ignored from combine)"); } } EditorUtility.DisplayProgressBar("Combining", "", (float)i/ meshFilters.Length); } Mesh[] meshes = new Mesh[materials.Count]; CombineInstance[] combineInstances = new CombineInstance[materials.Count]; for (int m = 0; m < materials.Count; m++) { CombineInstance[] combineInstanceArray = (combineInstanceArrays[m] as ArrayList).ToArray(typeof(CombineInstance)) as CombineInstance[]; meshes[m] = new Mesh(); meshes[m].CombineMeshes(combineInstanceArray, true, true); combineInstances[m] = new CombineInstance(); combineInstances[m].mesh = meshes[m]; combineInstances[m].subMeshIndex = 0; } Mesh ms = combo.GetComponent<MeshFilter>().sharedMesh = new Mesh(); ms.Clear(); ms.CombineMeshes(combineInstances, false, false); combo.GetComponent<MeshFilter>().sharedMesh = ms;//.CombineMeshes(combineInstances, false, false); //combo.GetComponent<MeshFilter>().sharedMesh.Optimize(); foreach (Mesh mesh in meshes) { mesh.Clear(); DestroyImmediate(mesh); } MeshRenderer meshRendererCombine = combo.GetComponent<MeshFilter>().GetComponent<MeshRenderer>(); if (meshRendererCombine == null) meshRendererCombine = sTarget.gameObject.AddComponent<MeshRenderer>(); Material[] materialsArray = materials.ToArray(typeof(Material)) as Material[]; meshRendererCombine.materials = materialsArray; sTarget.combined = combo.gameObject; combo.transform.parent = sTarget.transform; ToggleRenderers(false); SpriteRenderer sr = combo.transform.parent.GetChild(0).GetComponent<SpriteRenderer>(); if(sr){ combo.GetComponent<Renderer>().sortingOrder = sr.sortingOrder; combo.GetComponent<Renderer>().sortingLayerName = sr.sortingLayerName; } sTarget.vCount = ms.vertexCount; EditorUtility.ClearProgressBar(); } public int Contains(ArrayList l, Material n) { for (int i = 0; i < l.Count; i++) { if ((l[i] as Material) == n) { return i; } } return -1; } public Mesh ConvertSprite(SpriteRenderer spriteRenderer) { Sprite sprite = spriteRenderer.sprite; spriteRenderer.transform.position = new Vector3(spriteRenderer.transform.position.x, spriteRenderer.transform.position.y, spriteRenderer.transform.position.z + (spriteRenderer.sortingOrder * sTarget.sortingOrderToZPositionMultiplier + sTarget.sortingOrderToZPositionOffset)); Mesh newMesh = new Mesh (); Vector3[] meshVerts = new Vector3[sprite.vertices.Length]; Color[] colors = new Color[sprite.vertices.Length]; Vector3[] normals = new Vector3[sprite.vertices.Length]; for (int i = 0; i < sprite.vertices.Length; i++) meshVerts[i] = sprite.vertices[i]; newMesh.vertices = meshVerts; for (int i = 0; i < sprite.vertices.Length; i++) { colors[i] = spriteRenderer.color; normals[i] = new Vector3(0 ,0 , -1); } newMesh.colors = colors; newMesh.normals = normals; newMesh.uv = SpriteUtility.GetSpriteUVs(sprite, false); int[] meshIndicies = new int[sprite.triangles.Length]; for (int i = 0; i < meshIndicies.Length; i++) meshIndicies[i] = sprite.triangles[i]; newMesh.SetIndices(meshIndicies, MeshTopology.Triangles, 0); newMesh.hideFlags = HideFlags.HideAndDontSave; return newMesh; } public void TagForExclusion(bool exclude) { SpriteRenderer[] renderers = FindSpriteRenderers(); for (int i = 0; i < renderers.Length; i++) { if (!CheckExcludeFromCombine(renderers[i].gameObject) || !exclude) { if (exclude) { sTarget.editorOnlyTagged = true; renderers[i].transform.tag = "EditorOnly"; } else { sTarget.editorOnlyTagged = false; renderers[i].transform.tag = "Untagged"; } } } } public void ToggleRenderers(bool enable) { SpriteRenderer[] renderers = FindSpriteRenderers(); for (int i = 0; i < renderers.Length; i++) { if (!CheckExcludeFromCombine(renderers[i].gameObject)) { renderers[i].enabled = enable; } } } public void ToggleColliders(bool enable) { SpriteRenderer[] renderers = FindSpriteRenderers(); for (int i = 0; i < renderers.Length; i++) { if (!CheckExcludeFromCombine(renderers[i].gameObject)) { Collider2D collider= renderers[i].GetComponent<Collider2D>(); if (collider) collider.enabled = enable; } } } public void GUISetup() { if (buttonStyle != null) return; buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle2 = new GUIStyle(GUI.skin.button); buttonStyle2.margin = new RectOffset((int)((Screen.width - 200) * .5f), (int)((Screen.width - 200) * .5f), 0, 0); buttonStyle.margin = new RectOffset((int)((Screen.width - 150) * .5f), (int)((Screen.width - 150) * .5f), 0, 0); infoStyle = new GUIStyle(GUI.skin.label); infoStyle.fontSize = 10; infoStyle.margin.top = 0; infoStyle.margin.bottom = 0; } //public void CombineSpritesx() { // SpriteRenderer[] renderers = FindSpriteRenderers(); // if (sTarget.combined) DestroyImmediate(sTarget.combined); // Material m = null; // if (sTarget.useCutoutShader) // m = new Material(Shader.Find("Unlit/Transparent Cutout")); // else // m = new Material(Shader.Find("Sprites/Default")); // GameObject combineGameObject = new GameObject(); // combineGameObject.name = "" + sTarget.transform.name + " Combined [SSC]"; // combineGameObject.gameObject.AddComponent<MeshFilter>(); // combineGameObject.gameObject.AddComponent<MeshRenderer>(); // combineGameObject.transform.parent = sTarget.transform; // combineGameObject.transform.SetSiblingIndex(1); // sTarget.combined = combineGameObject.gameObject; // Mesh meshSprites = new Mesh(); // CombineInstance[] combineInstace = new CombineInstance[renderers.Length]; // sTarget.oldZPositions = new float[renderers.Length]; // for (int i = 0; i < combineInstace.Length; i++) { // EditorUtility.DisplayProgressBar("Combining", "" + i + " / " + combineInstace.Length, (float)i / combineInstace.Length); // sTarget.oldZPositions[i] = renderers[i].transform.position.z; // if (!CheckExcludeFromCombine(renderers[i].gameObject)) { // combineInstace[i].mesh = ConvertSprite(renderers[i]); // combineInstace[i].transform = renderers[i].transform.localToWorldMatrix; // } else { // if (renderers[i].gameObject.tag == "EditorOnly") renderers[i].gameObject.tag = "Untagged"; // combineInstace[i].mesh = new Mesh(); // combineInstace[i].transform = sTarget.transform.localToWorldMatrix; // } // renderers[i].transform.position = new Vector3(renderers[i].transform.position.x, renderers[i].transform.position.y, sTarget.oldZPositions[i]); // } // EditorUtility.ClearProgressBar(); // ToggleRenderers(false); // m.SetTexture("_MainTex", SpriteUtility.GetSpriteTexture(renderers[0].sprite, false)); // combineGameObject.GetComponent<MeshFilter>().sharedMesh = meshSprites; // combineGameObject.GetComponent<Renderer>().material = m; // meshSprites.Clear(); // meshSprites.CombineMeshes(combineInstace); // sTarget.vCount = meshSprites.vertexCount; // if (sTarget.vCount > 65536) { // Debug.LogWarning("Vertex Count: " + sTarget.vCount + "- Vertex Count too high, please divide mesh combine into more groups. Max 65536 for each mesh"); // sTarget._canGenerateLightmapUV = false; // } else { // sTarget._canGenerateLightmapUV = true; // } //} public override void OnInspectorGUI() { GUISetup(); // // EDITOR ONLY WARNING // if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } else { GUILayout.Label("Editor can't combine in play-mode", infoStyle); GUI.enabled = false; } GUILayout.Space(15.0f); // // COMBINE RELEASE BUTTONS // if (sTarget.combined == null) { if (GUILayout.Button("Combine", buttonStyle)) { CombineSprites(); if (!sTarget.combined) return; sTarget.combined.isStatic = true; sTarget.combined.AddComponent<MeshSpriteSorting>(); } sTarget.useCutoutShader = EditorGUILayout.Toggle("Use Cutout shader", sTarget.useCutoutShader); GUILayout.Space(15.0f); GUILayout.Label("Set sprite and mesh Z position\nbased on sprite sorting order."); sTarget.sortingOrderToZPositionMultiplier = EditorGUILayout.FloatField("Z Position Multiplier", sTarget.sortingOrderToZPositionMultiplier); sTarget.sortingOrderToZPositionOffset = EditorGUILayout.FloatField("Z Position Offset", sTarget.sortingOrderToZPositionOffset); } else { if (GUILayout.Button("Release", buttonStyle)) { ReleaseSprites(); } } GUILayout.Space(5.0f); // // COMBINED FUNCTIONALITY // if (sTarget.combined != null) { if (sTarget.vCount > 65536) { GUILayout.Label("Warning: Mesh has too high vertex count", EditorStyles.boldLabel); GUI.enabled = false; } GUILayout.Space(5.0f); if (sTarget.editorOnlyTagged) { GUI.color = Color.cyan; } if (GUILayout.Button("Tag Sprites \"EditorOnly\"", buttonStyle2)) { if (EditorUtility.DisplayDialog("Tag Sprites \"EditorOnly\"", "Tag all sprite gameobjects with \"EditorOnly\"? \n\nGameobjects and and their components like colliders will be IGNORED when building the scene.\n(Does not apply to excluded objects)" , "Yes", "No I need tags")) { TagForExclusion(true); } } GUI.color = Color.white; GUILayout.Space(5.0f); if (GUILayout.Button("Tag Sprites \"Untagged\"", buttonStyle2)) { if (EditorUtility.DisplayDialog("Tag Sprites \"Untagged\"", "Tag all sprite gameobjects with \"Untagged\"? \n\nGameobjects and their components like colliders will be INCLUDED when building the scene." , "Yes", "No I need tags")) { TagForExclusion(false); } } GUILayout.Space(20.0f); if (sTarget.combined.GetComponent<MeshFilter>().sharedMesh.name != "") { GUI.enabled = false; } else if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } if (GUILayout.Button("Save Mesh", buttonStyle2)) { string path = SaveFile("Assets/", sTarget.transform.name + " [SSC Mesh]", "asset"); if (path != null && path != "") { UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path, (Type)typeof(object)); if (asset == null) { Debug.Log(path); AssetDatabase.CreateAsset(sTarget.combined.GetComponent<MeshFilter>().sharedMesh, path); } else { ((Mesh)asset).Clear(); EditorUtility.CopySerialized(sTarget.combined.GetComponent<MeshFilter>().sharedMesh, asset); AssetDatabase.SaveAssets(); } sTarget.combined.GetComponent<MeshFilter>().sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(path, (Type)typeof(object)); Debug.Log("Saved mesh asset: " + path); } } GUI.color = Color.white; GUILayout.Space(5.0f); if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } if (GUILayout.Button("Save Material", buttonStyle2)) { string path = SaveFile("Assets/", sTarget.transform.name + " [SSC Material]", "mat"); if (path != null && path != "") { UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(path, (Type)typeof(object)); if (asset == null) { AssetDatabase.CreateAsset(sTarget.combined.GetComponent<Renderer>().sharedMaterial, path); } else { EditorUtility.CopySerialized(sTarget.combined.GetComponent<Renderer>().sharedMaterial, asset); AssetDatabase.SaveAssets(); } sTarget.combined.GetComponent<Renderer>().sharedMaterial = (Material)AssetDatabase.LoadAssetAtPath(path, (Type)typeof(object)); if (sTarget.copyTarget) sTarget.copyTargetMesh.GetComponent<Renderer>().sharedMaterial = (Material)AssetDatabase.LoadAssetAtPath(path, (Type)typeof(object)); Debug.Log("Saved material asset: " + path); } } GUILayout.Space(5.0f); if (sTarget.toggleCollidersStatus) { if (GUILayout.Button("Disable Colliders", buttonStyle2)) { ToggleColliders(false); sTarget.toggleCollidersStatus = false; } } else { if (GUILayout.Button("Enable Colliders", buttonStyle2)) { ToggleColliders(true); sTarget.toggleCollidersStatus = true; } } GUILayout.Space(5.0f); if (GUILayout.Button("Copy Colliders >> Self", buttonStyle2)) { CopyColliders(true); } GUILayout.Space(20.0f); } if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } if (sTarget.combined != null) { string bText = "Create Clone"; if (sTarget.combined.GetComponent<MeshFilter>().sharedMesh.name == "") { bText = bText + " (Save mesh first)"; GUI.enabled = false; } else if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } if (GUILayout.Button(bText, buttonStyle2)) { GameObject newCopy = new GameObject(); GameObject newCopy2 = new GameObject(); newCopy2.transform.parent = newCopy.transform; newCopy2.transform.localPosition = sTarget.combined.transform.localPosition; newCopy2.transform.localRotation = sTarget.combined.transform.localRotation; newCopy.name = sTarget.name + " Clone [SSC]"; newCopy2.name = "Mesh Clone [SSC]"; newCopy.transform.position = sTarget.transform.position; newCopy.transform.rotation = sTarget.transform.rotation; MeshFilter mf = newCopy2.AddComponent<MeshFilter>(); newCopy2.AddComponent<MeshRenderer>(); mf.sharedMesh = sTarget.combined.GetComponent<MeshFilter>().sharedMesh; sTarget.copyTarget = newCopy; sTarget.copyTargetMesh = newCopy2; CopyMaterials(newCopy2.transform); CopyColliders(); Selection.activeTransform = newCopy.transform; } GUILayout.Space(5.0f); if (!sTarget.copyTarget) { GUI.enabled = false; } else if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } if (GUILayout.Button("Copy Colliders >> Clone", buttonStyle2)) { CopyColliders(); } GUILayout.Space(5.0f); if (GUILayout.Button("Copy Materials >> Clone", buttonStyle2)) { CopyMaterials(sTarget.copyTargetMesh.transform); } if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } sTarget.destroyOldColliders = EditorGUILayout.Toggle("Destroy old colliders", sTarget.destroyOldColliders); sTarget.keepStructure = EditorGUILayout.Toggle("Keep collider structure", sTarget.keepStructure); sTarget.copyTarget = (GameObject)EditorGUILayout.ObjectField("Copy to clone: ", sTarget.copyTarget, typeof(GameObject), true); } GUILayout.Space(15.0f); if (sTarget.combined) { GUI.enabled = false; } serializedObject.Update(); SerializedProperty excludeProperty; excludeProperty = serializedObject.FindProperty("excludeFromCombine"); EditorGUILayout.PropertyField(excludeProperty, new GUIContent("Exclude GameObjects From Combine"), true); serializedObject.ApplyModifiedProperties(); if (sTarget.excludeFromCombine != null && sTarget.excludeFromCombine.Length == 0) EditorGUILayout.LabelField("(Lock inspector to drag many at once.)"); GUILayout.Space(5.0f); if (!sTarget.copyTarget) { GUI.enabled = false; } else if (!UnityEngine.Application.isPlaying) { GUI.enabled = true; } GUILayout.Space(5.0f); if (sTarget.excludeFromCombine != null && sTarget.excludeFromCombine.Length > 0 && sTarget.combined) { if (GUILayout.Button("Copy Excluded >> Clone", buttonStyle2)) { CopyExcludedFromCombine(); } } GUILayout.Space(5.0f); if (sTarget.combined != null) { GUILayout.Label("Vertex count: " + sTarget.vCount + " / 65536", infoStyle); } else { GUILayout.Label("Vertex count: - / 65536", infoStyle); } if (GUI.changed) { EditorUtility.SetDirty(sTarget); } } public void DestroyComponentsExeptColliders(Transform t) { Component[] transforms = t.GetComponentsInChildren(typeof(Transform)); foreach (Transform trans in transforms) { if (trans != null && trans.parent != sTarget.transform && trans.name == "Colliders Copy [SSC]") DestroyImmediate(trans.gameObject); else if (trans!= null && !sTarget.keepStructure && trans.transform.parent != t && trans.transform != t && (trans.GetComponent(typeof(Collider2D)) != null)) { trans.transform.name = "" + GetParentStructure(t, trans.transform); trans.transform.parent = t; } } Component[] components = t.GetComponentsInChildren(typeof(Component)); foreach (Component comp in components) { if((comp is Collider2D)) { ((Collider2D)comp).enabled = true; } if (!(comp is Collider2D) && !(comp is Transform)) { DestroyImmediate(comp); } } } public string GetParentStructure(Transform root, Transform t) { Transform ct = t; string s = ""; while (ct != root) { s = s.Insert(0, ct.name + " - "); ct = ct.parent; } s = s.Remove(s.Length - 3, 3); return s; } public void DestroyEmptyGameObjects(Transform t) { Component[] components = t.GetComponentsInChildren(typeof(Transform)); foreach (Transform comp in components) { if ((comp != null) && (comp.childCount == 0 || !CheckChildrenForColliders(comp))) { Collider2D col = (Collider2D)comp.GetComponent(typeof(Collider2D)); if (col == null || CheckExcludeFromCombine(comp.gameObject, true)) { DestroyImmediate(comp.gameObject); } } } } public bool CheckChildrenForColliders(Transform t) { Component[] components = t.GetComponentsInChildren(typeof(Collider2D)); if (components.Length > 0) { return true; } return false; } public void CopyMaterials(Transform t) { Renderer r = t.GetComponent<Renderer>(); r.sharedMaterials = sTarget.combined.transform.GetComponent<Renderer>().sharedMaterials; } public void CopyColliders(bool copyToSelf = false) { GameObject clone; if (copyToSelf) clone = (GameObject)Instantiate(sTarget.gameObject, sTarget.transform.position, sTarget.transform.rotation); else clone = (GameObject)Instantiate(sTarget.gameObject, sTarget.copyTarget.transform.position, sTarget.copyTarget.transform.rotation); if (!copyToSelf && sTarget.destroyOldColliders) { if (sTarget.copyTargetColliders) { DestroyImmediate(sTarget.copyTargetColliders); } }else if (copyToSelf && sTarget.destroyOldColliders) { if (sTarget.selfColliders) { DestroyImmediate(sTarget.selfColliders); } } if (copyToSelf) { clone.transform.name = "Colliders Copy [SSC]"; clone.transform.parent = sTarget.transform; sTarget.selfColliders = clone; } else { clone.transform.name = "Colliders Clone [SSC]"; clone.transform.parent = sTarget.copyTarget.transform; sTarget.copyTargetColliders = clone; } clone.transform.SetSiblingIndex(2); DestroyComponentsExeptColliders(clone.transform); DestroyEmptyGameObjects(clone.transform); } public void ExportMesh(MeshFilter meshFilter, string folder, string filename) { string path = SaveFile(folder, filename, "obj"); if (path != null) { StreamWriter sw = new StreamWriter(path); sw.Write(MeshToString(meshFilter)); sw.Flush(); sw.Close(); AssetDatabase.Refresh(); Debug.Log("Exported OBJ file to folder: " + path); } } public string MeshToString(MeshFilter meshFilter) { Mesh sMesh = meshFilter.sharedMesh; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("g ").Append(meshFilter.name).Append("\n"); foreach (Vector3 vert in sMesh.vertices) { Vector3 tPoint = meshFilter.transform.TransformPoint(vert); stringBuilder.Append(String.Format("v {0} {1} {2}\n", -tPoint.x, tPoint.y, tPoint.z)); } stringBuilder.Append("\n"); foreach (Vector3 norm in sMesh.normals) { Vector3 tDir = meshFilter.transform.TransformDirection(norm); stringBuilder.Append(String.Format("vn {0} {1} {2}\n", -tDir.x, tDir.y, tDir.z)); } stringBuilder.Append("\n"); foreach (Vector3 uv in sMesh.uv) { stringBuilder.Append(String.Format("vt {0} {1}\n", uv.x, uv.y)); } for (int material = 0; material < sMesh.subMeshCount; material++) { stringBuilder.Append("\n"); int[] tris = sMesh.GetTriangles(material); for (int i = 0; i < tris.Length; i += 3) { stringBuilder.Append(String.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n", tris[i] + 1, tris[i + 1] + 1, tris[i + 2] + 1)); } } return stringBuilder.ToString(); } public string SaveFile(string folder, string name, string type) { string newPath = ""; string path = EditorUtility.SaveFilePanel("Select Folder ", folder, name, type); if (path.Length > 0) { if (path.Contains("" + UnityEngine.Application.dataPath)) { string s = "" + path + ""; string d = "" + UnityEngine.Application.dataPath + "/"; string p = "Assets/" + s.Remove(0, d.Length); newPath = p; bool cancel = false; if (cancel) Debug.Log("Save file canceled"); } else { Debug.LogError("Prefab Save Failed: Can't save outside project: " + path); } } return newPath; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition { using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update; using Microsoft.Azure.Management.Network.Fluent.HasCookieBasedAffinity.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasServerNameIndication.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasHostName.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasSslCertificate.UpdateDefinition; /// <summary> /// The stage of an application gateway request routing rule definition allowing to specify the frontend for the rule to apply to. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithFrontend<ParentT> { /// <summary> /// Enables the rule to apply to the application gateway's private (internal) frontend. /// If the private frontend IP configuration does not yet exist, it will be created under an auto-generated name. /// If the application gateway does not have a subnet specified for its private frontend, one will be created automatically, /// unless a specific subnet is specified in the application gateway definition's optional settings. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithFrontendPort<ParentT> FromPrivateFrontend(); /// <summary> /// Enables the rule to apply to the application gateway's public (Internet-facing) frontend. /// If the public frontend IP configuration does not yet exist, it will be created under an auto-generated name. /// If the application gateway does not have a public IP address specified for its public frontend, one will be created /// automatically, unless a specific public IP address is specified in the application gateway definition's optional settings. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithFrontendPort<ParentT> FromPublicFrontend(); } /// <summary> /// The stage of an application gateway request routing rule definition allowing to add an address to the backend used by this request routing rule. /// A new backend will be created if none is associated with this rule yet. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendAddress<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddressBeta<ParentT> { /// <summary> /// Adds an IP address to the backend associated with this rule. /// If no backend has been associated with this rule yet, a new one will be created with an auto-generated name. /// This call can be used in a sequence to add multiple IP addresses. /// </summary> /// <param name="ipAddress">An IP address.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddressOrAttach<ParentT> ToBackendIPAddress(string ipAddress); /// <summary> /// Adds an FQDN (fully qualified domain name) to the backend associated with this rule. /// If no backend has been associated with this rule yet, a new one will be created with an auto-generated name. /// This call can be used in a sequence to add multiple FQDNs. /// </summary> /// <param name="fqdn">A fully qualified domain name.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddressOrAttach<ParentT> ToBackendFqdn(string fqdn); } /// <summary> /// The final stage of an application gateway request routing rule definition. /// At this stage, any remaining optional settings can be specified, or the definition /// can be attached to the parent application gateway definition. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithAttach<ParentT> : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithHostName<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithCookieBasedAffinity<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithRedirectConfig<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to specify the backend HTTP settings configuration /// to associate the routing rule with. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendHttpConfiguration<ParentT> { /// <summary> /// Associates the specified backend HTTP settings configuration with this request routing rule. /// If the backend configuration does not exist yet, it must be defined in the optional part of the application gateway /// definition. The request routing rule references it only by name. /// </summary> /// <param name="name">The name of a backend HTTP settings configuration.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendOrAddress<ParentT> ToBackendHttpConfiguration(string name); /// <summary> /// Creates a backend HTTP settings configuration for the specified backend port and the HTTP protocol, and associates it with this /// request routing rule. /// An auto-generated name will be used for this newly created configuration. /// </summary> /// <param name="portNumber">The port number for a new backend HTTP settings configuration.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendOrAddress<ParentT> ToBackendHttpPort(int portNumber); } /// <summary> /// The stage of an application gateway request routing rule definition allowing to specify an existing listener to /// associate the routing rule with. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithListener<ParentT> { /// <summary> /// Associates the request routing rule with a frontend listener. /// If the listener with the specified name does not yet exist, it must be defined separately in the optional part /// of the application gateway definition. This only adds a reference to the listener by its name. /// Also, note that a given listener can be used by no more than one request routing rule at a time. /// </summary> /// <param name="name">The name of a listener to reference.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrRedirect<ParentT> FromListener(string name); } /// <summary> /// The stage of an application gateway request routing rule allowing to enable cookie based affinity. /// </summary> /// <typeparam name="ParentT">The next stage of the definition.</typeparam> public interface IWithCookieBasedAffinity<ParentT> : Microsoft.Azure.Management.Network.Fluent.HasCookieBasedAffinity.UpdateDefinition.IWithCookieBasedAffinity<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT>> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to require server name indication if the /// application gateway is serving multiple websites in its backends and SSL is required. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendHttpConfigurationOrSni<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfiguration<ParentT>, Microsoft.Azure.Management.Network.Fluent.HasServerNameIndication.UpdateDefinition.IWithServerNameIndication<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfiguration<ParentT>> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to specify the host name of a backend website /// for the listener to receive traffic for. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithHostName<ParentT> : Microsoft.Azure.Management.Network.Fluent.HasHostName.UpdateDefinition.IWithHostName<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT>> { } /// <summary> /// The entirety of an application gateway request routing rule definition as part of an application gateway update. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IUpdateDefinition<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IBlank<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithFrontend<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithListener<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithFrontendPort<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithListenerOrFrontend<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackend<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddress<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendOrAddress<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddressOrAttach<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfiguration<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrRedirect<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigurationOrSni<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrSniOrRedirect<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithSslCertificate<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithSslPassword<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrSniOrRedirect<ParentT>> { } /// <summary> /// The stage of an application gateway request routing rule allowing to specify backend HTTP settings, or SNI, or a redirect configuration. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway update to return to after attaching this definition.</typeparam> public interface IWithBackendHttpConfigOrSniOrRedirect<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigurationOrSni<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithRedirectConfig<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to require server name indication. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithServerNameIndication<ParentT> : Microsoft.Azure.Management.Network.Fluent.HasServerNameIndication.UpdateDefinition.IWithServerNameIndication<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT>> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to specify the backend to associate the routing rule with. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackend<ParentT> { /// <summary> /// Associates the request routing rule with a backend on this application gateway. /// If the backend does not yet exist, it will be automatically created. /// </summary> /// <param name="name">The name of an existing backend.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT> ToBackend(string name); } /// <summary> /// The stage of an application gateway request routing rule definition allowing to select either a backend or a redirect configuration. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway update to return to after attaching this definition.</typeparam> public interface IWithBackendHttpConfigOrRedirect<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfiguration<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithRedirectConfig<ParentT> { } /// <summary> /// The first stage of an application gateway request routing rule definition. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IBlank<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithListenerOrFrontend<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to associate an existing listener /// with the rule, or create a new one implicitly by specifying the frontend to listen to. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithListenerOrFrontend<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithListener<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithFrontend<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to add an address to specify an existing /// backend to associate with this request routing rule or create a new backend with an auto-generated name and addresses to it. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendOrAddress<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackend<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddress<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule allowing to specify an SSL certificate. /// </summary> /// <typeparam name="ParentT">The next stage of the definition.</typeparam> public interface IWithSslCertificate<ParentT> : Microsoft.Azure.Management.Network.Fluent.HasSslCertificate.UpdateDefinition.IWithSslCertificate<Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrSniOrRedirect<ParentT>> { } /// <summary> /// The stage of an application gateway request routing rule allowing to specify an SSL certificate. /// </summary> /// <typeparam name="ParentT">The next stage of the definition.</typeparam> public interface IWithSslPassword<ParentT> : Microsoft.Azure.Management.Network.Fluent.HasSslCertificate.UpdateDefinition.IWithSslPassword<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to associate the rule with a redirect configuration. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway update to return to after attaching this definition.</typeparam> public interface IWithRedirectConfig<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithRedirectConfigBeta<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to create an associate listener and frontend /// for a specific port number and protocol. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithFrontendPort<ParentT> { /// <summary> /// Associates a new listener for the specified port number and the HTTPS protocol with this rule. /// </summary> /// <param name="portNumber">The port number to listen to.</param> /// <return>The next stage of the definition, or null if the specified port number is already used for a different protocol.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithSslCertificate<ParentT> FromFrontendHttpsPort(int portNumber); /// <summary> /// Associates a new listener for the specified port number and the HTTP protocol with this rule. /// </summary> /// <param name="portNumber">The port number to listen to.</param> /// <return>The next stage of the definition, or null if the specified port number is already used for a different protocol.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendHttpConfigOrRedirect<ParentT> FromFrontendHttpPort(int portNumber); } /// <summary> /// The stage of an application gateway request routing rule definition allowing to add more backend addresses, /// start specifying optional settings, or finish the definition by attaching it to the parent application gateway. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendAddressOrAttach<ParentT> : Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddress<ParentT>, Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT> { } /// <summary> /// The stage of an application gateway request routing rule definition allowing to add an address to the backend used by this request routing rule. /// A new backend will be created if none is associated with this rule yet. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway definition to return to after attaching this definition.</typeparam> public interface IWithBackendAddressBeta<ParentT> : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Adds the specified IP addresses to the backend associated with this rule. /// </summary> /// <param name="ipAddresses">IP addresses to add.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithBackendAddressOrAttach<ParentT> ToBackendIPAddresses(params string[] ipAddresses); } /// <summary> /// The stage of an application gateway request routing rule definition allowing to associate the rule with a redirect configuration. /// </summary> /// <typeparam name="ParentT">The stage of the application gateway update to return to after attaching this definition.</typeparam> public interface IWithRedirectConfigBeta<ParentT> : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Associates the specified redirect configuration with this request routing rule. /// </summary> /// <param name="name">The name of a redirect configuration on this application gateway.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.ApplicationGatewayRequestRoutingRule.UpdateDefinition.IWithAttach<ParentT> WithRedirectConfiguration(string name); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace nHydrate.Generator.Common.Util { public static class Extensions { public static List<EnvDTE.Project> GetProjects(this EnvDTE80.Solution2 solution) { var projects = new List<EnvDTE.Project>(); for (var ii = 1; ii <= solution.Count; ii++) { var project = solution.Item(ii); switch (project.Kind) { //List: https://www.codeproject.com/reference/720512/list-of-visual-studio-project-type-guids case "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}": //C# case "{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}": //ASP.NET 5 case "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}": //.NET Core projects.Add(project); break; default: break; } } var folders = solution.GetFolders(); foreach (var f in folders) { for (var ii = 1; ii <= f.ProjectItems.Count; ii++) { var project = f.ProjectItems.Item(ii); var p = project.Object as EnvDTE.Project; if (p != null) projects.Add(p); } //((EnvDTE.ProjectItem)(CurrentSolution.GetFolders()[0].ProjectItems.Item(1))).Name } return projects; } public static List<EnvDTE.Project> GetFolders(this EnvDTE80.Solution2 solution) { var folders = new List<EnvDTE.Project>(); for (var ii = 1; ii <= solution.Count; ii++) { var project = solution.Item(ii); switch(project.Kind) { case "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}": case "{66A26722-8FB5-11D2-AA7E-00C04F688DDE}": folders.Add(project); break; default: break; } } return folders; } public static List<EnvDTE.Project> GetFolders(this EnvDTE.Project project) { var folders = new List<EnvDTE.Project>(); for (var ii = 1; ii <= project.ProjectItems.Count; ii++) { var child = project.ProjectItems.Item(ii); switch(child.Kind) { case "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}": case "{66A26722-8FB5-11D2-AA7E-00C04F688DDE}": folders.Add(child as EnvDTE.Project); break; default: break; } } return folders; } /// <summary> /// Determines if the data type is a database type of Int,BigInt,TinyInt,SmallInt /// </summary> public static bool IsIntegerType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.BigInt: case System.Data.SqlDbType.Int: case System.Data.SqlDbType.TinyInt: case System.Data.SqlDbType.SmallInt: return true; } return false; } /// <summary> /// Determines if the data type is a database character type of Binary,Image,VarBinary /// </summary> public static bool IsBinaryType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.Binary: case System.Data.SqlDbType.Image: case System.Data.SqlDbType.VarBinary: return true; default: return false; } } /// <summary> /// Determines if the data type is a database character type of Char,NChar,NText,NVarChar,Text,VarChar,Xml /// </summary> public static bool IsTextType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.Char: case System.Data.SqlDbType.NChar: case System.Data.SqlDbType.NText: case System.Data.SqlDbType.NVarChar: case System.Data.SqlDbType.Text: case System.Data.SqlDbType.VarChar: case System.Data.SqlDbType.Xml: return true; default: return false; } } /// <summary> /// Determines if the data type is a database character type of DateTime,DateTime2,DateTimeOffset,SmallDateTime /// </summary> public static bool IsDateType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.Date: case System.Data.SqlDbType.DateTime: case System.Data.SqlDbType.DateTime2: case System.Data.SqlDbType.DateTimeOffset: case System.Data.SqlDbType.SmallDateTime: return true; } return false; } /// <summary> /// Determines if the type is a number wither floating point or integer /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsNumericType(this System.Data.SqlDbType type) { return IsDecimalType(type) || IsIntegerType(type) || IsMoneyType(type); } /// <summary> /// Determines if the data type is a database type of Money,SmallMoney /// </summary> public static bool IsMoneyType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.Money: case System.Data.SqlDbType.SmallMoney: return true; } return false; } /// <summary> /// Determines if the data type is a database type of Decimal,Float,Real /// </summary> public static bool IsDecimalType(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.Decimal: case System.Data.SqlDbType.Float: case System.Data.SqlDbType.Real: return true; } return false; } /// <summary> /// Determines if this type supports the MAX syntax in SQL 2008 /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool SupportsMax(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.VarChar: case System.Data.SqlDbType.NVarChar: case System.Data.SqlDbType.VarBinary: return true; default: return false; } } public static bool DefaultIsString(this System.Data.SqlDbType type) { switch (type) { case System.Data.SqlDbType.BigInt: return false; case System.Data.SqlDbType.Binary: return true; case System.Data.SqlDbType.Bit: return false; case System.Data.SqlDbType.Char: return true; case System.Data.SqlDbType.DateTime: return false; case System.Data.SqlDbType.Decimal: return false; case System.Data.SqlDbType.Float: return false; case System.Data.SqlDbType.Image: return true; case System.Data.SqlDbType.Int: return false; case System.Data.SqlDbType.Money: return false; case System.Data.SqlDbType.NChar: return true; case System.Data.SqlDbType.NText: return true; case System.Data.SqlDbType.NVarChar: return true; case System.Data.SqlDbType.Real: return false; case System.Data.SqlDbType.SmallDateTime: return false; case System.Data.SqlDbType.SmallInt: return false; case System.Data.SqlDbType.SmallMoney: return false; case System.Data.SqlDbType.Text: return true; case System.Data.SqlDbType.Timestamp: return false; case System.Data.SqlDbType.TinyInt: return false; case System.Data.SqlDbType.Udt: return false; case System.Data.SqlDbType.UniqueIdentifier: return true; case System.Data.SqlDbType.VarBinary: return true; case System.Data.SqlDbType.VarChar: return true; case System.Data.SqlDbType.Variant: return true; case System.Data.SqlDbType.Xml: return true; default: return false; } } /// <summary> /// Gets the SQL equivalent for this default value /// </summary> /// <returns></returns> public static string GetSQLDefault(this System.Data.SqlDbType dataType, string defaultValue) { var retval = string.Empty; if ((dataType == System.Data.SqlDbType.DateTime) || (dataType == System.Data.SqlDbType.SmallDateTime)) { if (defaultValue == "getdate") { //retval = defaultValue; } else if (defaultValue == "sysdatetime") { //retval = defaultValue; } else if (defaultValue == "getutcdate") { //retval = defaultValue; } else if (defaultValue.StartsWith("getdate+")) { //Do Nothing - Cannot calculate } //else if (daatType == System.Data.SqlDbType.SmallDateTime) //{ // defaultValue = String.Format("new DateTime(1900, 1, 1)", this.PascalName); //} //else //{ // defaultValue = String.Format("new DateTime(1753, 1, 1)", this.PascalName); //} } else if (dataType == System.Data.SqlDbType.Char) { retval = "' '"; if (defaultValue.Length == 1) retval = "'" + defaultValue[0].ToString().Replace("'", "''") + "'"; } else if (dataType.IsBinaryType()) { //Do Nothing - Cannot calculate } //else if (dataType == System.Data.SqlDbType.DateTimeOffset) //{ // defaultValue = "DateTimeOffset.MinValue"; //} //else if (this.IsDateType) //{ // defaultValue = "System.DateTime.MinValue"; //} //else if (dataType == System.Data.SqlDbType.Time) //{ // defaultValue = "0"; //} else if (dataType == System.Data.SqlDbType.UniqueIdentifier) { //Do Nothing //if ((StringHelper.Match(defaultValue, "newid", true)) || (StringHelper.Match(defaultValue, "newid()", true))) // retval = "newid"; //else if (string.IsNullOrEmpty(defaultValue)) // retval = string.Empty; //else //{ // Guid g; // if (Guid.TryParse(defaultValue, out g)) // retval = "'" + g.ToString() + "'"; //} } else if (dataType.IsIntegerType()) { int i; if (int.TryParse(defaultValue, out i)) retval = defaultValue; } else if (dataType.IsNumericType()) { double d; if (double.TryParse(defaultValue, out d)) { retval = defaultValue; } } else if (dataType == System.Data.SqlDbType.Bit) { if (defaultValue == "0" || defaultValue == "1") retval = defaultValue; } else { if (dataType.IsTextType() && !string.IsNullOrEmpty(defaultValue)) retval = "'" + defaultValue.Replace("'", "''") + "'"; } return retval; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel; using System.IO; using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Win32; namespace Microsoft.AspNetCore.DataProtection { /// <summary> /// Extensions for configuring data protection using an <see cref="IDataProtectionBuilder"/>. /// </summary> public static class DataProtectionBuilderExtensions { /// <summary> /// Sets the unique name of this application within the data protection system. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="applicationName">The application name.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// This API corresponds to setting the <see cref="DataProtectionOptions.ApplicationDiscriminator"/> property /// to the value of <paramref name="applicationName"/>. /// </remarks> public static IDataProtectionBuilder SetApplicationName(this IDataProtectionBuilder builder, string applicationName) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.Configure<DataProtectionOptions>(options => { options.ApplicationDiscriminator = applicationName; }); return builder; } /// <summary> /// Registers a <see cref="IKeyEscrowSink"/> to perform escrow before keys are persisted to storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="sink">The instance of the <see cref="IKeyEscrowSink"/> to register.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// Registrations are additive. /// </remarks> public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilder builder, IKeyEscrowSink sink) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (sink == null) { throw new ArgumentNullException(nameof(sink)); } builder.Services.Configure<KeyManagementOptions>(options => { options.KeyEscrowSinks.Add(sink); }); return builder; } /// <summary> /// Registers a <see cref="IKeyEscrowSink"/> to perform escrow before keys are persisted to storage. /// </summary> /// <typeparam name="TImplementation">The concrete type of the <see cref="IKeyEscrowSink"/> to register.</typeparam> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// Registrations are additive. The factory is registered as <see cref="ServiceLifetime.Singleton"/>. /// </remarks> public static IDataProtectionBuilder AddKeyEscrowSink<TImplementation>(this IDataProtectionBuilder builder) where TImplementation : class, IKeyEscrowSink { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var implementationInstance = services.GetRequiredService<TImplementation>(); return new ConfigureOptions<KeyManagementOptions>(options => { options.KeyEscrowSinks.Add(implementationInstance); }); }); return builder; } /// <summary> /// Registers a <see cref="IKeyEscrowSink"/> to perform escrow before keys are persisted to storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="factory">A factory that creates the <see cref="IKeyEscrowSink"/> instance.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// Registrations are additive. The factory is registered as <see cref="ServiceLifetime.Singleton"/>. /// </remarks> public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilder builder, Func<IServiceProvider, IKeyEscrowSink> factory) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (factory == null) { throw new ArgumentNullException(nameof(factory)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var instance = factory(services); return new ConfigureOptions<KeyManagementOptions>(options => { options.KeyEscrowSinks.Add(instance); }); }); return builder; } /// <summary> /// Configures the key management options for the data protection system. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="setupAction">An <see cref="Action{KeyManagementOptions}"/> to configure the provided <see cref="KeyManagementOptions"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder AddKeyManagementOptions(this IDataProtectionBuilder builder, Action<KeyManagementOptions> setupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } builder.Services.Configure(setupAction); return builder; } /// <summary> /// Configures the data protection system not to generate new keys automatically. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// Calling this API corresponds to setting <see cref="KeyManagementOptions.AutoGenerateKeys"/> /// to 'false'. See that property's documentation for more information. /// </remarks> public static IDataProtectionBuilder DisableAutomaticKeyGeneration(this IDataProtectionBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.Configure<KeyManagementOptions>(options => { options.AutoGenerateKeys = false; }); return builder; } /// <summary> /// Configures the data protection system to persist keys to the specified directory. /// This path may be on the local machine or may point to a UNC share. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="directory">The directory in which to store keys.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder PersistKeysToFileSystem(this IDataProtectionBuilder builder, DirectoryInfo directory) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (directory == null) { throw new ArgumentNullException(nameof(directory)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; return new ConfigureOptions<KeyManagementOptions>(options => { options.XmlRepository = new FileSystemXmlRepository(directory, loggerFactory); }); }); return builder; } /// <summary> /// Configures the data protection system to persist keys to the Windows registry. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="registryKey">The location in the registry where keys should be stored.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> [SupportedOSPlatform("windows")] public static IDataProtectionBuilder PersistKeysToRegistry(this IDataProtectionBuilder builder, RegistryKey registryKey) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (registryKey == null) { throw new ArgumentNullException(nameof(registryKey)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; return new ConfigureOptions<KeyManagementOptions>(options => { options.XmlRepository = new RegistryXmlRepository(registryKey, loggerFactory); }); }); return builder; } /// <summary> /// Configures keys to be encrypted to a given certificate before being persisted to storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="certificate">The certificate to use when encrypting keys.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtectionBuilder builder, X509Certificate2 certificate) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; return new ConfigureOptions<KeyManagementOptions>(options => { options.XmlEncryptor = new CertificateXmlEncryptor(certificate, loggerFactory); }); }); builder.Services.Configure<XmlKeyDecryptionOptions>(o => o.AddKeyDecryptionCertificate(certificate)); return builder; } /// <summary> /// Configures keys to be encrypted to a given certificate before being persisted to storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="thumbprint">The thumbprint of the certificate to use when encrypting keys.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtectionBuilder builder, string thumbprint) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (thumbprint == null) { throw new ArgumentNullException(nameof(thumbprint)); } // Make sure the thumbprint corresponds to a valid certificate. if (new CertificateResolver().ResolveCertificate(thumbprint) == null) { throw Error.CertificateXmlEncryptor_CertificateNotFound(thumbprint); } // ICertificateResolver is necessary for this type to work correctly, so register it // if it doesn't already exist. builder.Services.TryAddSingleton<ICertificateResolver, CertificateResolver>(); builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; var certificateResolver = services.GetRequiredService<ICertificateResolver>(); return new ConfigureOptions<KeyManagementOptions>(options => { options.XmlEncryptor = new CertificateXmlEncryptor(thumbprint, certificateResolver, loggerFactory); }); }); return builder; } /// <summary> /// Configures certificates which can be used to decrypt keys loaded from storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="certificates">Certificates that can be used to decrypt key data.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder UnprotectKeysWithAnyCertificate(this IDataProtectionBuilder builder, params X509Certificate2[] certificates) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.Configure<XmlKeyDecryptionOptions>(o => { if (certificates != null) { foreach (var certificate in certificates) { o.AddKeyDecryptionCertificate(certificate); } } }); return builder; } /// <summary> /// Configures keys to be encrypted with Windows DPAPI before being persisted to /// storage. The encrypted key will only be decryptable by the current Windows user account. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// This API is only supported on Windows platforms. /// </remarks> [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return builder.ProtectKeysWithDpapi(protectToLocalMachine: false); } /// <summary> /// Configures keys to be encrypted with Windows DPAPI before being persisted to /// storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="protectToLocalMachine">'true' if the key should be decryptable by any /// use on the local machine, 'false' if the key should only be decryptable by the current /// Windows user account.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// This API is only supported on Windows platforms. /// </remarks> [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder, bool protectToLocalMachine) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; return new ConfigureOptions<KeyManagementOptions>(options => { CryptoUtil.AssertPlatformIsWindows(); options.XmlEncryptor = new DpapiXmlEncryptor(protectToLocalMachine, loggerFactory); }); }); return builder; } /// <summary> /// Configures keys to be encrypted with Windows CNG DPAPI before being persisted /// to storage. The keys will be decryptable by the current Windows user account. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// See https://msdn.microsoft.com/en-us/library/windows/desktop/hh706794(v=vs.85).aspx /// for more information on DPAPI-NG. This API is only supported on Windows 8 / Windows Server 2012 and higher. /// </remarks> [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return builder.ProtectKeysWithDpapiNG( protectionDescriptorRule: DpapiNGXmlEncryptor.GetDefaultProtectionDescriptorString(), flags: DpapiNGProtectionDescriptorFlags.None); } /// <summary> /// Configures keys to be encrypted with Windows CNG DPAPI before being persisted to storage. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="protectionDescriptorRule">The descriptor rule string with which to protect the key material.</param> /// <param name="flags">Flags that should be passed to the call to 'NCryptCreateProtectionDescriptor'. /// The default value of this parameter is <see cref="DpapiNGProtectionDescriptorFlags.None"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// See https://msdn.microsoft.com/en-us/library/windows/desktop/hh769091(v=vs.85).aspx /// and https://msdn.microsoft.com/en-us/library/windows/desktop/hh706800(v=vs.85).aspx /// for more information on valid values for the the <paramref name="protectionDescriptorRule"/> /// and <paramref name="flags"/> arguments. /// This API is only supported on Windows 8 / Windows Server 2012 and higher. /// </remarks> [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder, string protectionDescriptorRule, DpapiNGProtectionDescriptorFlags flags) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (protectionDescriptorRule == null) { throw new ArgumentNullException(nameof(protectionDescriptorRule)); } builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services => { var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; return new ConfigureOptions<KeyManagementOptions>(options => { CryptoUtil.AssertPlatformIsWindows8OrLater(); options.XmlEncryptor = new DpapiNGXmlEncryptor(protectionDescriptorRule, flags, loggerFactory); }); }); return builder; } /// <summary> /// Sets the default lifetime of keys created by the data protection system. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="lifetime">The lifetime (time before expiration) for newly-created keys. /// See <see cref="KeyManagementOptions.NewKeyLifetime"/> for more information and /// usage notes.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder SetDefaultKeyLifetime(this IDataProtectionBuilder builder, TimeSpan lifetime) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (lifetime < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(Resources.FormatLifetimeMustNotBeNegative(nameof(lifetime))); } builder.Services.Configure<KeyManagementOptions>(options => { options.NewKeyLifetime = lifetime; }); return builder; } /// <summary> /// Configures the data protection system to use the specified cryptographic algorithms /// by default when generating protected payloads. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="configuration">Information about what cryptographic algorithms should be used.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> public static IDataProtectionBuilder UseCryptographicAlgorithms(this IDataProtectionBuilder builder, AuthenticatedEncryptorConfiguration configuration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return UseCryptographicAlgorithmsCore(builder, configuration); } /// <summary> /// Configures the data protection system to use custom Windows CNG algorithms. /// This API is intended for advanced scenarios where the developer cannot use the /// algorithms specified in the <see cref="EncryptionAlgorithm"/> and /// <see cref="ValidationAlgorithm"/> enumerations. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="configuration">Information about what cryptographic algorithms should be used.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// This API is only available on Windows. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] [SupportedOSPlatform("windows")] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, CngCbcAuthenticatedEncryptorConfiguration configuration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return UseCryptographicAlgorithmsCore(builder, configuration); } /// <summary> /// Configures the data protection system to use custom Windows CNG algorithms. /// This API is intended for advanced scenarios where the developer cannot use the /// algorithms specified in the <see cref="EncryptionAlgorithm"/> and /// <see cref="ValidationAlgorithm"/> enumerations. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="configuration">Information about what cryptographic algorithms should be used.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// This API is only available on Windows. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] [SupportedOSPlatform("windows")] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, CngGcmAuthenticatedEncryptorConfiguration configuration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return UseCryptographicAlgorithmsCore(builder, configuration); } /// <summary> /// Configures the data protection system to use custom algorithms. /// This API is intended for advanced scenarios where the developer cannot use the /// algorithms specified in the <see cref="EncryptionAlgorithm"/> and /// <see cref="ValidationAlgorithm"/> enumerations. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <param name="configuration">Information about what cryptographic algorithms should be used.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, ManagedAuthenticatedEncryptorConfiguration configuration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return UseCryptographicAlgorithmsCore(builder, configuration); } private static IDataProtectionBuilder UseCryptographicAlgorithmsCore(IDataProtectionBuilder builder, AlgorithmConfiguration configuration) { ((IInternalAlgorithmConfiguration)configuration).Validate(); // perform self-test builder.Services.Configure<KeyManagementOptions>(options => { options.AuthenticatedEncryptorConfiguration = configuration; }); return builder; } /// <summary> /// Configures the data protection system to use the <see cref="EphemeralDataProtectionProvider"/> /// for data protection services. /// </summary> /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param> /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns> /// <remarks> /// If this option is used, payloads protected by the data protection system will /// be permanently undecipherable after the application exits. /// </remarks> public static IDataProtectionBuilder UseEphemeralDataProtectionProvider(this IDataProtectionBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.Replace(ServiceDescriptor.Singleton<IDataProtectionProvider, EphemeralDataProtectionProvider>()); return builder; } } }
// <copyright file="SvdTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Factorization { using Numerics; /// <summary> /// Svd factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class SvdTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = DenseMatrix.CreateIdentity(order); var factorSvd = matrixI.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; Assert.AreEqual(matrixI.RowCount, u.RowCount); Assert.AreEqual(matrixI.RowCount, u.ColumnCount); Assert.AreEqual(matrixI.ColumnCount, vt.RowCount); Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount); Assert.AreEqual(matrixI.RowCount, w.RowCount); Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount); for (var i = 0; i < w.RowCount; i++) { for (var j = 0; j < w.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, w[i, j]); } } } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; // Make sure the U has the right dimensions. Assert.AreEqual(row, u.RowCount); Assert.AreEqual(row, u.ColumnCount); // Make sure the VT has the right dimensions. Assert.AreEqual(column, vt.RowCount); Assert.AreEqual(column, vt.ColumnCount); // Make sure the W has the right dimensions. Assert.AreEqual(row, w.RowCount); Assert.AreEqual(column, w.ColumnCount); // Make sure the U*W*VT is the original matrix. var matrix = u*w*vt; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j].Real, matrix[i, j].Real, 1e-3f); Assert.AreEqual(matrixA[i, j].Imaginary, matrix[i, j].Imaginary, 1e-3f); } } } /// <summary> /// Can check rank of a non-square matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(10, 8)] [TestCase(48, 52)] [TestCase(100, 93)] public void CanCheckRankOfNonSquare(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var mn = Math.Min(row, column); Assert.AreEqual(factorSvd.Rank, mn); } /// <summary> /// Can check rank of a square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(9)] [TestCase(50)] [TestCase(90)] public void CanCheckRankSquare(int order) { var matrixA = Matrix<Complex32>.Build.Random(order, order, 1); var factorSvd = matrixA.Svd(); if (factorSvd.Determinant != 0) { Assert.AreEqual(factorSvd.Rank, order); } else { Assert.AreEqual(factorSvd.Rank, order - 1); } } /// <summary> /// Can check rank of a square singular matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanCheckRankOfSquareSingular(int order) { var matrixA = new DenseMatrix(order, order); matrixA[0, 0] = 1; matrixA[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { matrixA[i, i - 1] = 1; matrixA[i, i + 1] = 1; matrixA[i - 1, i] = 1; matrixA[i + 1, i] = 1; } var factorSvd = matrixA.Svd(); Assert.AreEqual(factorSvd.Determinant, Complex32.Zero); Assert.AreEqual(factorSvd.Rank, order - 1); } /// <summary> /// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<Complex32>.Build.Random(10, 3, 1); var factorSvd = matrixA.Svd(false); var matrixB = Matrix<Complex32>.Build.Random(10, 3, 1); Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException); } /// <summary> /// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<Complex32>.Build.Random(10, 3, 1); var factorSvd = matrixA.Svd(false); var vectorb = Vector<Complex32>.Build.Random(3, 1); Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException); } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVector(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<Complex32>.Build.Random(row, 1); var resultx = factorSvd.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f); Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrix(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<Complex32>.Build.Random(row, column, 1); var matrixX = factorSvd.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f); Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<Complex32>.Build.Random(row, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(column); factorSvd.Solve(vectorb, resultx); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f); Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column) { var matrixA = Matrix<Complex32>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<Complex32>.Build.Random(row, column, 1); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(column, column); factorSvd.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f); Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// Copyright 2016 Mark Raasveldt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; using System.Text.RegularExpressions; namespace Tibialyzer { class QuestForm : NotificationForm { private Label levelLabel; private Label label2; private PictureBox premiumBox; private Label summonableLabel; private Label cityLabel; private Label label3; private Label legendLabel; private Label questTitle; private Label wikiButton; public Quest quest; public QuestForm(Quest q) { this.quest = q; this.InitializeComponent(); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QuestForm)); this.legendLabel = new System.Windows.Forms.Label(); this.cityLabel = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.levelLabel = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.premiumBox = new System.Windows.Forms.PictureBox(); this.summonableLabel = new System.Windows.Forms.Label(); this.questTitle = new System.Windows.Forms.Label(); this.wikiButton = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.premiumBox)).BeginInit(); this.SuspendLayout(); // // legendLabel // this.legendLabel.AutoSize = true; this.legendLabel.BackColor = System.Drawing.Color.Transparent; this.legendLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.legendLabel.ForeColor = StyleManager.NotificationTextColor; this.legendLabel.Location = new System.Drawing.Point(12, 101); this.legendLabel.MaximumSize = new System.Drawing.Size(300, 60); this.legendLabel.Name = "legendLabel"; this.legendLabel.Padding = new System.Windows.Forms.Padding(3); this.legendLabel.Size = new System.Drawing.Size(160, 19); this.legendLabel.TabIndex = 29; this.legendLabel.Text = "This quest has no legend."; // // cityLabel // this.cityLabel.BackColor = System.Drawing.Color.Transparent; this.cityLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cityLabel.ForeColor = StyleManager.NotificationTextColor; this.cityLabel.Location = new System.Drawing.Point(161, 59); this.cityLabel.Name = "cityLabel"; this.cityLabel.Size = new System.Drawing.Size(100, 16); this.cityLabel.TabIndex = 28; this.cityLabel.Text = "Edron"; this.cityLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.ForeColor = StyleManager.NotificationTextColor; this.label3.Location = new System.Drawing.Point(259, 61); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(24, 13); this.label3.TabIndex = 27; this.label3.Text = "City"; // // levelLabel // this.levelLabel.BackColor = System.Drawing.Color.Transparent; this.levelLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.levelLabel.ForeColor = StyleManager.NotificationTextColor; this.levelLabel.Location = new System.Drawing.Point(211, 43); this.levelLabel.Name = "levelLabel"; this.levelLabel.Size = new System.Drawing.Size(50, 16); this.levelLabel.TabIndex = 26; this.levelLabel.Text = "0"; this.levelLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.ForeColor = StyleManager.NotificationTextColor; this.label2.Location = new System.Drawing.Point(259, 45); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(53, 13); this.label2.TabIndex = 25; this.label2.Text = "Min Level"; // // premiumBox // this.premiumBox.BackColor = System.Drawing.Color.Transparent; this.premiumBox.Location = new System.Drawing.Point(241, 26); this.premiumBox.Name = "premiumBox"; this.premiumBox.Size = new System.Drawing.Size(16, 16); this.premiumBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.premiumBox.TabIndex = 23; this.premiumBox.TabStop = false; // // summonableLabel // this.summonableLabel.AutoSize = true; this.summonableLabel.BackColor = System.Drawing.Color.Transparent; this.summonableLabel.ForeColor = StyleManager.NotificationTextColor; this.summonableLabel.Location = new System.Drawing.Point(259, 28); this.summonableLabel.Name = "summonableLabel"; this.summonableLabel.Size = new System.Drawing.Size(47, 13); this.summonableLabel.TabIndex = 24; this.summonableLabel.Text = "Premium"; // // questTitle // this.questTitle.BackColor = System.Drawing.Color.Transparent; this.questTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.questTitle.ForeColor = StyleManager.NotificationTextColor; this.questTitle.Location = new System.Drawing.Point(11, 30); this.questTitle.Name = "questTitle"; this.questTitle.Size = new System.Drawing.Size(200, 16); this.questTitle.TabIndex = 4; this.questTitle.Text = "Quest Name"; // // wikiButton // this.wikiButton.BackColor = System.Drawing.Color.Transparent; this.wikiButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.wikiButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.wikiButton.ForeColor = StyleManager.NotificationTextColor; this.wikiButton.Location = new System.Drawing.Point(11, 53); this.wikiButton.Name = "wikiButton"; this.wikiButton.Padding = new System.Windows.Forms.Padding(2); this.wikiButton.Size = new System.Drawing.Size(96, 21); this.wikiButton.TabIndex = 31; this.wikiButton.Text = "Wiki"; this.wikiButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.wikiButton.Click += new System.EventHandler(this.wikiButton_Click); // // QuestForm // this.ClientSize = new System.Drawing.Size(318, 153); this.Controls.Add(this.wikiButton); this.Controls.Add(this.legendLabel); this.Controls.Add(this.cityLabel); this.Controls.Add(this.label3); this.Controls.Add(this.levelLabel); this.Controls.Add(this.label2); this.Controls.Add(this.premiumBox); this.Controls.Add(this.summonableLabel); this.Controls.Add(this.questTitle); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "QuestForm"; ((System.ComponentModel.ISupportInitialize)(this.premiumBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } public override void LoadForm() { if (quest == null) return; this.SuspendLayout(); NotificationInitialize(); UnregisterControl(wikiButton); this.questTitle.Text = quest.name; this.premiumBox.Image = quest.premium ? StyleManager.GetImage("checkmark-yes.png") : StyleManager.GetImage("checkmark-no.png"); this.cityLabel.Text = quest.city == null ? "Unknown" : quest.city.ToTitle(); this.levelLabel.Text = quest.minlevel.ToString(); this.legendLabel.Text = quest.legend; List<TibiaObject> rewards = new List<TibiaObject>(); foreach(int reward in quest.rewardItems) { Item item = StorageManager.getItem(reward); rewards.Add(item); } rewards = rewards.OrderByDescending(o => (o as Item).GetMaxValue()).ToList<TibiaObject>(); int x = 5; int y = 77; foreach (string missionName in quest.questInstructions.Keys) { if (quest.questInstructions[missionName].Count == 0) continue; if (x + 150 >= this.Size.Width) { x = 5; y += 25; } Label missionButton = new Label(); missionButton.BackColor = System.Drawing.Color.Transparent; missionButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; missionButton.Font = wikiButton.Font; missionButton.ForeColor = StyleManager.NotificationTextColor; missionButton.Location = new System.Drawing.Point(x, y); missionButton.Name = quest.questInstructions[missionName][0].specialCommand != null ? quest.questInstructions[missionName][0].specialCommand : "guide" + Constants.CommandSymbol + quest.name.ToLower() + Constants.CommandSymbol + "1" + Constants.CommandSymbol + missionName; missionButton.Padding = new System.Windows.Forms.Padding(2); missionButton.Text = missionName; missionButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; missionButton.Click += MissionButton_Click; missionButton.Size = new Size(150, 21); this.Controls.Add(missionButton); x += missionButton.Width + 5; } y += 25; using (Graphics gr = Graphics.FromHwnd(legendLabel.Handle)) { this.legendLabel.Location = new Point(legendLabel.Location.X, y); y += (int)gr.MeasureString(this.legendLabel.Text, this.legendLabel.Font, this.legendLabel.MaximumSize.Width).Height + 20; } if (this.quest.additionalRequirements.Count > 0 || this.quest.questRequirements.Count > 0) { Label label = new Label(); label.Text = "Requirements"; label.Location = new Point(5, y); label.ForeColor = StyleManager.NotificationTextColor; label.BackColor = Color.Transparent; label.Font = questTitle.Font; label.Size = new Size(this.Size.Width - 10, label.Height); this.Controls.Add(label); y += 25; // Item requirements if (this.quest.questRequirements.Count > 0) { List<Tuple<int, Item>> requirements = new List<Tuple<int, Item>>(); foreach (Tuple<int, int> tpl in quest.questRequirements) { Item item = StorageManager.getItem(tpl.Item2); requirements.Add(new Tuple<int, Item>(tpl.Item1, item)); } requirements = requirements.OrderBy(o => o.Item1 * o.Item2.GetMaxValue()).ToList(); List<TibiaObject> itemList = requirements.Select(o => o.Item2).ToList<TibiaObject>(); List<Control> itemControls = new List<Control>(); y = y + UIManager.DisplayCreatureList(this.Controls, itemList, 10, y, this.Size.Width - 10, 1, null, 1, itemControls); int itemnr = 0; foreach (Control control in itemControls) { control.BackgroundImage = StyleManager.GetImage("item_background.png"); int itemCount = requirements[itemnr].Item1; Item item = requirements[itemnr].Item2; (control as PictureBox).Image = LootDropForm.DrawCountOnItem(item, itemCount); itemnr++; } } // Text requirements if (this.quest.additionalRequirements.Count > 0) { List<string> requirementStrings = this.quest.additionalRequirements.ToList(); if (this.quest.minlevel > 0) { requirementStrings.Add(String.Format("You must be at least level {0}.", this.quest.minlevel)); } y += 5; Regex questRegex = new Regex("\\[([^]]+)\\]"); foreach (string text in requirementStrings) { label = new Label(); string txt = text; Match m = questRegex.Match(txt); label.ForeColor = StyleManager.NotificationTextColor; if (m != null && m.Groups.Count > 1) { string requiredQuestName = m.Groups[1].Value; txt = txt.Replace(m.Groups[0].Value, requiredQuestName); label.Name = StorageManager.getQuest(requiredQuestName.ToLower()).GetCommand(); label.ForeColor = StyleManager.ClickableLinkColor; label.Click += MissionButton_Click; } label.Text = txt == "" ? "" : "- " + txt; label.Location = new Point(5, y); label.BackColor = Color.Transparent; label.Font = QuestGuideForm.requirementFont; Size size; using (Graphics gr = Graphics.FromHwnd(label.Handle)) { size = gr.MeasureString(label.Text, label.Font, this.Size.Width - 50).ToSize(); label.Size = new Size(this.Size.Width - 10, (int)(size.Height * 1.2)); } this.Controls.Add(label); y += label.Size.Height; } } } if (rewards.Count > 0 || quest.rewardOutfits.Count > 0) { Label label = new Label(); label.Text = "Rewards"; label.Location = new Point(40, y); label.ForeColor = StyleManager.NotificationTextColor; label.BackColor = Color.Transparent; label.Font = questTitle.Font; this.Controls.Add(label); y += 25; if (rewards.Count > 0) { List<Control> itemControls = new List<Control>(); y = y + UIManager.DisplayCreatureList(this.Controls, rewards, 10, y, this.Size.Width - 10, 1, null, 1, itemControls); } if (quest.rewardOutfits.Count > 0) { List<Control> outfitControls = new List<Control>(); List<TibiaObject> rewardOutfits = new List<TibiaObject>(); foreach (int reward in quest.rewardOutfits) { Outfit outfit = StorageManager.getOutfit(reward); rewardOutfits.Add(outfit); } y = y + UIManager.DisplayCreatureList(this.Controls, rewardOutfits, 10, y, this.Size.Width - 10, 4, null, 1, outfitControls); } } this.Size = new Size(this.Size.Width, y + 20); base.NotificationFinalize(); this.ResumeLayout(false); } private void outfitClick(object sender, EventArgs e) { this.ReturnFocusToTibia(); CommandManager.ExecuteCommand("outfit" + Constants.CommandSymbol + (sender as Control).Name); } private void itemClick(object sender, EventArgs e) { this.ReturnFocusToTibia(); CommandManager.ExecuteCommand("item" + Constants.CommandSymbol + (sender as Control).Name); } private void MissionButton_Click(object sender, EventArgs e) { CommandManager.ExecuteCommand((sender as Control).Name); } private void wikiButton_Click(object sender, EventArgs e) { MainForm.OpenUrl(String.Format("http://tibia.wikia.com/wiki/{0}/Spoiler", quest.title)); } public override string FormName() { return "QuestForm"; } } }
using System; using System.Collections; using BigMath; using Raksha.Asn1; using Raksha.Crypto; using Raksha.Crypto.Digests; using Raksha.Math; namespace Raksha.Asn1.X509 { /** * The AuthorityKeyIdentifier object. * <pre> * id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } * * AuthorityKeyIdentifier ::= Sequence { * keyIdentifier [0] IMPLICIT KeyIdentifier OPTIONAL, * authorityCertIssuer [1] IMPLICIT GeneralNames OPTIONAL, * authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL } * * KeyIdentifier ::= OCTET STRING * </pre> * */ public class AuthorityKeyIdentifier : Asn1Encodable { internal readonly Asn1OctetString keyidentifier; internal readonly GeneralNames certissuer; internal readonly DerInteger certserno; public static AuthorityKeyIdentifier GetInstance( Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } public static AuthorityKeyIdentifier GetInstance( object obj) { if (obj is AuthorityKeyIdentifier) { return (AuthorityKeyIdentifier) obj; } if (obj is Asn1Sequence) { return new AuthorityKeyIdentifier((Asn1Sequence) obj); } if (obj is X509Extension) { return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); } protected internal AuthorityKeyIdentifier( Asn1Sequence seq) { foreach (Asn1TaggedObject o in seq) { switch (o.TagNo) { case 0: this.keyidentifier = Asn1OctetString.GetInstance(o, false); break; case 1: this.certissuer = GeneralNames.GetInstance(o, false); break; case 2: this.certserno = DerInteger.GetInstance(o, false); break; default: throw new ArgumentException("illegal tag"); } } } /** * * Calulates the keyidentifier using a SHA1 hash over the BIT STRING * from SubjectPublicKeyInfo as defined in RFC2459. * * Example of making a AuthorityKeyIdentifier: * <pre> * SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream( * publicKey.getEncoded()).readObject()); * AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); * </pre> * **/ public AuthorityKeyIdentifier( SubjectPublicKeyInfo spki) { IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); this.keyidentifier = new DerOctetString(resBuf); } /** * create an AuthorityKeyIdentifier with the GeneralNames tag and * the serial number provided as well. */ public AuthorityKeyIdentifier( SubjectPublicKeyInfo spki, GeneralNames name, BigInteger serialNumber) { IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); this.keyidentifier = new DerOctetString(resBuf); this.certissuer = name; this.certserno = new DerInteger(serialNumber); } /** * create an AuthorityKeyIdentifier with the GeneralNames tag and * the serial number provided. */ public AuthorityKeyIdentifier( GeneralNames name, BigInteger serialNumber) { this.keyidentifier = null; this.certissuer = GeneralNames.GetInstance(name.ToAsn1Object()); this.certserno = new DerInteger(serialNumber); } /** * create an AuthorityKeyIdentifier with a precomputed key identifier */ public AuthorityKeyIdentifier( byte[] keyIdentifier) { this.keyidentifier = new DerOctetString(keyIdentifier); this.certissuer = null; this.certserno = null; } /** * create an AuthorityKeyIdentifier with a precomupted key identifier * and the GeneralNames tag and the serial number provided as well. */ public AuthorityKeyIdentifier( byte[] keyIdentifier, GeneralNames name, BigInteger serialNumber) { this.keyidentifier = new DerOctetString(keyIdentifier); this.certissuer = GeneralNames.GetInstance(name.ToAsn1Object()); this.certserno = new DerInteger(serialNumber); } public byte[] GetKeyIdentifier() { return keyidentifier == null ? null : keyidentifier.GetOctets(); } public GeneralNames AuthorityCertIssuer { get { return certissuer; } } public BigInteger AuthorityCertSerialNumber { get { return certserno == null ? null : certserno.Value; } } /** * Produce an object suitable for an Asn1OutputStream. */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(); if (keyidentifier != null) { v.Add(new DerTaggedObject(false, 0, keyidentifier)); } if (certissuer != null) { v.Add(new DerTaggedObject(false, 1, certissuer)); } if (certserno != null) { v.Add(new DerTaggedObject(false, 2, certserno)); } return new DerSequence(v); } public override string ToString() { return ("AuthorityKeyIdentifier: KeyID(" + this.keyidentifier.GetOctets() + ")"); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Remoting.Internal; using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet takes a Job object and checks to see if it is debuggable. If it /// is debuggable then it breaks into the job debugger in step mode. If it is not /// debuggable then it is treated as a parent job and each child job is checked if /// it is debuggable and if it is will break into its job debugger in step mode. /// For multiple debuggable child jobs, each job execution will be halted and the /// debugger will step to each job execution point sequentially. /// /// When a job is debugged its output data is written to host and the executing job /// script will break into the host debugger, in step mode, at the next stoppable /// execution point. /// </summary> [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] [Cmdlet(VerbsDiagnostic.Debug, "Job", SupportsShouldProcess = true, DefaultParameterSetName = DebugJobCommand.JobParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=330208")] public sealed class DebugJobCommand : PSCmdlet { #region Strings private const string JobParameterSet = "JobParameterSet"; private const string JobNameParameterSet = "JobNameParameterSet"; private const string JobIdParameterSet = "JobIdParameterSet"; private const string JobInstanceIdParameterSet = "JobInstanceIdParameterSet"; #endregion #region Private members private Job _job; private Debugger _debugger; private PSDataCollection<PSStreamObject> _debugCollection; #endregion #region Parameters /// <summary> /// The Job object to be debugged. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = DebugJobCommand.JobParameterSet)] public Job Job { get; set; } /// <summary> /// The Job object name to be debugged. /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = DebugJobCommand.JobNameParameterSet)] public string Name { get; set; } /// <summary> /// The Job object Id to be debugged. /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = DebugJobCommand.JobIdParameterSet)] public int Id { get; set; } /// <summary> /// The Job object InstanceId to be debugged. /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = DebugJobCommand.JobInstanceIdParameterSet)] public Guid InstanceId { get; set; } /// <summary> /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. /// </summary> [Parameter] public SwitchParameter BreakAll { get; set; } #endregion #region Overrides /// <summary> /// End processing. Do work. /// </summary> protected override void EndProcessing() { switch (ParameterSetName) { case DebugJobCommand.JobParameterSet: _job = Job; break; case DebugJobCommand.JobNameParameterSet: _job = GetJobByName(Name); break; case DebugJobCommand.JobIdParameterSet: _job = GetJobById(Id); break; case DebugJobCommand.JobInstanceIdParameterSet: _job = GetJobByInstanceId(InstanceId); break; } if (!ShouldProcess(_job.Name, VerbsDiagnostic.Debug)) { return; } Runspace runspace = LocalRunspace.DefaultRunspace; if (runspace == null || runspace.Debugger == null) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(RemotingErrorIdStrings.CannotDebugJobNoHostDebugger), "DebugJobNoHostDebugger", ErrorCategory.InvalidOperation, this) ); } if ((runspace.Debugger.DebugMode == DebugModes.Default) || (runspace.Debugger.DebugMode == DebugModes.None)) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(RemotingErrorIdStrings.CannotDebugJobInvalidDebuggerMode), "DebugJobWrongDebugMode", ErrorCategory.InvalidOperation, this) ); } if (this.Host == null || this.Host.UI == null) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(RemotingErrorIdStrings.CannotDebugJobNoHostUI), "DebugJobNoHostAvailable", ErrorCategory.InvalidOperation, this) ); } if (!CheckForDebuggableJob()) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(DebuggerStrings.NoDebuggableJobsFound), "DebugJobNoDebuggableJobsFound", ErrorCategory.InvalidOperation, this) ); } // Set up host script debugger to debug the job. _debugger = runspace.Debugger; _debugger.DebugJob(_job, breakAll: BreakAll); // Blocking call. Send job output to host UI while debugging and wait for Job completion. WaitAndReceiveJobOutput(); } /// <summary> /// Stop processing. /// </summary> protected override void StopProcessing() { // Cancel job debugging. Debugger debugger = _debugger; if ((debugger != null) && (_job != null)) { debugger.StopDebugJob(_job); } // Unblock the data collection. PSDataCollection<PSStreamObject> debugCollection = _debugCollection; if (debugCollection != null) { debugCollection.Complete(); } } #endregion #region Private methods /// <summary> /// Check for debuggable job. Job must implement IJobDebugger and also /// must be running or in Debug stopped state. /// </summary> /// <returns></returns> private bool CheckForDebuggableJob() { // Check passed in job object. bool debuggableJobFound = GetJobDebuggable(_job); if (!debuggableJobFound) { // Assume passed in job is a container job and check child jobs. foreach (var cJob in _job.ChildJobs) { debuggableJobFound = GetJobDebuggable(cJob); if (debuggableJobFound) { break; } } } return debuggableJobFound; } private static bool GetJobDebuggable(Job job) { if (job is IJobDebugger) { return ((job.JobStateInfo.State == JobState.Running) || (job.JobStateInfo.State == JobState.AtBreakpoint)); } return false; } private void WaitAndReceiveJobOutput() { _debugCollection = new PSDataCollection<PSStreamObject>(); _debugCollection.BlockingEnumerator = true; try { AddEventHandlers(); // This call blocks (blocking enumerator) until the job completes // or this command is cancelled. foreach (var streamItem in _debugCollection) { if (streamItem != null) { streamItem.WriteStreamObject(this); } } } catch (Exception) { // Terminate job on exception. if (!_job.IsFinishedState(_job.JobStateInfo.State)) { _job.StopJob(); } throw; } finally { RemoveEventHandlers(); _debugCollection = null; } } private void HandleJobStateChangedEvent(object sender, JobStateEventArgs stateChangedArgs) { Job job = sender as Job; if (job.IsFinishedState(stateChangedArgs.JobStateInfo.State)) { _debugCollection.Complete(); } } private void HandleResultsDataAdding(object sender, DataAddingEventArgs dataAddingArgs) { if (_debugCollection.IsOpen) { PSStreamObject streamObject = dataAddingArgs.ItemAdded as PSStreamObject; if (streamObject != null) { try { _debugCollection.Add(streamObject); } catch (PSInvalidOperationException) { } } } } private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArgs e) { StopProcessing(); } private void AddEventHandlers() { _job.StateChanged += HandleJobStateChangedEvent; _debugger.NestedDebuggingCancelledEvent += HandleDebuggerNestedDebuggingCancelledEvent; if (_job.ChildJobs.Count == 0) { // No child jobs, monitor this job's results collection. _job.Results.DataAdding += HandleResultsDataAdding; } else { // Monitor each child job's results collections. foreach (var childJob in _job.ChildJobs) { childJob.Results.DataAdding += HandleResultsDataAdding; } } } private void RemoveEventHandlers() { _job.StateChanged -= HandleJobStateChangedEvent; _debugger.NestedDebuggingCancelledEvent -= HandleDebuggerNestedDebuggingCancelledEvent; if (_job.ChildJobs.Count == 0) { // Remove single job DataAdding event handler. _job.Results.DataAdding -= HandleResultsDataAdding; } else { // Remove each child job's DataAdding event handler. foreach (var childJob in _job.ChildJobs) { childJob.Results.DataAdding -= HandleResultsDataAdding; } } } private Job GetJobByName(string name) { // Search jobs in job repository. List<Job> jobs1 = new List<Job>(); WildcardPattern pattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase | WildcardOptions.Compiled); foreach (Job job in JobRepository.Jobs) { if (pattern.IsMatch(job.Name)) { jobs1.Add(job); } } // Search jobs in job manager. List<Job2> jobs2 = JobManager.GetJobsByName(name, this, false, false, false, null); int jobCount = jobs1.Count + jobs2.Count; if (jobCount == 1) { return (jobs1.Count > 0) ? jobs1[0] : jobs2[0]; } if (jobCount > 1) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.FoundMultipleJobsWithName, name)), "DebugJobFoundMultipleJobsWithName", ErrorCategory.InvalidOperation, this) ); return null; } ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.CannotFindJobWithName, name)), "DebugJobCannotFindJobWithName", ErrorCategory.InvalidOperation, this) ); return null; } private Job GetJobById(int id) { // Search jobs in job repository. List<Job> jobs1 = new List<Job>(); foreach (Job job in JobRepository.Jobs) { if (job.Id == id) { jobs1.Add(job); } } // Search jobs in job manager. Job job2 = JobManager.GetJobById(id, this, false, false, false); if ((jobs1.Count == 0) && (job2 == null)) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.CannotFindJobWithId, id)), "DebugJobCannotFindJobWithId", ErrorCategory.InvalidOperation, this) ); return null; } if ((jobs1.Count > 1) || (jobs1.Count == 1) && (job2 != null)) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.FoundMultipleJobsWithId, id)), "DebugJobFoundMultipleJobsWithId", ErrorCategory.InvalidOperation, this) ); return null; } return (jobs1.Count > 0) ? jobs1[0] : job2; } private Job GetJobByInstanceId(Guid instanceId) { // Search jobs in job repository. foreach (Job job in JobRepository.Jobs) { if (job.InstanceId == instanceId) { return job; } } // Search jobs in job manager. Job2 job2 = JobManager.GetJobByInstanceId(instanceId, this, false, false, false); if (job2 != null) { return job2; } ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.CannotFindJobWithInstanceId, instanceId)), "DebugJobCannotFindJobWithInstanceId", ErrorCategory.InvalidOperation, this) ); return null; } #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. /* ** Copyright (c) Microsoft. All rights reserved. ** Licensed under the MIT license. ** See LICENSE file in the project root for full license information. ** ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /************************ ** BITFIELD OPERATIONS ** *************************/ /************* ** DoBitops ** ************** ** Perform the bit operations test portion of the CPU ** benchmark. Returns the iterations per second. */ using System; public class BitOps : BitOpStruct { public override string Name() { return "BITFIELD"; } public override double Run() { int[] bitarraybase; /* Base of bitmap array */ int[] bitoparraybase; /* Base of bitmap operations array */ int nbitops = 0; /* # of bitfield operations */ long accumtime; /* Accumulated time in ticks */ double iterations; /* # of iterations */ /* ** See if we need to run adjustment code. */ if (this.adjust == 0) { bitarraybase = new int[this.bitfieldarraysize]; /* ** Initialize bitfield operations array to [2,30] elements */ this.bitoparraysize = 30; while (true) { /* ** Allocate space for operations array */ bitoparraybase = new int[this.bitoparraysize * 2]; /* ** Do an iteration of the bitmap test. If the ** elapsed time is less than or equal to the permitted ** minimum, then de-allocate the array, reallocate a ** larger version, and try again. */ if (DoBitfieldIteration(bitarraybase, bitoparraybase, this.bitoparraysize, ref nbitops) > global.min_ticks) break; /* We're ok...exit */ this.bitoparraysize += 100; } } else { /* ** Don't need to do self adjustment, just allocate ** the array space. */ bitarraybase = new int[this.bitfieldarraysize]; bitoparraybase = new int[this.bitoparraysize * 2]; } /* ** All's well if we get here. Repeatedly perform bitops until the ** accumulated elapsed time is greater than # of seconds requested. */ accumtime = 0; iterations = (double)0.0; do { accumtime += DoBitfieldIteration(bitarraybase, bitoparraybase, this.bitoparraysize, ref nbitops); iterations += (double)nbitops; } while (ByteMark.TicksToSecs(accumtime) < this.request_secs); /* ** Clean up, calculate results, and go home. ** Also, set adjustment flag to show that we don't have ** to do self adjusting in the future. */ if (this.adjust == 0) this.adjust = 1; return (iterations / ByteMark.TicksToFracSecs(accumtime)); } /************************ ** DoBitfieldIteration ** ************************* ** Perform a single iteration of the bitfield benchmark. ** Return the # of ticks accumulated by the operation. */ private static long DoBitfieldIteration(int[] bitarraybase, int[] bitoparraybase, int bitoparraysize, ref int nbitops) { int i; /* Index */ int bitoffset; /* Offset into bitmap */ long elapsed; /* Time to execute */ /* ** Clear # bitops counter */ nbitops = 0; /* ** Construct a set of bitmap offsets and run lengths. ** The offset can be any random number from 0 to the ** size of the bitmap (in bits). The run length can ** be any random number from 1 to the number of bits ** between the offset and the end of the bitmap. ** Note that the bitmap has 8192 * 32 bits in it. ** (262,144 bits) */ for (i = 0; i < bitoparraysize; i++) { /* First item is offset */ bitoparraybase[i + i] = bitoffset = ByteMark.abs_randwc(262140); /* Next item is run length */ nbitops += bitoparraybase[i + i + 1] = ByteMark.abs_randwc(262140 - bitoffset); } /* ** Array of offset and lengths built...do an iteration of ** the test. ** Start the stopwatch. */ elapsed = ByteMark.StartStopwatch(); /* ** Loop through array off offset/run length pairs. ** Execute operation based on modulus of index. */ for (i = 0; i < bitoparraysize; i++) { switch (i % 3) { case 0: /* Set run of bits */ ToggleBitRun(bitarraybase, bitoparraybase[i + i], bitoparraybase[i + i + 1], 1); break; case 1: /* Clear run of bits */ ToggleBitRun(bitarraybase, bitoparraybase[i + i], bitoparraybase[i + i + 1], 0); break; case 2: /* Complement run of bits */ FlipBitRun(bitarraybase, bitoparraybase[i + i], bitoparraybase[i + i + 1]); break; } } /* ** Return elapsed time */ return (ByteMark.StopStopwatch(elapsed)); } /***************************** ** ToggleBitRun * ****************************** ** Set or clear a run of nbits starting at ** bit_addr in bitmap. */ private static void ToggleBitRun(int[] bitmap, /* Bitmap */ int bit_addr, /* Address of bits to set */ int nbits, /* # of bits to set/clr */ int val) /* 1 or 0 */ { int bindex; /* Index into array */ int bitnumb; /* Bit number */ while (nbits-- > 0) { #if LONG64 bindex=bit_addr>>>6; /* Index is number /64 */ bindex=bit_addr % 64; /* Bit number in word */ #else bindex = (int)((uint)bit_addr) >> 5; /* Index is number /32 */ bitnumb = bit_addr % 32; /* bit number in word */ #endif if (val != 0) bitmap[bindex] |= (1 << bitnumb); else bitmap[bindex] &= ~(1 << bitnumb); bit_addr++; } return; } /*************** ** FlipBitRun ** **************** ** Complements a run of bits. */ private static void FlipBitRun(int[] bitmap, /* Bit map */ int bit_addr, /* Bit address */ int nbits) /* # of bits to flip */ { int bindex; /* Index into array */ int bitnumb; /* Bit number */ while (nbits-- > 0) { #if LONG64 bindex=bit_addr>>6; /* Index is number /64 */ bitnumb=bit_addr % 32; /* Bit number in longword */ #else bindex = bit_addr >> 5; /* Index is number /32 */ bitnumb = bit_addr % 32; /* Bit number in longword */ #endif bitmap[bindex] ^= (1 << bitnumb); bit_addr++; } return; } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.IO; using System.Xml; /// <summary> /// A class represents a Xml Writer XmlWriterInjector which inherits from "XmlWriter". /// Use this class instead of XmlWriter to get the request data from request stream during the processing of the proxy class generated by WSDL.exe. /// </summary> public class XmlWriterInjector : XmlWriter { /// <summary> /// An XmlWriter instance. /// </summary> private XmlWriter originalXmlWriter; /// <summary> /// An XmlTextWriter instance. /// </summary> private XmlTextWriter injectorXmlTextWriter; /// <summary> /// A StringWriter instance. /// </summary> private StringWriter stringWriterInstance; /// <summary> /// Initializes a new instance of the XmlWriterInjector class. /// </summary> /// <param name="implementation">A parameter instance represents an XmlWriter type implementation.</param> public XmlWriterInjector(XmlWriter implementation) { this.originalXmlWriter = implementation; this.stringWriterInstance = new StringWriter(); this.injectorXmlTextWriter = new XmlTextWriter(this.stringWriterInstance); this.injectorXmlTextWriter.Formatting = Formatting.Indented; } /// <summary> /// Gets the xml string which is written to request stream. /// </summary> public string Xml { get { return this.stringWriterInstance == null ? null : this.stringWriterInstance.ToString(); } } /// <summary> /// A method used to override the method "WriteState" of XmlWriter. /// </summary> public override WriteState WriteState { get { return this.originalXmlWriter.WriteState; } } /// <summary> /// Gets the current xml:lang scope. /// </summary> public override string XmlLang { get { return this.originalXmlWriter.XmlLang; } } /// <summary> /// Gets an System.Xml.XmlSpace representing the current xml:space scope. /// None: This is the default value if no xml:space scope exists. /// Default: This value is meaning the current scope is xml:space="default". /// Preserve: This value is meaning the current scope is xml:space="preserve". /// </summary> public override XmlSpace XmlSpace { get { return this.originalXmlWriter.XmlSpace; } } /// <summary> /// A method used to override the method "Flush". /// It flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public override void Flush() { this.originalXmlWriter.Flush(); this.injectorXmlTextWriter.Flush(); this.stringWriterInstance.Flush(); } /// <summary> /// A method used to override the method "Close". /// It closes this stream and the underlying stream. /// </summary> public override void Close() { this.originalXmlWriter.Close(); this.injectorXmlTextWriter.Close(); } /// <summary> /// A method used to override the method "LookupPrefix". /// It returns the closest prefix defined in the current namespace scope for the namespace URI. /// </summary> /// <param name="ns">A method represents the namespace URI whose prefix you want to find.</param> /// <returns> A return value represents the matching prefix or null if no matching namespace URI is found in the current scope.</returns> public override string LookupPrefix(string ns) { return this.originalXmlWriter.LookupPrefix(ns); } /// <summary> /// A method used to override the method "WriteBase64" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents Byte array to encode.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the bytes to write.</param> /// <param name="count">A parameter represents the number of bytes to write.</param> public override void WriteBase64(byte[] buffer, int index, int count) { this.originalXmlWriter.WriteBase64(buffer, index, count); this.injectorXmlTextWriter.WriteBase64(buffer, index, count); } /// <summary> /// A method used to override the method "WriteCData" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to place inside the CDATA block.</param> public override void WriteCData(string text) { this.originalXmlWriter.WriteCData(text); this.injectorXmlTextWriter.WriteCData(text); } /// <summary> /// A method used to override the method "WriteCharEntity" of XmlWriter. /// </summary> /// <param name="ch">A parameter represents the Unicode character for which to generate a character entity.</param> public override void WriteCharEntity(char ch) { this.originalXmlWriter.WriteCharEntity(ch); this.injectorXmlTextWriter.WriteCharEntity(ch); } /// <summary> /// A method used to override the method "WriteChars" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents the character array containing the text to write.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the text to write.</param> /// <param name="count">A parameter represents the number of characters to write.</param> public override void WriteChars(char[] buffer, int index, int count) { this.originalXmlWriter.WriteChars(buffer, index, count); this.injectorXmlTextWriter.WriteChars(buffer, index, count); } /// <summary> /// A method used to override the method "WriteComment" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to place inside the comment.</param> public override void WriteComment(string text) { this.originalXmlWriter.WriteComment(text); this.injectorXmlTextWriter.WriteComment(text); } /// <summary> /// A method used to override the method "WriteDocType" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the DOCTYPE. This must be non-empty.</param> /// <param name="pubid">A parameter represents that if non-null it also writes PUBLIC "pubid" "sysid" where pubid and sysid are replaced with the value of the given arguments.</param> /// <param name="sysid">A parameter represents that if pubid is null and sysid is non-null it writes SYSTEM "sysid" where sysid is replaced with the value of this argument.</param> /// <param name="subset">A parameter represents that if non-null it writes [subset] where subset is replaced with the value of this argument.</param> public override void WriteDocType(string name, string pubid, string sysid, string subset) { this.originalXmlWriter.WriteDocType(name, pubid, sysid, subset); this.injectorXmlTextWriter.WriteDocType(name, pubid, sysid, subset); } /// <summary> /// A method used to override the method "WriteEndAttribute" of XmlWriter. /// </summary> public override void WriteEndAttribute() { this.originalXmlWriter.WriteEndAttribute(); this.injectorXmlTextWriter.WriteEndAttribute(); } /// <summary> /// A method used to override the method "WriteEndDocument" of XmlWriter. /// </summary> public override void WriteEndDocument() { this.originalXmlWriter.WriteEndDocument(); this.injectorXmlTextWriter.WriteEndDocument(); } /// <summary> /// A method used to override the method "WriteEndElement" of XmlWriter. /// </summary> public override void WriteEndElement() { this.originalXmlWriter.WriteEndElement(); this.injectorXmlTextWriter.WriteEndElement(); } /// <summary> /// A method used to override the method "WriteEntityRef" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the entity reference.</param> public override void WriteEntityRef(string name) { this.originalXmlWriter.WriteEntityRef(name); this.injectorXmlTextWriter.WriteEntityRef(name); } /// <summary> /// A method used to override the method "WriteFullEndElement" of XmlWriter. /// </summary> public override void WriteFullEndElement() { this.originalXmlWriter.WriteFullEndElement(); this.injectorXmlTextWriter.WriteFullEndElement(); } /// <summary> /// A method used to override the method "WriteProcessingInstruction" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the processing instruction.</param> /// <param name="text">A parameter represents the text to include in the processing instruction.</param> public override void WriteProcessingInstruction(string name, string text) { this.originalXmlWriter.WriteProcessingInstruction(name, text); this.injectorXmlTextWriter.WriteProcessingInstruction(name, text); } /// <summary> /// A method used to override the method "WriteRaw" of XmlWriter. /// </summary> /// <param name="data">A parameter represents the string containing the text to write.</param> public override void WriteRaw(string data) { this.originalXmlWriter.WriteRaw(data); this.injectorXmlTextWriter.WriteRaw(data); } /// <summary> /// A method used to override the method "WriteRaw" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents character array containing the text to write.</param> /// <param name="index">A parameter represents the position within the buffer indicating the start of the text to write.</param> /// <param name="count">A parameter represents the number of characters to write.</param> public override void WriteRaw(char[] buffer, int index, int count) { this.originalXmlWriter.WriteRaw(buffer, index, count); this.injectorXmlTextWriter.WriteRaw(buffer, index, count); } /// <summary> /// A method used to override the method "WriteStartAttribute" of XmlWriter. /// </summary> /// <param name="prefix">A parameter represents the namespace prefix of the attribute.</param> /// <param name="localName">A parameter represents the local name of the attribute.</param> /// <param name="ns">A parameter represents the namespace URI for the attribute.</param> public override void WriteStartAttribute(string prefix, string localName, string ns) { this.originalXmlWriter.WriteStartAttribute(prefix, localName, ns); this.injectorXmlTextWriter.WriteStartAttribute(prefix, localName, ns); } /// <summary> /// A method used to override the method "WriteStartDocument" of XmlWriter. /// </summary> /// <param name="standalone">A parameter represents that if true, it writes "standalone=yes"; if false, it writes "standalone=no".</param> public override void WriteStartDocument(bool standalone) { this.originalXmlWriter.WriteStartDocument(standalone); this.injectorXmlTextWriter.WriteStartDocument(standalone); } /// <summary> /// A method used to override the method "WriteStartDocument" of XmlWriter. /// </summary> public override void WriteStartDocument() { this.originalXmlWriter.WriteStartDocument(); this.injectorXmlTextWriter.WriteStartDocument(); } /// <summary> /// A method used to override the method "WriteStartElement" of XmlWriter. /// </summary> /// <param name="prefix">A parameter represents the namespace prefix of the element.</param> /// <param name="localName">A parameter represents the local name of the element.</param> /// <param name="ns">A parameter represents the namespace URI to associate with the element.</param> public override void WriteStartElement(string prefix, string localName, string ns) { this.originalXmlWriter.WriteStartElement(prefix, localName, ns); this.injectorXmlTextWriter.WriteStartElement(prefix, localName, ns); } /// <summary> /// A method used to override the method "WriteString" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to write.</param> public override void WriteString(string text) { this.originalXmlWriter.WriteString(text); this.injectorXmlTextWriter.WriteString(text); } /// <summary> /// A method used to override the method "WriteSurrogateCharEntity" of XmlWriter. /// </summary> /// <param name="lowChar">A parameter represents the low surrogate. This must be a value between 0xDC00 and 0xDFFF.</param> /// <param name="highChar">A parameter represents the high surrogate. This must be a value between 0xD800 and 0xDBFF.</param> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { this.originalXmlWriter.WriteSurrogateCharEntity(lowChar, highChar); this.injectorXmlTextWriter.WriteSurrogateCharEntity(lowChar, highChar); } /// <summary> /// A method used to override the method "WriteWhitespace" of XmlWriter. /// </summary> /// <param name="ws">A parameter represents the string of white space characters.</param> public override void WriteWhitespace(string ws) { this.originalXmlWriter.WriteWhitespace(ws); this.injectorXmlTextWriter.WriteWhitespace(ws); } /// <summary> /// A method used to write out the specified name, ensuring it is a valid name according to the W3C XML 1.0. /// </summary> /// <param name="name">A parameter represents the name to write.</param> public override void WriteName(string name) { this.originalXmlWriter.WriteName(name); this.injectorXmlTextWriter.WriteName(name); } /// <summary> /// A method used to encode the specified binary bytes as BinHex and writes out the resulting text. /// </summary> /// <param name="buffer">A parameter represents the Byte array to encode.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the bytes to write.</param> /// <param name="count">A parameter represents the number of bytes to write.</param> public override void WriteBinHex(byte[] buffer, int index, int count) { this.originalXmlWriter.WriteBinHex(buffer, index, count); this.injectorXmlTextWriter.WriteBinHex(buffer, index, count); } /// <summary> /// A method used to write out the specified name, ensuring it is a valid NmToken according to the W3C XML 1.0. /// </summary> /// <param name="name">A parameter represents the name to write.</param> public override void WriteNmToken(string name) { this.originalXmlWriter.WriteNmToken(name); this.injectorXmlTextWriter.WriteNmToken(name); } /// <summary> /// A method used to copy everything from the reader to the writer and moves the reader to the start of the next sibling. /// </summary> /// <param name="navigator">A parameter represents the System.Xml.XPath.XPathNavigator to copy from.</param> /// <param name="defattr">A parameter represents whether copy the default attributes from the XmlReader, true means copy, false means not copy.</param> public override void WriteNode(System.Xml.XPath.XPathNavigator navigator, bool defattr) { this.originalXmlWriter.WriteNode(navigator, defattr); this.injectorXmlTextWriter.WriteNode(navigator, defattr); } /// <summary> /// A method used to copy everything from the reader to the writer and moves the reader to the start of the next sibling. /// </summary> /// <param name="reader">A parameter represents the System.Xml.XmlReader to read from.</param> /// <param name="defattr">A parameter represents whether copy the default attributes from the XmlReader, true means copy, false means not copy.</param> public override void WriteNode(XmlReader reader, bool defattr) { this.originalXmlWriter.WriteNode(reader, defattr); this.injectorXmlTextWriter.WriteNode(reader, defattr); } /// <summary> /// A method used to write out the namespace-qualified name. /// </summary> /// <param name="localName">A parameter represents the local name to write.</param> /// <param name="ns">>A parameter represents the namespace URI for the name.</param> public override void WriteQualifiedName(string localName, string ns) { this.originalXmlWriter.WriteQualifiedName(localName, ns); this.injectorXmlTextWriter.WriteQualifiedName(localName, ns); } /// <summary> /// A method used to write a System.Boolean value. /// </summary> /// <param name="value">A parameter represents the System.Boolean value to write.</param> public override void WriteValue(bool value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a System.DateTime value. /// </summary> /// <param name="value">A parameter represents the System.DateTime value to write.</param> public override void WriteValue(DateTime value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a System.Decimal value. /// </summary> /// <param name="value">A parameter represents the System.Decimal value to write.</param> public override void WriteValue(decimal value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a System.Double value. /// </summary> /// <param name="value">A parameter represents the System.Double value to write.</param> public override void WriteValue(double value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a single-precision floating-point number. /// </summary> /// <param name="value">A parameter represents the single-precision floating-point number to write.</param> public override void WriteValue(float value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a System.Int32 value. /// </summary> /// <param name="value">A parameter represents the System.Int32 value to write.</param> public override void WriteValue(int value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write a System.Int64 value. /// </summary> /// <param name="value">A parameter represents the System.Int64 value to write.</param> public override void WriteValue(long value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to write the object value. /// </summary> /// <param name="value">A parameter represents the object value to write.</param> public override void WriteValue(object value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method write a System.String value. /// </summary> /// <param name="value">A parameter represents the System.Boolean value to write.</param> public override void WriteValue(string value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } } }
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCore.Configuration { /// <summary> /// Metadata about the shape of a JSON:API resource in the resource graph. /// </summary> [PublicAPI] public sealed class ResourceContext { private readonly Dictionary<string, ResourceFieldAttribute> _fieldsByPublicName = new(); private readonly Dictionary<string, ResourceFieldAttribute> _fieldsByPropertyName = new(); /// <summary> /// The publicly exposed resource name. /// </summary> public string PublicName { get; } /// <summary> /// The CLR type of the resource. /// </summary> public Type ResourceType { get; } /// <summary> /// The identity type of the resource. /// </summary> public Type IdentityType { get; } /// <summary> /// Exposed resource attributes and relationships. See https://jsonapi.org/format/#document-resource-object-fields. /// </summary> public IReadOnlyCollection<ResourceFieldAttribute> Fields { get; } /// <summary> /// Exposed resource attributes. See https://jsonapi.org/format/#document-resource-object-attributes. /// </summary> public IReadOnlyCollection<AttrAttribute> Attributes { get; } /// <summary> /// Exposed resource relationships. See https://jsonapi.org/format/#document-resource-object-relationships. /// </summary> public IReadOnlyCollection<RelationshipAttribute> Relationships { get; } /// <summary> /// Related entities that are not exposed as resource relationships. /// </summary> public IReadOnlyCollection<EagerLoadAttribute> EagerLoads { get; } /// <summary> /// Configures which links to show in the <see cref="Serialization.Objects.TopLevelLinks" /> object for this resource type. Defaults to /// <see cref="LinkTypes.NotConfigured" />, which falls back to <see cref="IJsonApiOptions.TopLevelLinks" />. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.TopLevelLinks" /> usage. /// </remarks> public LinkTypes TopLevelLinks { get; } /// <summary> /// Configures which links to show in the <see cref="Serialization.Objects.ResourceLinks" /> object for this resource type. Defaults to /// <see cref="LinkTypes.NotConfigured" />, which falls back to <see cref="IJsonApiOptions.ResourceLinks" />. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.ResourceLinks" /> usage. /// </remarks> public LinkTypes ResourceLinks { get; } /// <summary> /// Configures which links to show in the <see cref="Serialization.Objects.RelationshipLinks" /> object for all relationships of this resource type. /// Defaults to <see cref="LinkTypes.NotConfigured" />, which falls back to <see cref="IJsonApiOptions.RelationshipLinks" />. This can be overruled per /// relationship by setting <see cref="RelationshipAttribute.Links" />. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.RelationshipLinks" /> usage. /// </remarks> public LinkTypes RelationshipLinks { get; } public ResourceContext(string publicName, Type resourceType, Type identityType, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships, IReadOnlyCollection<EagerLoadAttribute> eagerLoads, LinkTypes topLevelLinks = LinkTypes.NotConfigured, LinkTypes resourceLinks = LinkTypes.NotConfigured, LinkTypes relationshipLinks = LinkTypes.NotConfigured) { ArgumentGuard.NotNullNorEmpty(publicName, nameof(publicName)); ArgumentGuard.NotNull(resourceType, nameof(resourceType)); ArgumentGuard.NotNull(identityType, nameof(identityType)); ArgumentGuard.NotNull(attributes, nameof(attributes)); ArgumentGuard.NotNull(relationships, nameof(relationships)); ArgumentGuard.NotNull(eagerLoads, nameof(eagerLoads)); PublicName = publicName; ResourceType = resourceType; IdentityType = identityType; Fields = attributes.Cast<ResourceFieldAttribute>().Concat(relationships).ToArray(); Attributes = attributes; Relationships = relationships; EagerLoads = eagerLoads; TopLevelLinks = topLevelLinks; ResourceLinks = resourceLinks; RelationshipLinks = relationshipLinks; foreach (ResourceFieldAttribute field in Fields) { _fieldsByPublicName.Add(field.PublicName, field); _fieldsByPropertyName.Add(field.Property.Name, field); } } public AttrAttribute GetAttributeByPublicName(string publicName) { AttrAttribute attribute = TryGetAttributeByPublicName(publicName); return attribute ?? throw new InvalidOperationException($"Attribute '{publicName}' does not exist on resource type '{PublicName}'."); } public AttrAttribute TryGetAttributeByPublicName(string publicName) { ArgumentGuard.NotNull(publicName, nameof(publicName)); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute field) && field is AttrAttribute attribute ? attribute : null; } public AttrAttribute GetAttributeByPropertyName(string propertyName) { AttrAttribute attribute = TryGetAttributeByPropertyName(propertyName); return attribute ?? throw new InvalidOperationException($"Attribute for property '{propertyName}' does not exist on resource type '{ResourceType.Name}'."); } public AttrAttribute TryGetAttributeByPropertyName(string propertyName) { ArgumentGuard.NotNull(propertyName, nameof(propertyName)); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute field) && field is AttrAttribute attribute ? attribute : null; } public RelationshipAttribute GetRelationshipByPublicName(string publicName) { RelationshipAttribute relationship = TryGetRelationshipByPublicName(publicName); return relationship ?? throw new InvalidOperationException($"Relationship '{publicName}' does not exist on resource type '{PublicName}'."); } public RelationshipAttribute TryGetRelationshipByPublicName(string publicName) { ArgumentGuard.NotNull(publicName, nameof(publicName)); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute field) && field is RelationshipAttribute relationship ? relationship : null; } public RelationshipAttribute GetRelationshipByPropertyName(string propertyName) { RelationshipAttribute relationship = TryGetRelationshipByPropertyName(propertyName); return relationship ?? throw new InvalidOperationException($"Relationship for property '{propertyName}' does not exist on resource type '{ResourceType.Name}'."); } public RelationshipAttribute TryGetRelationshipByPropertyName(string propertyName) { ArgumentGuard.NotNull(propertyName, nameof(propertyName)); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute field) && field is RelationshipAttribute relationship ? relationship : null; } public override string ToString() { return PublicName; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (obj is null || GetType() != obj.GetType()) { return false; } var other = (ResourceContext)obj; return PublicName == other.PublicName && ResourceType == other.ResourceType && IdentityType == other.IdentityType && Attributes.SequenceEqual(other.Attributes) && Relationships.SequenceEqual(other.Relationships) && EagerLoads.SequenceEqual(other.EagerLoads) && TopLevelLinks == other.TopLevelLinks && ResourceLinks == other.ResourceLinks && RelationshipLinks == other.RelationshipLinks; } public override int GetHashCode() { var hashCode = new HashCode(); hashCode.Add(PublicName); hashCode.Add(ResourceType); hashCode.Add(IdentityType); foreach (AttrAttribute attribute in Attributes) { hashCode.Add(attribute); } foreach (RelationshipAttribute relationship in Relationships) { hashCode.Add(relationship); } foreach (EagerLoadAttribute eagerLoad in EagerLoads) { hashCode.Add(eagerLoad); } hashCode.Add(TopLevelLinks); hashCode.Add(ResourceLinks); hashCode.Add(RelationshipLinks); return hashCode.ToHashCode(); } } }
// 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 contains the basic primitive type definitions (int etc) // These types are well known to the compiler and the runtime and are basic interchange types that do not change // CONTRACT with Runtime // Each of the data types has a data contract with the runtime. See the contract in the type definition // using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { // CONTRACT with Runtime // Place holder type for type hierarchy, Compiler/Runtime requires this class public abstract class ValueType { } // CONTRACT with Runtime, Compiler/Runtime requires this class // Place holder type for type hierarchy public abstract class Enum : ValueType { } /*============================================================ ** ** Class: Boolean ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ // CONTRACT with Runtime // The Boolean type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type bool public struct Boolean { // Disable compile warning about unused m_value field #pragma warning disable 0169 private bool _value; #pragma warning restore 0169 } /*============================================================ ** ** Class: Char ** ** ** Purpose: This is the value class representing a Unicode character ** ** ===========================================================*/ // CONTRACT with Runtime // The Char type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type char // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Char { private char _value; } /*============================================================ ** ** Class: SByte ** ** ** Purpose: A representation of a 8 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The SByte type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type sbyte // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct SByte { private sbyte _value; } /*============================================================ ** ** Class: Byte ** ** ** Purpose: A representation of a 8 bit integer (byte) ** ** ===========================================================*/ // CONTRACT with Runtime // The Byte type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type bool // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Byte { private byte _value; } /*============================================================ ** ** Class: Int16 ** ** ** Purpose: A representation of a 16 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int16 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type short // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int16 { private short _value; } /*============================================================ ** ** Class: UInt16 ** ** ** Purpose: A representation of a short (unsigned 16-bit) integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Uint16 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type ushort // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt16 { private ushort _value; } /*============================================================ ** ** Class: Int32 ** ** ** Purpose: A representation of a 32 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int32 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type int // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int32 { private int _value; } /*============================================================ ** ** Class: UInt32 ** ** ** Purpose: A representation of a 32 bit unsigned integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Uint32 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type uint // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt32 { private uint _value; } /*============================================================ ** ** Class: Int64 ** ** ** Purpose: A representation of a 64 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int64 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type long // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int64 { private long _value; } /*============================================================ ** ** Class: UInt64 ** ** ** Purpose: A representation of a 64 bit unsigned integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The UInt64 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type ulong // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt64 { private ulong _value; } /*============================================================ ** ** Class: Single ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ // CONTRACT with Runtime // The Single type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type float // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Single { private float _value; } /*============================================================ ** ** Class: Double ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ // CONTRACT with Runtime // The Double type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type double // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Double { private double _value; } /*============================================================ ** ** Class: IntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ // CONTRACT with Runtime // The IntPtr type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type void * // This type implements == without overriding GetHashCode, Equals, disable compiler warning #pragma warning disable 0660, 0661 public struct IntPtr { unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior [Intrinsic] public static readonly IntPtr Zero; [Intrinsic] public unsafe IntPtr(void* value) { _value = value; } [Intrinsic] public unsafe IntPtr(int value) { _value = (void*)value; } [Intrinsic] public unsafe IntPtr(long value) { _value = (void*)value; } [Intrinsic] public static unsafe explicit operator IntPtr(int value) { return new IntPtr(value); } [Intrinsic] public static unsafe explicit operator IntPtr(long value) { return new IntPtr(value); } [Intrinsic] public static unsafe explicit operator IntPtr(void* value) { return new IntPtr(value); } [Intrinsic] public static unsafe explicit operator void* (IntPtr value) { return value._value; } [Intrinsic] public static unsafe explicit operator int(IntPtr value) { return unchecked((int)value._value); } [Intrinsic] public static unsafe explicit operator long(IntPtr value) { return unchecked((long)value._value); } [Intrinsic] public unsafe static bool operator ==(IntPtr value1, IntPtr value2) { return value1._value == value2._value; } [Intrinsic] public unsafe static bool operator !=(IntPtr value1, IntPtr value2) { return value1._value != value2._value; } } #pragma warning restore 0660, 0661 /*============================================================ ** ** Class: UIntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ // CONTRACT with Runtime // The UIntPtr type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type void * // This type implements == without overriding GetHashCode, Equals, disable compiler warning #pragma warning disable 0660, 0661 public struct UIntPtr { unsafe private void* _value; [Intrinsic] public static readonly UIntPtr Zero; [Intrinsic] public unsafe UIntPtr(uint value) { _value = (void*)value; } [Intrinsic] public unsafe UIntPtr(ulong value) { #if BIT64 _value = (void*)value; #else _value = (void*)checked((uint)value); #endif } [Intrinsic] public unsafe UIntPtr(void* value) { _value = value; } [Intrinsic] public static unsafe explicit operator UIntPtr(void* value) { return new UIntPtr(value); } [Intrinsic] public static unsafe explicit operator void* (UIntPtr value) { return value._value; } [Intrinsic] public unsafe static explicit operator uint (UIntPtr value) { #if BIT64 return checked((uint)value._value); #else return (uint)value._value; #endif } [Intrinsic] public unsafe static explicit operator ulong (UIntPtr value) { return (ulong)value._value; } [Intrinsic] public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2) { return value1._value == value2._value; } [Intrinsic] public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2) { return value1._value != value2._value; } } #pragma warning restore 0660, 0661 }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor { public sealed partial class CBORNumber { /* The "==" and "!=" operators are not overridden in the .NET version to be consistent with Equals, for the following reason: Objects with this type can have arbitrary size (e.g., they can be arbitrary-precision integers), and comparing two of them for equality can be much more complicated and take much more time than the default behavior of reference equality. */ /// <summary>Returns whether one object's value is less than /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if the first object's value is less than the /// other's; otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator <(CBORNumber a, CBORNumber b) { return a == null ? b != null : a.CompareTo(b) < 0; } /// <summary>Returns whether one object's value is up to /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is up to another's; /// otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator <=(CBORNumber a, CBORNumber b) { return a == null || a.CompareTo(b) <= 0; } /// <summary>Returns whether one object's value is greater than /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is greater than /// another's; otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator >(CBORNumber a, CBORNumber b) { return a != null && a.CompareTo(b) > 0; } /// <summary>Returns whether one object's value is at least /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is at least another's; /// otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator >=(CBORNumber a, CBORNumber b) { return a == null ? b == null : a.CompareTo(b) >= 0; } /// <summary>Converts this number's value to an 8-bit signed integer if /// it can fit in an 8-bit signed integer after converting it to an /// integer by discarding its fractional part.</summary> /// <returns>This number's value, truncated to an 8-bit signed /// integer.</returns> /// <exception cref='OverflowException'>This value is infinity or /// not-a-number, or the number, once converted to an integer by /// discarding its fractional part, is less than -128 or greater than /// 127.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public sbyte ToSByteChecked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } return this.ToEInteger().ToSByteChecked(); } /// <summary>Converts this number's value to an integer by discarding /// its fractional part, and returns the least-significant bits of its /// two's-complement form as an 8-bit signed integer.</summary> /// <returns>This number, converted to an 8-bit signed integer. Returns /// 0 if this value is infinity or not-a-number.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public sbyte ToSByteUnchecked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.IsFinite() ? this.ToEInteger().ToSByteUnchecked() : (sbyte)0; } /// <summary>Converts this number's value to an 8-bit signed integer if /// it can fit in an 8-bit signed integer without rounding to a /// different numerical value.</summary> /// <returns>This number's value as an 8-bit signed integer.</returns> /// <exception cref='ArithmeticException'>This value is infinity or /// not-a-number, is not an exact integer, or is less than -128 or /// greater than 127.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public sbyte ToSByteIfExact() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } return this.IsZero() ? ((sbyte)0) : this.ToEIntegerIfExact().ToSByteChecked(); } /// <summary>Converts this number's value to a 16-bit unsigned integer /// if it can fit in a 16-bit unsigned integer after converting it to /// an integer by discarding its fractional part.</summary> /// <returns>This number's value, truncated to a 16-bit unsigned /// integer.</returns> /// <exception cref='OverflowException'>This value is infinity or /// not-a-number, or the number, once converted to an integer by /// discarding its fractional part, is less than 0 or greater than /// 65535.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ushort ToUInt16Checked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } return this.ToEInteger().ToUInt16Checked(); } /// <summary>Converts this number's value to an integer by discarding /// its fractional part, and returns the least-significant bits of its /// two's-complement form as a 16-bit unsigned integer.</summary> /// <returns>This number, converted to a 16-bit unsigned integer. /// Returns 0 if this value is infinity or not-a-number.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ushort ToUInt16Unchecked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.IsFinite() ? this.ToEInteger().ToUInt16Unchecked() : (ushort)0; } /// <summary>Converts this number's value to a 16-bit unsigned integer /// if it can fit in a 16-bit unsigned integer without rounding to a /// different numerical value.</summary> /// <returns>This number's value as a 16-bit unsigned /// integer.</returns> /// <exception cref='ArithmeticException'>This value is infinity or /// not-a-number, is not an exact integer, or is less than 0 or greater /// than 65535.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ushort ToUInt16IfExact() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } if (this.IsZero()) { return (ushort)0; } if (this.IsNegative()) { throw new OverflowException("Value out of range"); } return this.ToEIntegerIfExact().ToUInt16Checked(); } /// <summary>Converts this number's value to a 32-bit signed integer if /// it can fit in a 32-bit signed integer after converting it to an /// integer by discarding its fractional part.</summary> /// <returns>This number's value, truncated to a 32-bit signed /// integer.</returns> /// <exception cref='OverflowException'>This value is infinity or /// not-a-number, or the number, once converted to an integer by /// discarding its fractional part, is less than 0 or greater than /// 4294967295.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public uint ToUInt32Checked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } return this.ToEInteger().ToUInt32Checked(); } /// <summary>Converts this number's value to an integer by discarding /// its fractional part, and returns the least-significant bits of its /// two's-complement form as a 32-bit signed integer.</summary> /// <returns>This number, converted to a 32-bit signed integer. Returns /// 0 if this value is infinity or not-a-number.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public uint ToUInt32Unchecked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.IsFinite() ? this.ToEInteger().ToUInt32Unchecked() : 0U; } /// <summary>Converts this number's value to a 32-bit signed integer if /// it can fit in a 32-bit signed integer without rounding to a /// different numerical value.</summary> /// <returns>This number's value as a 32-bit signed integer.</returns> /// <exception cref='ArithmeticException'>This value is infinity or /// not-a-number, is not an exact integer, or is less than 0 or greater /// than 4294967295.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public uint ToUInt32IfExact() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } if (this.IsZero()) { return 0U; } if (this.IsNegative()) { throw new OverflowException("Value out of range"); } return this.ToEIntegerIfExact().ToUInt32Checked(); } /// <summary>Converts this number's value to a 64-bit unsigned integer /// if it can fit in a 64-bit unsigned integer after converting it to /// an integer by discarding its fractional part.</summary> /// <returns>This number's value, truncated to a 64-bit unsigned /// integer.</returns> /// <exception cref='OverflowException'>This value is infinity or /// not-a-number, or the number, once converted to an integer by /// discarding its fractional part, is less than 0 or greater than /// 18446744073709551615.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ulong ToUInt64Checked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } return this.ToEInteger().ToUInt64Checked(); } /// <summary>Converts this number's value to an integer by discarding /// its fractional part, and returns the least-significant bits of its /// two's-complement form as a 64-bit unsigned integer.</summary> /// <returns>This number, converted to a 64-bit unsigned integer. /// Returns 0 if this value is infinity or not-a-number.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ulong ToUInt64Unchecked() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.IsFinite() ? this.ToEInteger().ToUInt64Unchecked() : 0UL; } /// <summary>Converts this number's value to a 64-bit unsigned integer /// if it can fit in a 64-bit unsigned integer without rounding to a /// different numerical value.</summary> /// <returns>This number's value as a 64-bit unsigned /// integer.</returns> /// <exception cref='ArithmeticException'>This value is infinity or /// not-a-number, is not an exact integer, or is less than 0 or greater /// than 18446744073709551615.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ulong ToUInt64IfExact() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (!this.IsFinite()) { throw new OverflowException("Value is infinity or NaN"); } if (this.IsZero()) { return 0UL; } if (this.IsNegative()) { throw new OverflowException("Value out of range"); } return this.ToEIntegerIfExact().ToUInt64Checked(); } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.IO; using System.Text; using log4net; using MindTouch.Dream.Test; using MindTouch.Tasking; using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Dream.Storage.Test { using Yield = IEnumerator<IYield>; [TestFixture] public class PrivateStorageTests { //--- Constants --- private const string TEST_PATH = "private-storage-proxy"; //--- Class Fields --- private static readonly ILog _log = LogUtils.CreateLog(); //--- Fields --- private Plug testService; private DreamHostInfo _hostInfo; private string _folder; private string _storageFolder; [TestFixtureSetUp] public void Init() { _folder = Path.GetTempPath(); Directory.CreateDirectory(_folder); _storageFolder = Path.Combine(Path.GetTempPath(), StringUtil.CreateAlphaNumericKey(6)); Directory.CreateDirectory(_storageFolder); XDoc config = new XDoc("config").Elem("service-dir", _folder); _hostInfo = DreamTestHelper.CreateRandomPortHost(config); CreatePrivateStorageServiceProxy(); } [TearDown] public void DeinitTest() { System.GC.Collect(); } [TestFixtureTearDown] public void TearDown() { _hostInfo.Dispose(); Directory.Delete(_storageFolder, true); } [Test] public void Can_init() { } [Test] public void Can_create_two_services_with_private_storage() { _log.Debug("start test"); CreateSecondPrivateStorageServiceProxy(); } [Test] public void Service_can_store_and_retrieve_file() { DreamMessage response = testService.AtPath("create-retrieve-delete").Post(new Result<DreamMessage>()).Wait(); Assert.IsTrue(response.IsSuccessful, response.ToText()); } [Test] public void Service_can_store_and_retrieve_head() { DreamMessage response = testService.AtPath("create-retrievehead-delete").Post(new Result<DreamMessage>()).Wait(); Assert.IsTrue(response.IsSuccessful, response.ToText()); } [Test] public void Service_storage_will_expire_file() { DreamMessage response = testService.AtPath("create-expire").Post(new Result<DreamMessage>()).Wait(); Assert.IsTrue(response.IsSuccessful, response.ToText()); } private void CreatePrivateStorageServiceProxy() { _hostInfo.Host.Self.At("load").With("name", "test.mindtouch.storage").Post(DreamMessage.Ok()); _hostInfo.Host.Self.At("services").Post( new XDoc("config") .Elem("class", typeof(TestServiceWithPrivateStorage).FullName) .Elem("path", TEST_PATH)); testService = Plug.New(_hostInfo.Host.LocalMachineUri).At(TEST_PATH); } private void CreateSecondPrivateStorageServiceProxy() { _hostInfo.Host.Self.At("services").Post( new XDoc("config") .Elem("class", typeof(TestServiceWithPrivateStorage).FullName) .Elem("path", TEST_PATH + "2")); _log.Debug("created second storage service"); testService = Plug.New(_hostInfo.Host.LocalMachineUri).At(TEST_PATH + "2"); } } [DreamService("TestServiceWithPrivateStorage", "Copyright (c) 2008 MindTouch, Inc.", Info = "", SID = new[] { "sid://mindtouch.com/TestServiceWithPrivateStorage" } )] [DreamServiceBlueprint("setup/private-storage")] public class TestServiceWithPrivateStorage : DreamService { //--- Constants --- private const string TEST_CONTENTS = "Sample content"; private const string TEST_FILE_URI = "testfile"; //--- Class Fields --- private static readonly ILog _log = LogUtils.CreateLog(); [DreamFeature("POST:create-retrieve-delete", "Create and retrieve test")] public Yield TestCreateRetrieveDelete(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string filename = Path.GetTempFileName(); using(Stream s = File.OpenWrite(filename)) { byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS); s.Write(data, 0, data.Length); } _log.Debug("created file"); // add a file Storage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false)); File.Delete(filename); _log.Debug("put file"); // get file and compare contents string contents = Storage.AtPath(TEST_FILE_URI).Get().ToText(); Assert.AreEqual(TEST_CONTENTS, contents); _log.Debug("got file"); // delete file Storage.AtPath(TEST_FILE_URI).Delete(); _log.Debug("deleted file"); response.Return(DreamMessage.Ok()); yield break; } [DreamFeature("POST:create-retrievehead-delete", "Create and retrieve head test")] public Yield TestCreateRetrieveHeadDelete(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string filename = Path.GetTempFileName(); using(Stream s = File.OpenWrite(filename)) { byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS); s.Write(data, 0, data.Length); } _log.Debug("created file"); // add a file Storage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false)); File.Delete(filename); _log.Debug("put file"); // get file and compare contents DreamMessage headResponse = Storage.AtPath(TEST_FILE_URI).Invoke(Verb.HEAD, DreamMessage.Ok()); Assert.AreEqual(TEST_CONTENTS.Length, headResponse.ContentLength); _log.Debug("got content length"); // delete file Storage.AtPath(TEST_FILE_URI).Delete(); _log.Debug("deleted file"); response.Return(DreamMessage.Ok()); yield break; } [DreamFeature("POST:create-expire", "Create and expire test")] public Yield TestCreateTtlExpire(DreamContext context, DreamMessage request, Result<DreamMessage> response) { // add a file Storage.AtPath(TEST_FILE_URI).With("ttl", "2").Put(DreamMessage.Ok(MimeType.TEXT, TEST_CONTENTS)); _log.DebugFormat("File stored at: {0}", GlobalClock.UtcNow); // get file and compare contents string contents = Storage.AtPath(TEST_FILE_URI).Get().ToText(); Assert.AreEqual(TEST_CONTENTS, contents); _log.DebugFormat("check file at: {0}", GlobalClock.UtcNow); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4)); // get file and compare contents _log.DebugFormat("Checking for expired file at: {0}", GlobalClock.UtcNow); DreamMessage getResponse = Storage.AtPath(TEST_FILE_URI).Get(new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.NotFound, getResponse.Status); response.Return(DreamMessage.Ok()); yield break; } protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); result.Return(); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An elementary school. /// </summary> public class ElementarySchool_Core : TypeCore, IEducationalOrganization { public ElementarySchool_Core() { this._TypeId = 91; this._Id = "ElementarySchool"; this._Schema_Org_Url = "http://schema.org/ElementarySchool"; string label = ""; GetLabel(out label, "ElementarySchool", typeof(ElementarySchool_Core)); this._Label = label; this._Ancestors = new int[]{266,193,88}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{88}; this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196,13}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// Alumni of educational organization. /// </summary> private Alumni_Core alumni; public Alumni_Core Alumni { get { return alumni; } set { alumni = value; SetPropertyInstance(alumni); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System.Collections.Generic; namespace Avalonia.Media.TextFormatting.Unicode { internal static class PropertyValueAliasHelper { private static readonly Dictionary<Script, string> s_scriptToTag = new Dictionary<Script, string>{ { Script.Unknown, "Zzzz"}, { Script.Common, "Zyyy"}, { Script.Inherited, "Zinh"}, { Script.Adlam, "Adlm"}, { Script.CaucasianAlbanian, "Aghb"}, { Script.Ahom, "Ahom"}, { Script.Arabic, "Arab"}, { Script.ImperialAramaic, "Armi"}, { Script.Armenian, "Armn"}, { Script.Avestan, "Avst"}, { Script.Balinese, "Bali"}, { Script.Bamum, "Bamu"}, { Script.BassaVah, "Bass"}, { Script.Batak, "Batk"}, { Script.Bengali, "Beng"}, { Script.Bhaiksuki, "Bhks"}, { Script.Bopomofo, "Bopo"}, { Script.Brahmi, "Brah"}, { Script.Braille, "Brai"}, { Script.Buginese, "Bugi"}, { Script.Buhid, "Buhd"}, { Script.Chakma, "Cakm"}, { Script.CanadianAboriginal, "Cans"}, { Script.Carian, "Cari"}, { Script.Cham, "Cham"}, { Script.Cherokee, "Cher"}, { Script.Chorasmian, "Chrs"}, { Script.Coptic, "Copt"}, { Script.Cypriot, "Cprt"}, { Script.Cyrillic, "Cyrl"}, { Script.Devanagari, "Deva"}, { Script.DivesAkuru, "Diak"}, { Script.Dogra, "Dogr"}, { Script.Deseret, "Dsrt"}, { Script.Duployan, "Dupl"}, { Script.EgyptianHieroglyphs, "Egyp"}, { Script.Elbasan, "Elba"}, { Script.Elymaic, "Elym"}, { Script.Ethiopic, "Ethi"}, { Script.Georgian, "Geor"}, { Script.Glagolitic, "Glag"}, { Script.GunjalaGondi, "Gong"}, { Script.MasaramGondi, "Gonm"}, { Script.Gothic, "Goth"}, { Script.Grantha, "Gran"}, { Script.Greek, "Grek"}, { Script.Gujarati, "Gujr"}, { Script.Gurmukhi, "Guru"}, { Script.Hangul, "Hang"}, { Script.Han, "Hani"}, { Script.Hanunoo, "Hano"}, { Script.Hatran, "Hatr"}, { Script.Hebrew, "Hebr"}, { Script.Hiragana, "Hira"}, { Script.AnatolianHieroglyphs, "Hluw"}, { Script.PahawhHmong, "Hmng"}, { Script.NyiakengPuachueHmong, "Hmnp"}, { Script.KatakanaOrHiragana, "Hrkt"}, { Script.OldHungarian, "Hung"}, { Script.OldItalic, "Ital"}, { Script.Javanese, "Java"}, { Script.KayahLi, "Kali"}, { Script.Katakana, "Kana"}, { Script.Kharoshthi, "Khar"}, { Script.Khmer, "Khmr"}, { Script.Khojki, "Khoj"}, { Script.KhitanSmallScript, "Kits"}, { Script.Kannada, "Knda"}, { Script.Kaithi, "Kthi"}, { Script.TaiTham, "Lana"}, { Script.Lao, "Laoo"}, { Script.Latin, "Latn"}, { Script.Lepcha, "Lepc"}, { Script.Limbu, "Limb"}, { Script.LinearA, "Lina"}, { Script.LinearB, "Linb"}, { Script.Lisu, "Lisu"}, { Script.Lycian, "Lyci"}, { Script.Lydian, "Lydi"}, { Script.Mahajani, "Mahj"}, { Script.Makasar, "Maka"}, { Script.Mandaic, "Mand"}, { Script.Manichaean, "Mani"}, { Script.Marchen, "Marc"}, { Script.Medefaidrin, "Medf"}, { Script.MendeKikakui, "Mend"}, { Script.MeroiticCursive, "Merc"}, { Script.MeroiticHieroglyphs, "Mero"}, { Script.Malayalam, "Mlym"}, { Script.Modi, "Modi"}, { Script.Mongolian, "Mong"}, { Script.Mro, "Mroo"}, { Script.MeeteiMayek, "Mtei"}, { Script.Multani, "Mult"}, { Script.Myanmar, "Mymr"}, { Script.Nandinagari, "Nand"}, { Script.OldNorthArabian, "Narb"}, { Script.Nabataean, "Nbat"}, { Script.Newa, "Newa"}, { Script.Nko, "Nkoo"}, { Script.Nushu, "Nshu"}, { Script.Ogham, "Ogam"}, { Script.OlChiki, "Olck"}, { Script.OldTurkic, "Orkh"}, { Script.Oriya, "Orya"}, { Script.Osage, "Osge"}, { Script.Osmanya, "Osma"}, { Script.Palmyrene, "Palm"}, { Script.PauCinHau, "Pauc"}, { Script.OldPermic, "Perm"}, { Script.PhagsPa, "Phag"}, { Script.InscriptionalPahlavi, "Phli"}, { Script.PsalterPahlavi, "Phlp"}, { Script.Phoenician, "Phnx"}, { Script.Miao, "Plrd"}, { Script.InscriptionalParthian, "Prti"}, { Script.Rejang, "Rjng"}, { Script.HanifiRohingya, "Rohg"}, { Script.Runic, "Runr"}, { Script.Samaritan, "Samr"}, { Script.OldSouthArabian, "Sarb"}, { Script.Saurashtra, "Saur"}, { Script.SignWriting, "Sgnw"}, { Script.Shavian, "Shaw"}, { Script.Sharada, "Shrd"}, { Script.Siddham, "Sidd"}, { Script.Khudawadi, "Sind"}, { Script.Sinhala, "Sinh"}, { Script.Sogdian, "Sogd"}, { Script.OldSogdian, "Sogo"}, { Script.SoraSompeng, "Sora"}, { Script.Soyombo, "Soyo"}, { Script.Sundanese, "Sund"}, { Script.SylotiNagri, "Sylo"}, { Script.Syriac, "Syrc"}, { Script.Tagbanwa, "Tagb"}, { Script.Takri, "Takr"}, { Script.TaiLe, "Tale"}, { Script.NewTaiLue, "Talu"}, { Script.Tamil, "Taml"}, { Script.Tangut, "Tang"}, { Script.TaiViet, "Tavt"}, { Script.Telugu, "Telu"}, { Script.Tifinagh, "Tfng"}, { Script.Tagalog, "Tglg"}, { Script.Thaana, "Thaa"}, { Script.Thai, "Thai"}, { Script.Tibetan, "Tibt"}, { Script.Tirhuta, "Tirh"}, { Script.Ugaritic, "Ugar"}, { Script.Vai, "Vaii"}, { Script.WarangCiti, "Wara"}, { Script.Wancho, "Wcho"}, { Script.OldPersian, "Xpeo"}, { Script.Cuneiform, "Xsux"}, { Script.Yezidi, "Yezi"}, { Script.Yi, "Yiii"}, { Script.ZanabazarSquare, "Zanb"}, }; public static string GetTag(Script script) { if(!s_scriptToTag.ContainsKey(script)) { return "Zzzz"; } return s_scriptToTag[script]; } private static readonly Dictionary<string, Script> s_tagToScript = new Dictionary<string,Script>{ { "Zzzz", Script.Unknown}, { "Zyyy", Script.Common}, { "Zinh", Script.Inherited}, { "Adlm", Script.Adlam}, { "Aghb", Script.CaucasianAlbanian}, { "Ahom", Script.Ahom}, { "Arab", Script.Arabic}, { "Armi", Script.ImperialAramaic}, { "Armn", Script.Armenian}, { "Avst", Script.Avestan}, { "Bali", Script.Balinese}, { "Bamu", Script.Bamum}, { "Bass", Script.BassaVah}, { "Batk", Script.Batak}, { "Beng", Script.Bengali}, { "Bhks", Script.Bhaiksuki}, { "Bopo", Script.Bopomofo}, { "Brah", Script.Brahmi}, { "Brai", Script.Braille}, { "Bugi", Script.Buginese}, { "Buhd", Script.Buhid}, { "Cakm", Script.Chakma}, { "Cans", Script.CanadianAboriginal}, { "Cari", Script.Carian}, { "Cham", Script.Cham}, { "Cher", Script.Cherokee}, { "Chrs", Script.Chorasmian}, { "Copt", Script.Coptic}, { "Cprt", Script.Cypriot}, { "Cyrl", Script.Cyrillic}, { "Deva", Script.Devanagari}, { "Diak", Script.DivesAkuru}, { "Dogr", Script.Dogra}, { "Dsrt", Script.Deseret}, { "Dupl", Script.Duployan}, { "Egyp", Script.EgyptianHieroglyphs}, { "Elba", Script.Elbasan}, { "Elym", Script.Elymaic}, { "Ethi", Script.Ethiopic}, { "Geor", Script.Georgian}, { "Glag", Script.Glagolitic}, { "Gong", Script.GunjalaGondi}, { "Gonm", Script.MasaramGondi}, { "Goth", Script.Gothic}, { "Gran", Script.Grantha}, { "Grek", Script.Greek}, { "Gujr", Script.Gujarati}, { "Guru", Script.Gurmukhi}, { "Hang", Script.Hangul}, { "Hani", Script.Han}, { "Hano", Script.Hanunoo}, { "Hatr", Script.Hatran}, { "Hebr", Script.Hebrew}, { "Hira", Script.Hiragana}, { "Hluw", Script.AnatolianHieroglyphs}, { "Hmng", Script.PahawhHmong}, { "Hmnp", Script.NyiakengPuachueHmong}, { "Hrkt", Script.KatakanaOrHiragana}, { "Hung", Script.OldHungarian}, { "Ital", Script.OldItalic}, { "Java", Script.Javanese}, { "Kali", Script.KayahLi}, { "Kana", Script.Katakana}, { "Khar", Script.Kharoshthi}, { "Khmr", Script.Khmer}, { "Khoj", Script.Khojki}, { "Kits", Script.KhitanSmallScript}, { "Knda", Script.Kannada}, { "Kthi", Script.Kaithi}, { "Lana", Script.TaiTham}, { "Laoo", Script.Lao}, { "Latn", Script.Latin}, { "Lepc", Script.Lepcha}, { "Limb", Script.Limbu}, { "Lina", Script.LinearA}, { "Linb", Script.LinearB}, { "Lisu", Script.Lisu}, { "Lyci", Script.Lycian}, { "Lydi", Script.Lydian}, { "Mahj", Script.Mahajani}, { "Maka", Script.Makasar}, { "Mand", Script.Mandaic}, { "Mani", Script.Manichaean}, { "Marc", Script.Marchen}, { "Medf", Script.Medefaidrin}, { "Mend", Script.MendeKikakui}, { "Merc", Script.MeroiticCursive}, { "Mero", Script.MeroiticHieroglyphs}, { "Mlym", Script.Malayalam}, { "Modi", Script.Modi}, { "Mong", Script.Mongolian}, { "Mroo", Script.Mro}, { "Mtei", Script.MeeteiMayek}, { "Mult", Script.Multani}, { "Mymr", Script.Myanmar}, { "Nand", Script.Nandinagari}, { "Narb", Script.OldNorthArabian}, { "Nbat", Script.Nabataean}, { "Newa", Script.Newa}, { "Nkoo", Script.Nko}, { "Nshu", Script.Nushu}, { "Ogam", Script.Ogham}, { "Olck", Script.OlChiki}, { "Orkh", Script.OldTurkic}, { "Orya", Script.Oriya}, { "Osge", Script.Osage}, { "Osma", Script.Osmanya}, { "Palm", Script.Palmyrene}, { "Pauc", Script.PauCinHau}, { "Perm", Script.OldPermic}, { "Phag", Script.PhagsPa}, { "Phli", Script.InscriptionalPahlavi}, { "Phlp", Script.PsalterPahlavi}, { "Phnx", Script.Phoenician}, { "Plrd", Script.Miao}, { "Prti", Script.InscriptionalParthian}, { "Rjng", Script.Rejang}, { "Rohg", Script.HanifiRohingya}, { "Runr", Script.Runic}, { "Samr", Script.Samaritan}, { "Sarb", Script.OldSouthArabian}, { "Saur", Script.Saurashtra}, { "Sgnw", Script.SignWriting}, { "Shaw", Script.Shavian}, { "Shrd", Script.Sharada}, { "Sidd", Script.Siddham}, { "Sind", Script.Khudawadi}, { "Sinh", Script.Sinhala}, { "Sogd", Script.Sogdian}, { "Sogo", Script.OldSogdian}, { "Sora", Script.SoraSompeng}, { "Soyo", Script.Soyombo}, { "Sund", Script.Sundanese}, { "Sylo", Script.SylotiNagri}, { "Syrc", Script.Syriac}, { "Tagb", Script.Tagbanwa}, { "Takr", Script.Takri}, { "Tale", Script.TaiLe}, { "Talu", Script.NewTaiLue}, { "Taml", Script.Tamil}, { "Tang", Script.Tangut}, { "Tavt", Script.TaiViet}, { "Telu", Script.Telugu}, { "Tfng", Script.Tifinagh}, { "Tglg", Script.Tagalog}, { "Thaa", Script.Thaana}, { "Thai", Script.Thai}, { "Tibt", Script.Tibetan}, { "Tirh", Script.Tirhuta}, { "Ugar", Script.Ugaritic}, { "Vaii", Script.Vai}, { "Wara", Script.WarangCiti}, { "Wcho", Script.Wancho}, { "Xpeo", Script.OldPersian}, { "Xsux", Script.Cuneiform}, { "Yezi", Script.Yezidi}, { "Yiii", Script.Yi}, { "Zanb", Script.ZanabazarSquare}, }; public static Script GetScript(string tag) { if(!s_tagToScript.ContainsKey(tag)) { return Script.Unknown; } return s_tagToScript[tag]; } private static readonly Dictionary<string, GeneralCategory> s_tagToGeneralCategory = new Dictionary<string,GeneralCategory>{ { "C", GeneralCategory.Other}, { "Cc", GeneralCategory.Control}, { "Cf", GeneralCategory.Format}, { "Cn", GeneralCategory.Unassigned}, { "Co", GeneralCategory.PrivateUse}, { "Cs", GeneralCategory.Surrogate}, { "L", GeneralCategory.Letter}, { "LC", GeneralCategory.CasedLetter}, { "Ll", GeneralCategory.LowercaseLetter}, { "Lm", GeneralCategory.ModifierLetter}, { "Lo", GeneralCategory.OtherLetter}, { "Lt", GeneralCategory.TitlecaseLetter}, { "Lu", GeneralCategory.UppercaseLetter}, { "M", GeneralCategory.Mark}, { "Mc", GeneralCategory.SpacingMark}, { "Me", GeneralCategory.EnclosingMark}, { "Mn", GeneralCategory.NonspacingMark}, { "N", GeneralCategory.Number}, { "Nd", GeneralCategory.DecimalNumber}, { "Nl", GeneralCategory.LetterNumber}, { "No", GeneralCategory.OtherNumber}, { "P", GeneralCategory.Punctuation}, { "Pc", GeneralCategory.ConnectorPunctuation}, { "Pd", GeneralCategory.DashPunctuation}, { "Pe", GeneralCategory.ClosePunctuation}, { "Pf", GeneralCategory.FinalPunctuation}, { "Pi", GeneralCategory.InitialPunctuation}, { "Po", GeneralCategory.OtherPunctuation}, { "Ps", GeneralCategory.OpenPunctuation}, { "S", GeneralCategory.Symbol}, { "Sc", GeneralCategory.CurrencySymbol}, { "Sk", GeneralCategory.ModifierSymbol}, { "Sm", GeneralCategory.MathSymbol}, { "So", GeneralCategory.OtherSymbol}, { "Z", GeneralCategory.Separator}, { "Zl", GeneralCategory.LineSeparator}, { "Zp", GeneralCategory.ParagraphSeparator}, { "Zs", GeneralCategory.SpaceSeparator}, }; public static GeneralCategory GetGeneralCategory(string tag) { if(!s_tagToGeneralCategory.ContainsKey(tag)) { return GeneralCategory.Other; } return s_tagToGeneralCategory[tag]; } private static readonly Dictionary<string, LineBreakClass> s_tagToLineBreakClass = new Dictionary<string,LineBreakClass>{ { "OP", LineBreakClass.OpenPunctuation}, { "CL", LineBreakClass.ClosePunctuation}, { "CP", LineBreakClass.CloseParenthesis}, { "QU", LineBreakClass.Quotation}, { "GL", LineBreakClass.Glue}, { "NS", LineBreakClass.Nonstarter}, { "EX", LineBreakClass.Exclamation}, { "SY", LineBreakClass.BreakSymbols}, { "IS", LineBreakClass.InfixNumeric}, { "PR", LineBreakClass.PrefixNumeric}, { "PO", LineBreakClass.PostfixNumeric}, { "NU", LineBreakClass.Numeric}, { "AL", LineBreakClass.Alphabetic}, { "HL", LineBreakClass.HebrewLetter}, { "ID", LineBreakClass.Ideographic}, { "IN", LineBreakClass.Inseparable}, { "HY", LineBreakClass.Hyphen}, { "BA", LineBreakClass.BreakAfter}, { "BB", LineBreakClass.BreakBefore}, { "B2", LineBreakClass.BreakBoth}, { "ZW", LineBreakClass.ZWSpace}, { "CM", LineBreakClass.CombiningMark}, { "WJ", LineBreakClass.WordJoiner}, { "H2", LineBreakClass.H2}, { "H3", LineBreakClass.H3}, { "JL", LineBreakClass.JL}, { "JV", LineBreakClass.JV}, { "JT", LineBreakClass.JT}, { "RI", LineBreakClass.RegionalIndicator}, { "EB", LineBreakClass.EBase}, { "EM", LineBreakClass.EModifier}, { "ZWJ", LineBreakClass.ZWJ}, { "CB", LineBreakClass.ContingentBreak}, { "XX", LineBreakClass.Unknown}, { "AI", LineBreakClass.Ambiguous}, { "BK", LineBreakClass.MandatoryBreak}, { "CJ", LineBreakClass.ConditionalJapaneseStarter}, { "CR", LineBreakClass.CarriageReturn}, { "LF", LineBreakClass.LineFeed}, { "NL", LineBreakClass.NextLine}, { "SA", LineBreakClass.ComplexContext}, { "SG", LineBreakClass.Surrogate}, { "SP", LineBreakClass.Space}, }; public static LineBreakClass GetLineBreakClass(string tag) { if(!s_tagToLineBreakClass.ContainsKey(tag)) { return LineBreakClass.Unknown; } return s_tagToLineBreakClass[tag]; } private static readonly Dictionary<string, BidiPairedBracketType> s_tagToBiDiPairedBracketType = new Dictionary<string,BidiPairedBracketType>{ { "n", BidiPairedBracketType.None}, { "c", BidiPairedBracketType.Close}, { "o", BidiPairedBracketType.Open}, }; public static BidiPairedBracketType GetBiDiPairedBracketType(string tag) { if(!s_tagToBiDiPairedBracketType.ContainsKey(tag)) { return BidiPairedBracketType.None; } return s_tagToBiDiPairedBracketType[tag]; } private static readonly Dictionary<string, BidiClass> s_tagToBiDiClass = new Dictionary<string,BidiClass>{ { "L", BidiClass.LeftToRight}, { "AL", BidiClass.ArabicLetter}, { "AN", BidiClass.ArabicNumber}, { "B", BidiClass.ParagraphSeparator}, { "BN", BidiClass.BoundaryNeutral}, { "CS", BidiClass.CommonSeparator}, { "EN", BidiClass.EuropeanNumber}, { "ES", BidiClass.EuropeanSeparator}, { "ET", BidiClass.EuropeanTerminator}, { "FSI", BidiClass.FirstStrongIsolate}, { "LRE", BidiClass.LeftToRightEmbedding}, { "LRI", BidiClass.LeftToRightIsolate}, { "LRO", BidiClass.LeftToRightOverride}, { "NSM", BidiClass.NonspacingMark}, { "ON", BidiClass.OtherNeutral}, { "PDF", BidiClass.PopDirectionalFormat}, { "PDI", BidiClass.PopDirectionalIsolate}, { "R", BidiClass.RightToLeft}, { "RLE", BidiClass.RightToLeftEmbedding}, { "RLI", BidiClass.RightToLeftIsolate}, { "RLO", BidiClass.RightToLeftOverride}, { "S", BidiClass.SegmentSeparator}, { "WS", BidiClass.WhiteSpace}, }; public static BidiClass GetBiDiClass(string tag) { if(!s_tagToBiDiClass.ContainsKey(tag)) { return BidiClass.LeftToRight; } return s_tagToBiDiClass[tag]; } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the CandidateLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in CandidateLogicBase by making a partial class of CandidateLogic // and overriding the base methods. namespace VotingInfo.Database.Logic.Data { public partial class CandidateLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run Candidate_Insert. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> public static int? InsertNow(int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName ) { return (new CandidateLogic()).Insert(fldUserId , fldContentInspectionId , fldLocationId , fldOrganizationId , fldCandidateName ); } /// <summary> /// Run Candidate_Insert. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Insert(fldUserId , fldContentInspectionId , fldLocationId , fldOrganizationId , fldCandidateName , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(CandidateContract row) { return (new CandidateLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<CandidateContract> rows) { return (new CandidateLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run Candidate_Update. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldCandidateId , int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName ) { return (new CandidateLogic()).Update(fldCandidateId , fldUserId , fldContentInspectionId , fldLocationId , fldOrganizationId , fldCandidateName ); } /// <summary> /// Run Candidate_Update. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldCandidateId , int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Update(fldCandidateId , fldUserId , fldContentInspectionId , fldLocationId , fldOrganizationId , fldCandidateName , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(CandidateContract row) { return (new CandidateLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<CandidateContract> rows) { return (new CandidateLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run Candidate_Delete. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldCandidateId ) { return (new CandidateLogic()).Delete(fldCandidateId ); } /// <summary> /// Run Candidate_Delete. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Delete(fldCandidateId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(CandidateContract row) { return (new CandidateLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<CandidateContract> rows) { return (new CandidateLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateId ) { return (new CandidateLogic()).Exists(fldCandidateId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).Exists(fldCandidateId , connection, transaction); } /// <summary> /// Run Candidate_Search, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SearchNow(string fldCandidateName ) { var driver = new CandidateLogic(); driver.Search(fldCandidateName ); return driver.Results; } /// <summary> /// Run Candidate_Search, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SearchNow(string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.Search(fldCandidateName , connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_SelectAll, and return results as a list of CandidateRow. /// </summary> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectAllNow() { var driver = new CandidateLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run Candidate_SelectAll, and return results as a list of CandidateRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_List, and return results as a list. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldCandidateName ) { return (new CandidateLogic()).List(fldCandidateName ); } /// <summary> /// Run Candidate_List, and return results as a list. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).List(fldCandidateName , connection, transaction); } /// <summary> /// Run Candidate_SelectBy_CandidateId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_CandidateIdNow(int fldCandidateId ) { var driver = new CandidateLogic(); driver.SelectBy_CandidateId(fldCandidateId ); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_CandidateId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_CandidateIdNow(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectBy_CandidateId(fldCandidateId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_UserId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_UserIdNow(int fldUserId ) { var driver = new CandidateLogic(); driver.SelectBy_UserId(fldUserId ); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_UserId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_UserIdNow(int fldUserId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectBy_UserId(fldUserId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_ContentInspectionId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId ) { var driver = new CandidateLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId ); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_ContentInspectionId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectBy_ContentInspectionId(fldContentInspectionId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_LocationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_LocationIdNow(int fldLocationId ) { var driver = new CandidateLogic(); driver.SelectBy_LocationId(fldLocationId ); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_LocationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_LocationIdNow(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectBy_LocationId(fldLocationId , connection, transaction); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_OrganizationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_OrganizationIdNow(int fldOrganizationId ) { var driver = new CandidateLogic(); driver.SelectBy_OrganizationId(fldOrganizationId ); return driver.Results; } /// <summary> /// Run Candidate_SelectBy_OrganizationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public static List<CandidateContract> SelectBy_OrganizationIdNow(int fldOrganizationId , SqlConnection connection, SqlTransaction transaction) { var driver = new CandidateLogic(); driver.SelectBy_OrganizationId(fldOrganizationId , connection, transaction); return driver.Results; } /// <summary> /// Read all Candidate rows from the provided reader into the list structure of CandidateRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated CandidateRows or an empty CandidateRows if there are no results.</returns> public static List<CandidateContract> ReadAllNow(SqlDataReader reader) { var driver = new CandidateLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a Candidate /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A Candidate or null if there are no results.</returns> public static CandidateContract ReadOneNow(SqlDataReader reader) { var driver = new CandidateLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(CandidateContract row) { if(row.CandidateId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { if(row.CandidateId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<CandidateContract> rows) { return (new CandidateLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new CandidateLogic()).SaveAll(rows, connection, transaction); } } }
// --------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; namespace Yodo1APICaller.UserControls { class ContosoListView : ListView { // For context menu handling. private bool _isShiftPressed = false; private bool _isPointerPressed = false; // This API check has a small cost, so just do it once and save the result. private bool _isContextFlyoutAPIPresent = false; public MenuFlyout ContextMenu { get { return (MenuFlyout)GetValue(ContextMenuProperty); } set { SetValue(ContextMenuProperty, value); } } /// <summary> /// Property for the backing store for ContextMenu. This enables animation, styling, binging, etc. /// </summary> public static readonly DependencyProperty ContextMenuProperty = DependencyProperty.Register("ContextMenu", typeof(MenuFlyout), typeof(ContosoListView), new PropertyMetadata(null)); public ContosoListView() { } /// <summary> /// Builds a visual template for the list view. /// </summary> protected override void OnApplyTemplate() { if (_isContextFlyoutAPIPresent == true && ContextMenu != null) { ContextMenu.Opened += (s, e) => { (ContextMenu.Target as ListViewItem).DataContext = (ContextMenu.Target as ListViewItem).Content; }; var listViewItemStyle = new Style(); listViewItemStyle.TargetType = typeof(ListViewItem); listViewItemStyle.Setters.Add(new Setter(ContextFlyoutProperty, ContextMenu)); ItemContainerStyle = listViewItemStyle; } base.OnApplyTemplate(); } #region Handlers for down-level systems /// <summary> /// Handles key down keyboard control for the context menu. /// </summary> protected override void OnKeyDown(KeyRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { // Handle Shift+F10 and the Menu key. if (e.Key == Windows.System.VirtualKey.Shift) { _isShiftPressed = true; } // Shift+F10 // The 'Menu' key next to Right Ctrl on most keyboards else if ((_isShiftPressed && e.Key == Windows.System.VirtualKey.F10) || e.Key == Windows.System.VirtualKey.Application) { var focusedElement = FocusManager.GetFocusedElement() as UIElement; ShowContextMenu(focusedElement, new Point(0, 0)); e.Handled = true; } } base.OnKeyDown(e); } /// <summary> /// Handles key up keyboard control for the context menu. /// </summary> protected override void OnKeyUp(KeyRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { if (e.Key == Windows.System.VirtualKey.Shift) { _isShiftPressed = false; } } base.OnKeyUp(e); } /// <summary> /// Handles key holding control for the context menu. /// </summary> /// <param name="e"></param> protected override void OnHolding(HoldingRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { // Responding to HoldingState.Started will show a context menu while your finger is still down, while // HoldingState.Completed will wait until you have removed your finger. if (e.HoldingState == Windows.UI.Input.HoldingState.Completed) { ListViewItem container = null; // Find the ListViewItem that is pressed. Also cancel direct manipulations on it to // prevent any scrollviewers from continuing to pan once the context menu is displayed. var pressedElements = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), this); foreach (var element in pressedElements) { if (element is ListViewItem) { element.CancelDirectManipulations(); container = element as ListViewItem; } } if (container != null) { ShowContextMenu(container, e.GetPosition(container)); } e.Handled = true; // This, combined with a check in OnRightTapped prevents the firing of RightTapped from // launching another context menu. _isPointerPressed = false; } } base.OnHolding(e); } /// <summary> /// Handles pointer control for the context menu. /// </summary> protected override void OnPointerPressed(PointerRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { _isPointerPressed = true; } base.OnPointerPressed(e); } /// <summary> /// Handles right click pointer control for the context menu /// </summary> protected override void OnRightTapped(RightTappedRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { if (_isPointerPressed) { var focusedElement = FocusManager.GetFocusedElement() as ListViewItem; if (focusedElement != null) { ShowContextMenu(focusedElement, e.GetPosition(focusedElement)); } e.Handled = true; } } base.OnRightTapped(e); } /// <summary> /// Shows the context menu when called. /// </summary> private void ShowContextMenu(UIElement target, Point offset) { if (ContextMenu != null) { if (target is ContentControl) { (target as ContentControl).DataContext = (target as ContentControl).Content; } ContextMenu.ShowAt(target, offset); } } #endregion } }
// <copyright file="TraceContextPropagator.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using OpenTelemetry.Internal; namespace OpenTelemetry.Context.Propagation { /// <summary> /// A text map propagator for W3C trace context. See https://w3c.github.io/trace-context/. /// </summary> public class TraceContextPropagator : TextMapPropagator { private const string TraceParent = "traceparent"; private const string TraceState = "tracestate"; private static readonly int VersionPrefixIdLength = "00-".Length; private static readonly int TraceIdLength = "0af7651916cd43dd8448eb211c80319c".Length; private static readonly int VersionAndTraceIdLength = "00-0af7651916cd43dd8448eb211c80319c-".Length; private static readonly int SpanIdLength = "00f067aa0ba902b7".Length; private static readonly int VersionAndTraceIdAndSpanIdLength = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-".Length; private static readonly int OptionsLength = "00".Length; private static readonly int TraceparentLengthV0 = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-00".Length; // The following length limits are from Trace Context v1 https://www.w3.org/TR/trace-context-1/#key private static readonly int TraceStateKeyMaxLength = 256; private static readonly int TraceStateKeyTenantMaxLength = 241; private static readonly int TraceStateKeyVendorMaxLength = 14; private static readonly int TraceStateValueMaxLength = 256; /// <inheritdoc/> public override ISet<string> Fields => new HashSet<string> { TraceState, TraceParent }; /// <inheritdoc/> public override PropagationContext Extract<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter) { if (context.ActivityContext.IsValid()) { // If a valid context has already been extracted, perform a noop. return context; } if (carrier == null) { OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(TraceContextPropagator), "null carrier"); return context; } if (getter == null) { OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(TraceContextPropagator), "null getter"); return context; } try { var traceparentCollection = getter(carrier, TraceParent); // There must be a single traceparent if (traceparentCollection == null || traceparentCollection.Count() != 1) { return context; } var traceparent = traceparentCollection.First(); var traceparentParsed = TryExtractTraceparent(traceparent, out var traceId, out var spanId, out var traceoptions); if (!traceparentParsed) { return context; } string tracestate = null; var tracestateCollection = getter(carrier, TraceState); if (tracestateCollection?.Any() ?? false) { TryExtractTracestate(tracestateCollection.ToArray(), out tracestate); } return new PropagationContext( new ActivityContext(traceId, spanId, traceoptions, tracestate, isRemote: true), context.Baggage); } catch (Exception ex) { OpenTelemetryApiEventSource.Log.ActivityContextExtractException(nameof(TraceContextPropagator), ex); } // in case of exception indicate to upstream that there is no parseable context from the top return context; } /// <inheritdoc/> public override void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter) { if (context.ActivityContext.TraceId == default || context.ActivityContext.SpanId == default) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TraceContextPropagator), "Invalid context"); return; } if (carrier == null) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TraceContextPropagator), "null carrier"); return; } if (setter == null) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(TraceContextPropagator), "null setter"); return; } var traceparent = string.Concat("00-", context.ActivityContext.TraceId.ToHexString(), "-", context.ActivityContext.SpanId.ToHexString()); traceparent = string.Concat(traceparent, (context.ActivityContext.TraceFlags & ActivityTraceFlags.Recorded) != 0 ? "-01" : "-00"); setter(carrier, TraceParent, traceparent); string tracestateStr = context.ActivityContext.TraceState; if (tracestateStr?.Length > 0) { setter(carrier, TraceState, tracestateStr); } } internal static bool TryExtractTraceparent(string traceparent, out ActivityTraceId traceId, out ActivitySpanId spanId, out ActivityTraceFlags traceOptions) { // from https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md // traceparent: 00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01 traceId = default; spanId = default; traceOptions = default; var bestAttempt = false; if (string.IsNullOrWhiteSpace(traceparent) || traceparent.Length < TraceparentLengthV0) { return false; } // if version does not end with delimiter if (traceparent[VersionPrefixIdLength - 1] != '-') { return false; } // or version is not a hex (will throw) var version0 = HexCharToByte(traceparent[0]); var version1 = HexCharToByte(traceparent[1]); if (version0 == 0xf && version1 == 0xf) { return false; } if (version0 > 0) { // expected version is 00 // for higher versions - best attempt parsing of trace id, span id, etc. bestAttempt = true; } if (traceparent[VersionAndTraceIdLength - 1] != '-') { return false; } try { traceId = ActivityTraceId.CreateFromString(traceparent.AsSpan().Slice(VersionPrefixIdLength, TraceIdLength)); } catch (ArgumentOutOfRangeException) { // it's ok to still parse tracestate return false; } if (traceparent[VersionAndTraceIdAndSpanIdLength - 1] != '-') { return false; } byte options1; try { spanId = ActivitySpanId.CreateFromString(traceparent.AsSpan().Slice(VersionAndTraceIdLength, SpanIdLength)); options1 = HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength + 1]); } catch (ArgumentOutOfRangeException) { // it's ok to still parse tracestate return false; } if ((options1 & 1) == 1) { traceOptions |= ActivityTraceFlags.Recorded; } if ((!bestAttempt) && (traceparent.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength)) { return false; } if (bestAttempt) { if ((traceparent.Length > TraceparentLengthV0) && (traceparent[TraceparentLengthV0] != '-')) { return false; } } return true; } internal static bool TryExtractTracestate(string[] tracestateCollection, out string tracestateResult) { tracestateResult = string.Empty; if (tracestateCollection != null) { var keySet = new HashSet<string>(); var result = new StringBuilder(); for (int i = 0; i < tracestateCollection.Length; ++i) { var tracestate = tracestateCollection[i].AsSpan(); int begin = 0; while (begin < tracestate.Length) { int length = tracestate.Slice(begin).IndexOf(','); ReadOnlySpan<char> listMember; if (length != -1) { listMember = tracestate.Slice(begin, length).Trim(); begin += length + 1; } else { listMember = tracestate.Slice(begin).Trim(); begin = tracestate.Length; } // https://github.com/w3c/trace-context/blob/master/spec/20-http_request_header_format.md#tracestate-header-field-values if (listMember.IsEmpty) { // Empty and whitespace - only list members are allowed. // Vendors MUST accept empty tracestate headers but SHOULD avoid sending them. continue; } if (keySet.Count >= 32) { // https://github.com/w3c/trace-context/blob/master/spec/20-http_request_header_format.md#list // test_tracestate_member_count_limit return false; } int keyLength = listMember.IndexOf('='); if (keyLength == listMember.Length || keyLength == -1) { // Missing key or value in tracestate return false; } var key = listMember.Slice(0, keyLength); if (!ValidateKey(key)) { // test_tracestate_key_illegal_characters in https://github.com/w3c/trace-context/blob/master/test/test.py // test_tracestate_key_length_limit // test_tracestate_key_illegal_vendor_format return false; } var value = listMember.Slice(keyLength + 1); if (!ValidateValue(value)) { // test_tracestate_value_illegal_characters return false; } // ValidateKey() call above has ensured the key does not contain upper case letters. if (!keySet.Add(key.ToString())) { // test_tracestate_duplicated_keys return false; } if (result.Length > 0) { result.Append(','); } result.Append(listMember.ToString()); } } tracestateResult = result.ToString(); } return true; } private static byte HexCharToByte(char c) { if ((c >= '0') && (c <= '9')) { return (byte)(c - '0'); } if ((c >= 'a') && (c <= 'f')) { return (byte)(c - 'a' + 10); } throw new ArgumentOutOfRangeException(nameof(c), c, "Must be within: [0-9] or [a-f]"); } private static bool ValidateKey(ReadOnlySpan<char> key) { // This implementation follows Trace Context v1 which has W3C Recommendation. // https://www.w3.org/TR/trace-context-1/#key // It will be slightly differently from the next version of specification in GitHub repository. // There are two format for the key. The length rule applies to both. if (key.Length <= 0 || key.Length > TraceStateKeyMaxLength) { return false; } // The first format: // key = lcalpha 0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ) // lcalpha = % x61 - 7A; a - z // (There is an inconsistency in the expression above and the description in note. // Here is following the description in note: // "Identifiers MUST begin with a lowercase letter or a digit.") if (!IsLowerAlphaDigit(key[0])) { return false; } int tenantLength = -1; for (int i = 1; i < key.Length; ++i) { char ch = key[i]; if (ch == '@') { tenantLength = i; break; } if (!(IsLowerAlphaDigit(ch) || ch == '_' || ch == '-' || ch == '*' || ch == '/')) { return false; } } if (tenantLength == -1) { // There is no "@" sign. The key follow the first format. return true; } // The second format: // key = (lcalpha / DIGIT) 0 * 240(lcalpha / DIGIT / "_" / "-" / "*" / "/") "@" lcalpha 0 * 13(lcalpha / DIGIT / "_" / "-" / "*" / "/") if (tenantLength == 0 || tenantLength > TraceStateKeyTenantMaxLength) { return false; } int vendorLength = key.Length - tenantLength - 1; if (vendorLength == 0 || vendorLength > TraceStateKeyVendorMaxLength) { return false; } for (int i = tenantLength + 1; i < key.Length; ++i) { char ch = key[i]; if (!(IsLowerAlphaDigit(ch) || ch == '_' || ch == '-' || ch == '*' || ch == '/')) { return false; } } return true; } private static bool ValidateValue(ReadOnlySpan<char> value) { // https://github.com/w3c/trace-context/blob/master/spec/20-http_request_header_format.md#value // value = 0*255(chr) nblk-chr // nblk - chr = % x21 - 2B / % x2D - 3C / % x3E - 7E // chr = % x20 / nblk - chr if (value.Length <= 0 || value.Length > TraceStateValueMaxLength) { return false; } for (int i = 0; i < value.Length - 1; ++i) { char c = value[i]; if (!(c >= 0x20 && c <= 0x7E && c != 0x2C && c != 0x3D)) { return false; } } char last = value[value.Length - 1]; return last >= 0x21 && last <= 0x7E && last != 0x2C && last != 0x3D; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsLowerAlphaDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; // To simplify the process of finding the toolbox bitmap resource: // #1 Create an internal class called "resfinder" outside of the root namespace. // #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name. // #3 use the "<default namespace>.<resourcename>" string to locate the resource. // See: http://www.bobpowell.net/toolboxbitmap.htm internal class resfinder { } namespace WeifenLuo.WinFormsUI.Docking { [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")] public delegate IDockContent DeserializeDockContent(string persistString); [LocalizedDescription("DockPanel_Description")] [Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")] [ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")] [DefaultProperty("DocumentStyle")] [DefaultEvent("ActiveContentChanged")] public partial class DockPanel : Panel { private readonly FocusManagerImpl m_focusManager; private readonly DockPanelExtender m_extender; private readonly DockPaneCollection m_panes; private readonly FloatWindowCollection m_floatWindows; private AutoHideWindowControl m_autoHideWindow; private DockWindowCollection m_dockWindows; private readonly DockContent m_dummyContent; private readonly Control m_dummyControl; public DockPanel() { ShowAutoHideContentOnHover = true; m_focusManager = new FocusManagerImpl(this); m_extender = new DockPanelExtender(this); m_panes = new DockPaneCollection(); m_floatWindows = new FloatWindowCollection(); SuspendLayout(); m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; m_autoHideWindow.ActiveContentChanged += m_autoHideWindow_ActiveContentChanged; SetAutoHideWindowParent(); m_dummyControl = new DummyControl(); m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1); Controls.Add(m_dummyControl); LoadDockWindows(); m_dummyContent = new DockContent(); ResumeLayout(); } private Color m_BackColor; /// <summary> /// Determines the color with which the client rectangle will be drawn. /// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane). /// The BackColor property changes the borders of surrounding controls (DockPane). /// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle). /// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control) /// </summary> [Description("Determines the color with which the client rectangle will be drawn.\r\n" + "If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" + "The BackColor property changes the borders of surrounding controls (DockPane).\r\n" + "Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" + "For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")] public Color DockBackColor { get { return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor; } set { if (m_BackColor != value) { m_BackColor = value; this.Refresh(); } } } private bool ShouldSerializeDockBackColor() { return !m_BackColor.IsEmpty; } private void ResetDockBackColor() { DockBackColor = Color.Empty; } private AutoHideStripBase m_autoHideStripControl = null; internal AutoHideStripBase AutoHideStripControl { get { if (m_autoHideStripControl == null) { m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this); Controls.Add(m_autoHideStripControl); } return m_autoHideStripControl; } } internal void ResetAutoHideStripControl() { if (m_autoHideStripControl != null) m_autoHideStripControl.Dispose(); m_autoHideStripControl = null; } private void MdiClientHandleAssigned(object sender, EventArgs e) { SetMdiClient(); PerformLayout(); } private void MdiClient_Layout(object sender, LayoutEventArgs e) { if (DocumentStyle != DocumentStyle.DockingMdi) return; foreach (DockPane pane in Panes) if (pane.DockState == DockState.Document) pane.SetContentBounds(); InvalidateWindowRegion(); } private bool m_disposed = false; protected override void Dispose(bool disposing) { if (!m_disposed && disposing) { m_focusManager.Dispose(); if (m_mdiClientController != null) { m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned); m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout); m_mdiClientController.Dispose(); } FloatWindows.Dispose(); Panes.Dispose(); DummyContent.Dispose(); m_disposed = true; } base.Dispose(disposing); } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IDockContent ActiveAutoHideContent { get { return AutoHideWindow.ActiveContent; } set { AutoHideWindow.ActiveContent = value; } } private bool m_allowEndUserDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserDocking can only be false if running on Mono"); m_allowEndUserDocking = value; } } private bool m_allowEndUserNestedDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")] [DefaultValue(true)] public bool AllowEndUserNestedDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserNestedDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserNestedDocking can only be false if running on Mono"); m_allowEndUserNestedDocking = value; } } private DockContentCollection m_contents = new DockContentCollection(); [Browsable(false)] public DockContentCollection Contents { get { return m_contents; } } internal DockContent DummyContent { get { return m_dummyContent; } } private bool m_rightToLeftLayout = false; [DefaultValue(false)] [LocalizedCategory("Appearance")] [LocalizedDescription("DockPanel_RightToLeftLayout_Description")] public bool RightToLeftLayout { get { return m_rightToLeftLayout; } set { if (m_rightToLeftLayout == value) return; m_rightToLeftLayout = value; foreach (FloatWindow floatWindow in FloatWindows) floatWindow.RightToLeftLayout = value; } } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); foreach (FloatWindow floatWindow in FloatWindows) { if (floatWindow.RightToLeft != RightToLeft) floatWindow.RightToLeft = RightToLeft; } } private bool m_showDocumentIcon = false; [DefaultValue(false)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowDocumentIcon_Description")] public bool ShowDocumentIcon { get { return m_showDocumentIcon; } set { if (m_showDocumentIcon == value) return; m_showDocumentIcon = value; Refresh(); } } private DocumentTabStripLocation m_documentTabStripLocation = DocumentTabStripLocation.Top; [DefaultValue(DocumentTabStripLocation.Top)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentTabStripLocation")] public DocumentTabStripLocation DocumentTabStripLocation { get { return m_documentTabStripLocation; } set { m_documentTabStripLocation = value; } } [Browsable(false)] public DockPanelExtender Extender { get { return m_extender; } } [Browsable(false)] public DockPanelExtender.IDockPaneFactory DockPaneFactory { get { return Extender.DockPaneFactory; } } [Browsable(false)] public DockPanelExtender.IFloatWindowFactory FloatWindowFactory { get { return Extender.FloatWindowFactory; } } [Browsable(false)] public DockPanelExtender.IDockWindowFactory DockWindowFactory { get { return Extender.DockWindowFactory; } } internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory { get { return Extender.DockPaneCaptionFactory; } } internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory { get { return Extender.DockPaneStripFactory; } } internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory { get { return Extender.AutoHideStripFactory; } } [Browsable(false)] public DockPaneCollection Panes { get { return m_panes; } } internal Rectangle DockArea { get { return new Rectangle(DockPadding.Left, DockPadding.Top, ClientRectangle.Width - DockPadding.Left - DockPadding.Right, ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom); } } private double m_dockBottomPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockBottomPortion_Description")] [DefaultValue(0.25)] public double DockBottomPortion { get { return m_dockBottomPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockBottomPortion) return; m_dockBottomPortion = value; if (m_dockBottomPortion < 1 && m_dockTopPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockTopPortion = 1 - m_dockBottomPortion; } PerformLayout(); } } private double m_dockLeftPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockLeftPortion_Description")] [DefaultValue(0.25)] public double DockLeftPortion { get { return m_dockLeftPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockLeftPortion) return; m_dockLeftPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockRightPortion = 1 - m_dockLeftPortion; } PerformLayout(); } } private double m_dockRightPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockRightPortion_Description")] [DefaultValue(0.25)] public double DockRightPortion { get { return m_dockRightPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockRightPortion) return; m_dockRightPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockLeftPortion = 1 - m_dockRightPortion; } PerformLayout(); } } private double m_dockTopPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockTopPortion_Description")] [DefaultValue(0.25)] public double DockTopPortion { get { return m_dockTopPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockTopPortion) return; m_dockTopPortion = value; if (m_dockTopPortion < 1 && m_dockBottomPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockBottomPortion = 1 - m_dockTopPortion; } PerformLayout(); } } [Browsable(false)] public DockWindowCollection DockWindows { get { return m_dockWindows; } } public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge) { if (dockStyle == DockStyle.Left) { if (fullPanelEdge) DockWindows[DockState.DockLeft].SendToBack(); else DockWindows[DockState.DockLeft].BringToFront(); } else if (dockStyle == DockStyle.Right) { if (fullPanelEdge) DockWindows[DockState.DockRight].SendToBack(); else DockWindows[DockState.DockRight].BringToFront(); } else if (dockStyle == DockStyle.Top) { if (fullPanelEdge) DockWindows[DockState.DockTop].SendToBack(); else DockWindows[DockState.DockTop].BringToFront(); } else if (dockStyle == DockStyle.Bottom) { if (fullPanelEdge) DockWindows[DockState.DockBottom].SendToBack(); else DockWindows[DockState.DockBottom].BringToFront(); } } [Browsable(false)] public int DocumentsCount { get { int count = 0; foreach (IDockContent content in Documents) count++; return count; } } public IDockContent[] DocumentsToArray() { int count = DocumentsCount; IDockContent[] documents = new IDockContent[count]; int i = 0; foreach (IDockContent content in Documents) { documents[i] = content; i++; } return documents; } [Browsable(false)] public IEnumerable<IDockContent> Documents { get { foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) yield return content; } } } private Control DummyControl { get { return m_dummyControl; } } [Browsable(false)] public FloatWindowCollection FloatWindows { get { return m_floatWindows; } } private Size m_defaultFloatWindowSize = new Size(300, 300); [Category("Layout")] [LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")] public Size DefaultFloatWindowSize { get { return m_defaultFloatWindowSize; } set { m_defaultFloatWindowSize = value; } } private bool ShouldSerializeDefaultFloatWindowSize() { return DefaultFloatWindowSize != new Size(300, 300); } private void ResetDefaultFloatWindowSize() { DefaultFloatWindowSize = new Size(300, 300); } private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentStyle_Description")] [DefaultValue(DocumentStyle.DockingMdi)] public DocumentStyle DocumentStyle { get { return m_documentStyle; } set { if (value == m_documentStyle) return; if (!Enum.IsDefined(typeof(DocumentStyle), value)) throw new InvalidEnumArgumentException(); if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0) throw new InvalidEnumArgumentException(); m_documentStyle = value; SuspendLayout(true); SetAutoHideWindowParent(); SetMdiClient(); InvalidateWindowRegion(); foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane); } PerformMdiClientLayout(); ResumeLayout(true, true); } } private bool _supprtDeeplyNestedContent = false; [LocalizedCategory("Category_Performance")] [LocalizedDescription("DockPanel_SupportDeeplyNestedContent_Description")] [DefaultValue(false)] public bool SupportDeeplyNestedContent { get { return _supprtDeeplyNestedContent; } set { _supprtDeeplyNestedContent = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowAutoHideContentOnHover_Description")] [DefaultValue(true)] public bool ShowAutoHideContentOnHover { get; set; } public int GetDockWindowSize(DockState dockState) { if (dockState == DockState.DockLeft || dockState == DockState.DockRight) { int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right; int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion); int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion); if (dockLeftSize < MeasurePane.MinSize) dockLeftSize = MeasurePane.MinSize; if (dockRightSize < MeasurePane.MinSize) dockRightSize = MeasurePane.MinSize; if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize) { int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize); dockLeftSize -= adjust / 2; dockRightSize -= adjust / 2; } return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize; } else if (dockState == DockState.DockTop || dockState == DockState.DockBottom) { int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom; int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion); int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion); if (dockTopSize < MeasurePane.MinSize) dockTopSize = MeasurePane.MinSize; if (dockBottomSize < MeasurePane.MinSize) dockBottomSize = MeasurePane.MinSize; if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize) { int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize); dockTopSize -= adjust / 2; dockBottomSize -= adjust / 2; } return dockState == DockState.DockTop ? dockTopSize : dockBottomSize; } else return 0; } protected override void OnLayout(LayoutEventArgs levent) { SuspendLayout(true); AutoHideStripControl.Bounds = ClientRectangle; CalculateDockPadding(); DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft); DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight); DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop); DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom); AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle); DockWindows[DockState.Document].BringToFront(); AutoHideWindow.BringToFront(); base.OnLayout(levent); if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists) { SetMdiClientBounds(SystemMdiClientBounds); InvalidateWindowRegion(); } else if (DocumentStyle == DocumentStyle.DockingMdi) InvalidateWindowRegion(); ResumeLayout(true, true); } internal Rectangle GetTabStripRectangle(DockState dockState) { return AutoHideStripControl.GetTabStripRectangle(dockState); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (DockBackColor == BackColor) return; Graphics g = e.Graphics; SolidBrush bgBrush = new SolidBrush(DockBackColor); g.FillRectangle(bgBrush, ClientRectangle); } internal void AddContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (!Contents.Contains(content)) { Contents.Add(content); OnContentAdded(new DockContentEventArgs(content)); } } internal void AddPane(DockPane pane) { if (Panes.Contains(pane)) return; Panes.Add(pane); } internal void AddFloatWindow(FloatWindow floatWindow) { if (FloatWindows.Contains(floatWindow)) return; FloatWindows.Add(floatWindow); } private void CalculateDockPadding() { DockPadding.All = 0; int height = AutoHideStripControl.MeasureHeight(); if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0) DockPadding.Left = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0) DockPadding.Right = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0) DockPadding.Top = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0) DockPadding.Bottom = height; } internal void RemoveContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (Contents.Contains(content)) { Contents.Remove(content); OnContentRemoved(new DockContentEventArgs(content)); } } internal void RemovePane(DockPane pane) { if (!Panes.Contains(pane)) return; Panes.Remove(pane); } internal void RemoveFloatWindow(FloatWindow floatWindow) { if (!FloatWindows.Contains(floatWindow)) return; FloatWindows.Remove(floatWindow); if (FloatWindows.Count != 0) return; if (ParentForm == null) return; ParentForm.Focus(); } public void SetPaneIndex(DockPane pane, int index) { int oldIndex = Panes.IndexOf(pane); if (oldIndex == -1) throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane)); if (index < 0 || index > Panes.Count - 1) if (index != -1) throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Panes.Count - 1 && index == -1) return; Panes.Remove(pane); if (index == -1) Panes.Add(pane); else if (oldIndex < index) Panes.AddAt(pane, index - 1); else Panes.AddAt(pane, index); } public void SuspendLayout(bool allWindows) { FocusManager.SuspendFocusTracking(); SuspendLayout(); if (allWindows) SuspendMdiClientLayout(); } public void ResumeLayout(bool performLayout, bool allWindows) { FocusManager.ResumeFocusTracking(); ResumeLayout(performLayout); if (allWindows) ResumeMdiClientLayout(performLayout); } internal Form ParentForm { get { if (!IsParentFormValid()) throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid); return GetMdiClientController().ParentForm; } } private bool IsParentFormValid() { if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) return true; if (!MdiClientExists) GetMdiClientController().RenewMdiClient(); return (MdiClientExists); } protected override void OnParentChanged(EventArgs e) { SetAutoHideWindowParent(); GetMdiClientController().ParentForm = (this.Parent as Form); base.OnParentChanged (e); } private void SetAutoHideWindowParent() { Control parent; if (DocumentStyle == DocumentStyle.DockingMdi || DocumentStyle == DocumentStyle.SystemMdi) parent = this.Parent; else parent = this; if (AutoHideWindow.Parent != parent) { AutoHideWindow.Parent = parent; AutoHideWindow.BringToFront(); } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged (e); if (Visible) SetMdiClient(); } private Rectangle SystemMdiClientBounds { get { if (!IsParentFormValid() || !Visible) return Rectangle.Empty; Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds)); return rect; } } internal Rectangle DocumentWindowBounds { get { Rectangle rectDocumentBounds = DisplayRectangle; if (DockWindows[DockState.DockLeft].Visible) { rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width; rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width; } if (DockWindows[DockState.DockRight].Visible) rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width; if (DockWindows[DockState.DockTop].Visible) { rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height; rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height; } if (DockWindows[DockState.DockBottom].Visible) rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height; return rectDocumentBounds; } } private PaintEventHandler m_dummyControlPaintEventHandler = null; private void InvalidateWindowRegion() { if (DesignMode) return; if (m_dummyControlPaintEventHandler == null) m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint); DummyControl.Paint += m_dummyControlPaintEventHandler; DummyControl.Invalidate(); } void DummyControl_Paint(object sender, PaintEventArgs e) { DummyControl.Paint -= m_dummyControlPaintEventHandler; UpdateWindowRegion(); } private void UpdateWindowRegion() { if (this.DocumentStyle == DocumentStyle.DockingMdi) UpdateWindowRegion_ClipContent(); else if (this.DocumentStyle == DocumentStyle.DockingSdi || this.DocumentStyle == DocumentStyle.DockingWindow) UpdateWindowRegion_FullDocumentArea(); else if (this.DocumentStyle == DocumentStyle.SystemMdi) UpdateWindowRegion_EmptyDocumentArea(); } private void UpdateWindowRegion_FullDocumentArea() { SetRegion(null); } private void UpdateWindowRegion_EmptyDocumentArea() { Rectangle rect = DocumentWindowBounds; SetRegion(new Rectangle[] { rect }); } private void UpdateWindowRegion_ClipContent() { int count = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; count ++; } if (count == 0) { SetRegion(null); return; } Rectangle[] rects = new Rectangle[count]; int i = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle)); i++; } SetRegion(rects); } private Rectangle[] m_clipRects = null; private void SetRegion(Rectangle[] clipRects) { if (!IsClipRectsChanged(clipRects)) return; m_clipRects = clipRects; if (m_clipRects == null || m_clipRects.GetLength(0) == 0) Region = null; else { Region region = new Region(new Rectangle(0, 0, this.Width, this.Height)); foreach (Rectangle rect in m_clipRects) region.Exclude(rect); if (Region != null) { Region.Dispose(); } Region = region; } } private bool IsClipRectsChanged(Rectangle[] clipRects) { if (clipRects == null && m_clipRects == null) return false; else if ((clipRects == null) != (m_clipRects == null)) return true; foreach (Rectangle rect in clipRects) { bool matched = false; foreach (Rectangle rect2 in m_clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } foreach (Rectangle rect2 in m_clipRects) { bool matched = false; foreach (Rectangle rect in clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } return false; } private static readonly object ActiveAutoHideContentChangedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ActiveAutoHideContentChanged_Description")] public event EventHandler ActiveAutoHideContentChanged { add { Events.AddHandler(ActiveAutoHideContentChangedEvent, value); } remove { Events.RemoveHandler(ActiveAutoHideContentChangedEvent, value); } } protected virtual void OnActiveAutoHideContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveAutoHideContentChangedEvent]; if (handler != null) handler(this, e); } private void m_autoHideWindow_ActiveContentChanged(object sender, EventArgs e) { OnActiveAutoHideContentChanged(e); } private static readonly object ContentAddedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentAdded_Description")] public event EventHandler<DockContentEventArgs> ContentAdded { add { Events.AddHandler(ContentAddedEvent, value); } remove { Events.RemoveHandler(ContentAddedEvent, value); } } protected virtual void OnContentAdded(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent]; if (handler != null) handler(this, e); } private static readonly object ContentRemovedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentRemoved_Description")] public event EventHandler<DockContentEventArgs> ContentRemoved { add { Events.AddHandler(ContentRemovedEvent, value); } remove { Events.RemoveHandler(ContentRemovedEvent, value); } } protected virtual void OnContentRemoved(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent]; if (handler != null) handler(this, e); } internal void ReloadDockWindows() { var old = m_dockWindows; LoadDockWindows(); foreach (var dockWindow in old) { Controls.Remove(dockWindow); dockWindow.Dispose(); } } internal void LoadDockWindows() { m_dockWindows = new DockWindowCollection(this); foreach (var dockWindow in DockWindows) { Controls.Add(dockWindow); } } public void ResetAutoHideStripWindow() { var old = m_autoHideWindow; m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; SetAutoHideWindowParent(); old.Visible = false; old.Parent = null; old.Dispose(); } } }
using System; using System.Text; using System.IO; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using Syncfusion.XlsIO; namespace es.jbauer.lib.tables { public interface TableReader : IDisposable { /* List of headers. */ string[] getHeaders(); /* True if next row is the first row. */ bool isFirstRow(); /* If there is another row. */ bool hasNextRow(); /* Next row to display. */ TableRow getNextRow(); /* Information about the source from which we read data. */ string getInfo(); /* Information about the source from which we read data. */ void setInfo(string info); /* Sets the date formatting to be used when we parse string dates to Date. Default uses US formatting. */ void setDateFormat(string dateFormat, string dateTimeFormat); } public interface TableWriter : IDisposable { void writeHeaders(string[] headers); void writeRow(string[] values); void writeRow(TableRow row); } public interface TableRow { string[] getHeaders(); int getCount(); string[] getValues(); string getSourceInfo(); string get(int i); string get(string col); Int32 getInt(int i); Int32 getInt(string col); Int64 getInt64(int i); Int64 getInt64(string col); DateTime getDate(int i); DateTime getDate(string col); // Float getFloat(int i); // Float getFloat(string col); Boolean getBoolean(int i); Boolean getBoolean(string col); // Object get(int col, Class type); // Object get(string col, Class type); } public class JoinTableReader : TableReader { private string[] headers; private string info; int index = -1; private List<TableRow> rows = new List<TableRow>(); public JoinTableReader(TableReader reader1, string prefix1, string col1, TableReader reader2, string prefix2, string col2) { headers = append(reader1.getHeaders(), reader2.getHeaders()); int size1 = reader1.getHeaders().Length; for (int i = 0; i < size1; i++) headers[i] = prefix1 + "." + headers[i]; for (int i = size1; i < headers.Length; i++) headers[i] = prefix2 + "." + headers[i]; info = "Join: " + reader1.getInfo() + "(" + col1 + "), " + reader2.getInfo() + " (" + col2 + ")"; Dictionary<string, TableRow> row1Lookup = new Dictionary<string, TableRow>(); while (reader1.hasNextRow()) { TableRow row = reader1.getNextRow(); string key = row.get(col1); if (key != null) { if (!row1Lookup.ContainsKey(key)) row1Lookup.Add(key, row); // else // Console.Out.WriteLine(key + " => " + row.ToString()); } } while (reader2.hasNextRow()) { TableRow row2 = reader2.getNextRow(); TableRow row1 = null; if (row1Lookup.TryGetValue(row2.get(col2), out row1)) rows.Add(new StringArrayTableRow(headers, append(row1.getValues(), row2.getValues()))); } } private string[] append(string[] arr1, string[] arr2) { string[] result = new string[arr1.Length + arr2.Length]; Array.Copy(arr1, result, arr1.Length); Array.Copy(arr2, 0, result, arr1.Length, arr2.Length); return result; } public string[] getHeaders() { return headers; } public bool isFirstRow() { return index == 0; } public bool hasNextRow() { return index + 1< rows.Count; } public TableRow getNextRow() { index++; return rows[index]; } public void Dispose() {} public string getInfo() { return info; } public void setInfo(string info) {} public void setDateFormat(string dateFormat, string dateTimeFormat) {} } public class TableUtil { public static TableReader getTableReader(string vendor, string connection, string query) { if ("MSSQL".Equals(vendor) || "OLEDB".Equals(vendor) || "MYSQL".Equals(vendor)) return new DbTableReader(vendor, connection, query); if ("EXCEL".Equals(vendor)) return new ExcelTableReader(connection, query); // if ("CSV".Equals(vendor)) // return new ExcelTableReader(connection); return null; } } public class DbUtil { public static IDbConnection getConnection(string vendor, string connection) { if ("MSSQL".Equals(vendor)) return new SqlConnection(connection); else if ("OLEDB".Equals(vendor)) return new System.Data.OleDb.OleDbConnection(connection); else if ("MYSQL".Equals(vendor)) return new MySql.Data.MySqlClient.MySqlConnection(connection); else throw new Exception("Unknown vendor type '" + vendor + "'"); } } public class ExcelTableReader : TableReader { private string[] headers; private ExcelEngine xlsEngine; private IApplication xlsApp; private IWorksheet xlsSheet; private int nextRow = 0; private int skipRows = 0; private string info; public ExcelTableReader(string filename) : this(filename, null) {} public ExcelTableReader(string filename, string worksheetName) { if (worksheetName != null) { int pos = worksheetName.IndexOf("!"); if (pos != -1) { skipRows = Int32.Parse(worksheetName.Substring(pos + 1)); if (pos > 1) worksheetName = worksheetName.Substring(0, pos); else worksheetName = null; } } xlsEngine = new ExcelEngine(); xlsApp = xlsEngine.Excel; if (filename.EndsWith(".tsv")) xlsApp.Workbooks.Open(filename, "\t"); else if (filename.EndsWith(".csv")) xlsApp.Workbooks.Open(filename, ","); else xlsApp.Workbooks.Open(filename); IWorkbook wb = xlsApp.Workbooks[0]; if (String.IsNullOrEmpty(worksheetName)) xlsSheet = wb.Worksheets[0]; else { int i = 0; while (xlsSheet == null && i < wb.Worksheets.Count) { if (worksheetName.Equals(wb.Worksheets[i].Name)) xlsSheet = wb.Worksheets[i]; i++; } if (xlsSheet == null) xlsSheet = wb.Worksheets[0]; } List<string> tmpHeaders = new List<string>(); foreach (IRange cell in xlsSheet.Rows[skipRows].Cells) tmpHeaders.Add(cell.Value2.ToString()); nextRow = skipRows; headers = getArray(tmpHeaders); } private string[] getArray(IList<string> values) { string[] result = new string[values.Count]; for (int i = 0; i < result.Length; i++) result[i] = values[i]; return result; } public string[] getHeaders() { return headers; } /** @return True if next row is the first row. */ public bool isFirstRow() { return nextRow == skipRows; } /** @return If there is another row. */ public bool hasNextRow() { return nextRow + 1 < xlsSheet.Rows.Length; } /** @return Next row to display. */ public TableRow getNextRow() { if (!hasNextRow()) return null; List<string> values = new List<string>(); foreach (IRange cell in xlsSheet.Rows[nextRow + 1].Cells) values.Add(cell.Value2.ToString()); nextRow++; return new StringArrayTableRow(headers, getArray(values)); } public string getInfo() { return info; } public void setInfo(string info) { this.info = info; } public void setDateFormat(string dateFormat, string dateTimeFormat) {} public void Dispose() { xlsApp.Workbooks.Close(); xlsEngine.Dispose(); } } public class DbTableReader : TableReader { private string[] headers; private string query; private IDbConnection conn; private IDataReader reader; private TableRow row; private TableRow nextRow; private string info; private bool firstRow = true; public DbTableReader(string vendor, string connection, string query) { this.query = query; conn = DbUtil.getConnection(vendor, connection); conn.Open(); IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = query; Console.Out.WriteLine("==> " + query); Console.Out.Flush(); reader = null; reader = cmd.ExecuteReader(); headers = new string[reader.FieldCount]; for (int i = 0; i < headers.Length; i++) headers[i] = reader.GetName(i); } public string[] getHeaders() { return headers; } public bool isFirstRow() { return firstRow; } private void ensureNextRow() { if (nextRow != null) return; if (reader.Read()) { object[] v = new object[headers.Length]; reader.GetValues(v); string[] values = new string[headers.Length]; for (int i = 0; i < values.Length; i++) values[i] = v[i] == null ? null : v[i].ToString(); nextRow = new StringArrayTableRow(headers, values); } } public bool hasNextRow() { ensureNextRow(); return nextRow != null; } public TableRow getNextRow() { if (!hasNextRow()) return null; firstRow = row == null; row = nextRow; nextRow = null; return row; } public void Dispose() { reader.Close(); conn.Close(); GC.SuppressFinalize(this); } public string getInfo() { return info; } public void setInfo(string info) { this.info = info; } public void setDateFormat(string dateFormat, string dateTimeFormat) { throw new NotImplementedException(); } } abstract class TableRowBase : TableRow { private string[] headers; private string info; public abstract string get(int i); public abstract string[] getValues(); public TableRowBase(string[] headers) { this.headers = headers; } public string[] getHeaders() { return headers; } public int getCount() { return headers.Length; } public string getSourceInfo() { return info; } public void setSourceInfo(string info) { this.info = info; } public string get(string col) { return get(getIndex(col)); } public int getInt(int i) { if (!isValid(i)) return Int32.MinValue; return Int32.Parse(get(i)); } public int getInt(string col) { return getInt(getIndex(col)); } public long getInt64(int i) { return Int64.Parse(get(i)); } public long getInt64(string col) { return getInt64(getIndex(col)); } public DateTime getDate(int i) { if (!isValid(i)) return DateTime.MinValue; return DateTime.Parse(get(i)); } public DateTime getDate(string col) { return getDate(getIndex(col)); } public bool getBoolean(int i) { if (!isValid(i)) return false; return Boolean.Parse(get(i)); } public bool getBoolean(string col) { return getBoolean(getIndex(col)); } protected bool isValid(int index) { return index >= 0 && index < headers.Length; } protected int getIndex(string col) { for (int i = 0; i < headers.Length; i++) if (headers[i].Equals(col)) return i; throw new ArgumentException("Unknown column '" + col + "'"); } } class DictionaryTableRow : StringArrayTableRow { public DictionaryTableRow(string[] headers, Dictionary<string, string> values) : base(headers, DictionaryTableRow.getValues(headers, null, values)) {} public DictionaryTableRow(TableRow row, Dictionary<string, string> values) : base(row.getHeaders(), DictionaryTableRow.getValues(row.getHeaders(), row.getValues(), values)) {} private static string[] getValues(string[] headers, string[] values, Dictionary<string, string> mapValues) { string[] result = new string[headers.Length]; for (int i = 0; i < headers.Length; i++) { if (values != null) result[i] = values[i]; string value = ""; if (mapValues.TryGetValue(headers[i], out value)) result[i] = value; } return result; } } class StringArrayTableRow : TableRowBase { private string[] values; public StringArrayTableRow(string[] headers, string[] values) : base(headers) { this.values = values; } public override string[] getValues() { return values; } override public string get(int i) { return values[i]; } } class LogTableWriter : TableWriter { private TextWriter writer; private string[] headers = null; private bool headersWritten = false; private string prefix = ""; public LogTableWriter(TextWriter writer, string prefix) { this.writer = writer; this.prefix = prefix; } public LogTableWriter(TextWriter writer) { this.writer = writer; } public void writeHeaders(string[] headers) { if (this.headers == null) this.headers = headers; else { if (headers.Length != this.headers.Length) throw new Exception("Mismatching header count: " + headers.Length + " vs " + this.headers.Length); for (int i = 0; i < headers.Length; i++) if (!headers[i].Equals(this.headers[i])) throw new Exception("Mismatching header[" + i + "]: " + headers[i] + " vs " + this.headers[i]); } } public void writeRow(string[] values) { if (!headersWritten) { if (writer != null) writer.WriteLine(prefix + String.Join(", ", headers)); headersWritten = true; } if (writer != null) writer.WriteLine(prefix + String.Join(", ", values)); } public void writeRow(TableRow row) { writeRow(row.getValues()); } public void Dispose() { if (writer != null) writer.Flush(); } } class NullTableWriter : TableWriter { public void writeHeaders(string[] headers) { } public void writeRow(string[] values) { } public void writeRow(TableRow row) { } public void Dispose() { } } class DbTableWriter : TableWriter { private IDbConnection conn; private string table; private string[] headers; public DbTableWriter(string vendor, string connection, string table) { conn = DbUtil.getConnection(vendor, connection); conn.Open(); this.table = table; } public void writeHeaders(string[] headers) { this.headers = headers; } public void writeRow(string[] values) { IDbCommand cmd = conn.CreateCommand(); try { cmd.CommandText = getInsertSql(); for (int i = 0; i < headers.Length; i++) { IDbDataParameter param = cmd.CreateParameter(); param.ParameterName = headers[i]; if (String.IsNullOrEmpty(values[i])) param.Value = DBNull.Value; else param.Value = values[i]; cmd.Parameters.Add(param); } cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } } public void writeRow(TableRow row) { if (headers == null) headers = row.getHeaders(); writeRow(row.getValues()); } /** Finish writing table. */ public void Dispose() { if (conn != null) conn.Close(); conn = null; GC.SuppressFinalize(this); } private string getInsertSql() { StringBuilder result = new StringBuilder(); result.Append("INSERT INTO "); result.Append(table); result.Append(" ("); result.Append(String.Join(",", headers)); result.Append(") VALUES (@"); result.Append(String.Join(",@", headers)); result.Append(")"); return result.ToString(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// Prefer string.Contains over string.IndexOf when the result is used to check for the presence/absence of a substring /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class PreferStringContainsOverIndexOfAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2249"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferStringContainsOverIndexOfTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferStringContainsOverIndexOfMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferStringContainsOverIndexOfDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(context => { if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemString, out INamedTypeSymbol? stringType) || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemChar, out INamedTypeSymbol? charType) || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison, out INamedTypeSymbol? stringComparisonType)) { return; } // First get all the string.IndexOf methods that we are interested in tagging var stringIndexOfMethods = stringType .GetMembers("IndexOf") .OfType<IMethodSymbol>() .WhereAsArray(s => s.Parameters.Length <= 2); var stringArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(stringType)); var charArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(charType)); var stringAndComparisonTypeArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(stringType), ParameterInfo.GetParameterInfo(stringComparisonType)); var charAndComparisonTypeArgumentIndexOfMethod = stringIndexOfMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(charType), ParameterInfo.GetParameterInfo(stringComparisonType)); // Check that the contains methods that take 2 parameters exist // string.Contains(char) is also .NETStandard2.1+ var stringContainsMethods = stringType .GetMembers("Contains") .OfType<IMethodSymbol>() .WhereAsArray(s => s.Parameters.Length <= 2); var stringAndComparisonTypeArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(stringType), ParameterInfo.GetParameterInfo(stringComparisonType)); var charAndComparisonTypeArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(charType), ParameterInfo.GetParameterInfo(stringComparisonType)); var charArgumentContainsMethod = stringContainsMethods.GetFirstOrDefaultMemberWithParameterInfos( ParameterInfo.GetParameterInfo(charType)); if (stringAndComparisonTypeArgumentContainsMethod == null || charAndComparisonTypeArgumentContainsMethod == null || charArgumentContainsMethod == null) { return; } // Roslyn doesn't yet support "FindAllReferences" at a file/block level. So instead, find references to local int variables in this block. context.RegisterOperationBlockStartAction(OnOperationBlockStart); return; void OnOperationBlockStart(OperationBlockStartAnalysisContext context) { if (!(context.OwningSymbol is IMethodSymbol method)) { return; } // Algorithm: // We aim to change string.IndexOf -> string.Contains // 1. We register 1 callback for invocations of IndexOf. // 1a. Check if invocation.Parent is a binary operation we care about (string.IndexOf >= 0 OR string.IndexOf == -1). If so, report a diagnostic and return from the callback. // 1b. Otherwise, check if invocation.Parent is a variable declarator. If so, add the invocation as a potential violation to track into variableNameToOperationsMap. // 2. We register another callback for local references // 2a. If the local reference is not a type int, bail out. // 2b. If the local reference operation's parent is not a binary operation, add it to "localsToBailOut". // 3. In an operation block end, we check if entries in "variableNameToOperationsMap" exist in "localToBailOut". If an entry is NOT present, we report a diagnostic at that invocation. PooledConcurrentSet<ILocalSymbol> localsToBailOut = PooledConcurrentSet<ILocalSymbol>.GetInstance(); PooledConcurrentDictionary<ILocalSymbol, IInvocationOperation> variableNameToOperationsMap = PooledConcurrentDictionary<ILocalSymbol, IInvocationOperation>.GetInstance(); context.RegisterOperationAction(PopulateLocalReferencesSet, OperationKind.LocalReference); context.RegisterOperationAction(AnalyzeInvocationOperation, OperationKind.Invocation); context.RegisterOperationBlockEndAction(OnOperationBlockEnd); return; // Local Functions void PopulateLocalReferencesSet(OperationAnalysisContext context) { ILocalReferenceOperation localReference = (ILocalReferenceOperation)context.Operation; if (localReference.Local.Type.SpecialType != SpecialType.System_Int32) { return; } var parent = localReference.Parent; if (parent is IBinaryOperation binaryOperation) { var otherOperand = binaryOperation.LeftOperand is ILocalReferenceOperation ? binaryOperation.RightOperand : binaryOperation.LeftOperand; if (CheckOperatorKindAndOperand(binaryOperation, otherOperand)) { // Do nothing. This is a valid case to the tagged in the analyzer return; } } localsToBailOut.Add(localReference.Local); } void AnalyzeInvocationOperation(OperationAnalysisContext context) { var invocationOperation = (IInvocationOperation)context.Operation; if (!IsDesiredTargetMethod(invocationOperation.TargetMethod)) { return; } var parent = invocationOperation.Parent; if (parent is IBinaryOperation binaryOperation) { var otherOperand = binaryOperation.LeftOperand is IInvocationOperation ? binaryOperation.RightOperand : binaryOperation.LeftOperand; if (CheckOperatorKindAndOperand(binaryOperation, otherOperand)) { context.ReportDiagnostic(binaryOperation.CreateDiagnostic(Rule)); } } else if (parent is IVariableInitializerOperation variableInitializer) { if (variableInitializer.Parent is IVariableDeclaratorOperation variableDeclaratorOperation) { variableNameToOperationsMap.TryAdd(variableDeclaratorOperation.Symbol, invocationOperation); } else if (variableInitializer.Parent is IVariableDeclarationOperation variableDeclarationOperation && variableDeclarationOperation.Declarators.Length == 1) { variableNameToOperationsMap.TryAdd(variableDeclarationOperation.Declarators[0].Symbol, invocationOperation); } } } static bool CheckOperatorKindAndOperand(IBinaryOperation binaryOperation, IOperation otherOperand) { var operatorKind = binaryOperation.OperatorKind; if (otherOperand.ConstantValue.HasValue && otherOperand.ConstantValue.Value is int intValue) { if ((operatorKind == BinaryOperatorKind.Equals && intValue < 0) || (operatorKind == BinaryOperatorKind.GreaterThanOrEqual && intValue == 0)) { // This is the only case we are targeting in this analyzer return true; } } return false; } void OnOperationBlockEnd(OperationBlockAnalysisContext context) { foreach (var variableNameAndLocation in variableNameToOperationsMap) { ILocalSymbol variable = variableNameAndLocation.Key; if (!localsToBailOut.Contains(variable)) { context.ReportDiagnostic(variableNameAndLocation.Value.CreateDiagnostic(Rule)); } } variableNameToOperationsMap.Free(); localsToBailOut.Free(); } bool IsDesiredTargetMethod(IMethodSymbol targetMethod) => targetMethod.Equals(stringArgumentIndexOfMethod) || targetMethod.Equals(charArgumentIndexOfMethod) || targetMethod.Equals(stringAndComparisonTypeArgumentIndexOfMethod) || targetMethod.Equals(charAndComparisonTypeArgumentIndexOfMethod); } }); } } }
using Pathfinding; using System.Collections.Generic; namespace Pathfinding { /** Stores temporary node data for a single pathfinding request. * Every node has one PathNode per thread used. * It stores e.g G score, H score and other temporary variables needed * for path calculation, but which are not part of the graph structure. * * \see Pathfinding.PathHandler */ public class PathNode { /** Reference to the actual graph node */ public GraphNode node; /** Parent node in the search tree */ public PathNode parent; /** The path request (in this thread, if multithreading is used) which last used this node */ public ushort pathID; /** Bitpacked variable which stores several fields */ private uint flags; /** Cost uses the first 28 bits */ private const uint CostMask = (1U << 28) - 1U; /** Flag 1 is at bit 28 */ private const int Flag1Offset = 28; private const uint Flag1Mask = (uint)(1 << Flag1Offset); /** Flag 2 is at bit 29 */ private const int Flag2Offset = 29; private const uint Flag2Mask = (uint)(1 << Flag2Offset); public uint cost { get { return flags & CostMask; } set { flags = (flags & ~CostMask) | value; } } /** Use as temporary flag during pathfinding. * Pathfinders (only) can use this during pathfinding to mark * nodes. When done, this flag should be reverted to its default state (false) to * avoid messing up other pathfinding requests. */ public bool flag1 { get { return (flags & Flag1Mask) != 0; } set { flags = (flags & ~Flag1Mask) | (value ? Flag1Mask : 0U); } } /** Use as temporary flag during pathfinding. * Pathfinders (only) can use this during pathfinding to mark * nodes. When done, this flag should be reverted to its default state (false) to * avoid messing up other pathfinding requests. */ public bool flag2 { get { return (flags & Flag2Mask) != 0; } set { flags = (flags & ~Flag2Mask) | (value ? Flag2Mask : 0U); } } /** Backing field for the G score */ private uint g; /** Backing field for the H score */ private uint h; /** G score, cost to get to this node */ public uint G {get { return g;} set{g = value;}} /** H score, estimated cost to get to to the target */ public uint H {get { return h;} set{h = value;}} /** F score. H score + G score */ public uint F {get { return g+h;}} } /** Handles thread specific path data. */ public class PathHandler { /** Current PathID. * \see #PathID */ private ushort pathID; /** Binary heap to keep nodes on the "Open list" */ private BinaryHeapM heap = new BinaryHeapM(128); /** ID for the path currently being calculated or last path that was calculated */ public ushort PathID {get { return pathID; }} /** Push a node to the heap */ public void PushNode (PathNode node) { heap.Add (node); } /** Pop the node with the lowest F score off the heap */ public PathNode PopNode () { return heap.Remove (); } /** Get the internal heap. * \note Most things can be accomplished with the methods on this class instead. */ public BinaryHeapM GetHeap () { return heap; } /** Rebuild the heap to account for changed node values. * Some path types change the target for the H score in the middle of the path calculation, * that requires rebuilding the heap to keep it correctly sorted */ public void RebuildHeap () { heap.Rebuild (); } /** True if the heap is empty */ public bool HeapEmpty () { return heap.numberOfItems <= 0; } /** Log2 size of buckets. * So 10 yields a real bucket size of 1024. * Be careful with large values. */ const int BucketSizeLog2 = 10; /** Real bucket size */ const int BucketSize = 1 << BucketSizeLog2; const int BucketIndexMask = (1 << BucketSizeLog2)-1; /** Array of buckets containing PathNodes */ public PathNode[][] nodes = new PathNode[0][]; private bool[] bucketNew = new bool[0]; private bool[] bucketCreated = new bool[0]; private Stack<PathNode[]> bucketCache = new Stack<PathNode[]> (); private int filledBuckets = 0; /** StringBuilder that paths can use to build debug strings. * Better to use a single StringBuilder instead of each path creating its own */ public readonly System.Text.StringBuilder DebugStringBuilder = new System.Text.StringBuilder(); public PathHandler () { } public void InitializeForPath (Path p) { pathID = p.pathID; heap.Clear (); } /** Internal method to clean up node data */ public void DestroyNode (GraphNode node) { PathNode pn = GetPathNode (node); //Clean up reference to help GC pn.node = null; pn.parent = null; } /** Internal method to initialize node data */ public void InitializeNode (GraphNode node) { //Get the index of the node int ind = node.NodeIndex; int bucketNumber = ind >> BucketSizeLog2; int bucketIndex = ind & BucketIndexMask; if (bucketNumber >= nodes.Length) { //At least increase the size to: //Current size * 1.5 //Current size + 2 or //bucketNumber PathNode[][] newNodes = new PathNode[System.Math.Max (System.Math.Max (nodes.Length*3 / 2,bucketNumber+1), nodes.Length+2)][]; for (int i=0;i<nodes.Length;i++) newNodes[i] = nodes[i]; //Debug.Log ("Resizing Bucket List from " + nodes.Length + " to " + newNodes.Length + " (bucketNumber="+bucketNumber+")"); bool[] newBucketNew = new bool[newNodes.Length]; for (int i=0;i<nodes.Length;i++) newBucketNew[i] = bucketNew[i]; bool[] newBucketCreated = new bool[newNodes.Length]; for (int i=0;i<nodes.Length;i++) newBucketCreated[i] = bucketCreated[i]; nodes = newNodes; bucketNew = newBucketNew; bucketCreated = newBucketCreated; } if (nodes[bucketNumber] == null) { PathNode[] ns; if (bucketCache.Count > 0) { ns = bucketCache.Pop(); } else { ns = new PathNode[BucketSize]; for (int i=0;i<BucketSize;i++) ns[i] = new PathNode (); } nodes[bucketNumber] = ns; if (!bucketCreated[bucketNumber]) { bucketNew[bucketNumber] = true; bucketCreated[bucketNumber] = true; } filledBuckets++; } PathNode pn = nodes[bucketNumber][bucketIndex]; pn.node = node; } public PathNode GetPathNode (GraphNode node) { //Get the index of the node int ind = node.NodeIndex; return nodes[ind >> BucketSizeLog2][ind & BucketIndexMask]; } /** Set all node's pathIDs to 0. * \see Pathfinding.PathNode.pathID */ public void ClearPathIDs () { for (int i=0;i<nodes.Length;i++) { PathNode[] ns = nodes[i]; if (nodes[i] != null) for (int j=0;j<BucketSize;j++) ns[j].pathID = 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. namespace System.ServiceModel.Syndication { using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; [XmlRoot(ElementName = App10Constants.Categories, Namespace = App10Constants.Namespace)] public class AtomPub10CategoriesDocumentFormatter : CategoriesDocumentFormatter { private Type _inlineDocumentType; private int _maxExtensionSize; private bool _preserveAttributeExtensions; private bool _preserveElementExtensions; private Type _referencedDocumentType; public AtomPub10CategoriesDocumentFormatter() : this(typeof(InlineCategoriesDocument), typeof(ReferencedCategoriesDocument)) { } public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type referencedDocumentType) : base() { if (inlineDocumentType == null) { throw new ArgumentNullException(nameof(inlineDocumentType)); } if (!typeof(InlineCategoriesDocument).IsAssignableFrom(inlineDocumentType)) { throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(inlineDocumentType), nameof(InlineCategoriesDocument))); } if (referencedDocumentType == null) { throw new ArgumentNullException(nameof(referencedDocumentType)); } if (!typeof(ReferencedCategoriesDocument).IsAssignableFrom(referencedDocumentType)) { throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(referencedDocumentType), nameof(ReferencedCategoriesDocument))); } _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = true; _preserveElementExtensions = true; _inlineDocumentType = inlineDocumentType; _referencedDocumentType = referencedDocumentType; } public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) : base(documentToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = true; _preserveElementExtensions = true; if (documentToWrite.IsInline) { _inlineDocumentType = documentToWrite.GetType(); _referencedDocumentType = typeof(ReferencedCategoriesDocument); } else { _referencedDocumentType = documentToWrite.GetType(); _inlineDocumentType = typeof(InlineCategoriesDocument); } } public override string Version { get { return App10Constants.Namespace; } } public override Task<bool> CanReadAsync(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } XmlReaderWrapper wrappedReader = XmlReaderWrapper.CreateFromReader(reader); return wrappedReader.IsStartElementAsync(App10Constants.Categories, App10Constants.Namespace); } Task ReadXmlAsync(XmlReaderWrapper reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return ReadDocumentAsync(reader); } Task WriteXmlAsync(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (this.Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } return WriteDocumentAsync(writer); } public override async Task ReadFromAsync(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } if (!await CanReadAsync(reader)) { throw new XmlException(string.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI)); } await ReadDocumentAsync(XmlReaderWrapper.CreateFromReader(reader)); } public override async Task WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (this.Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } writer.WriteStartElement(App10Constants.Prefix, App10Constants.Categories, App10Constants.Namespace); await WriteDocumentAsync(writer); writer.WriteEndElement(); } protected override InlineCategoriesDocument CreateInlineCategoriesDocument() { if (_inlineDocumentType == typeof(InlineCategoriesDocument)) { return new InlineCategoriesDocument(); } else { return (InlineCategoriesDocument)Activator.CreateInstance(_inlineDocumentType); } } protected override ReferencedCategoriesDocument CreateReferencedCategoriesDocument() { if (_referencedDocumentType == typeof(ReferencedCategoriesDocument)) { return new ReferencedCategoriesDocument(); } else { return (ReferencedCategoriesDocument)Activator.CreateInstance(_referencedDocumentType); } } private async Task ReadDocumentAsync(XmlReaderWrapper reader) { try { await SyndicationFeedFormatter.MoveToStartElementAsync(reader); SetDocument(await AtomPub10ServiceDocumentFormatter.ReadCategories(reader, null, delegate () { return this.CreateInlineCategoriesDocument(); }, delegate () { return this.CreateReferencedCategoriesDocument(); }, this.Version, _preserveElementExtensions, _preserveAttributeExtensions, _maxExtensionSize)); } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e); } } private Task WriteDocumentAsync(XmlWriter writer) { // declare the atom10 namespace upfront for compactness writer.WriteAttributeString(Atom10Constants.Atom10Prefix, Atom10FeedFormatter.XmlNsNs, Atom10Constants.Atom10Namespace); return AtomPub10ServiceDocumentFormatter.WriteCategoriesInnerXml(writer, this.Document, null, this.Version); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Diagnostics; using System.Management.Automation.Language; namespace System.Management.Automation { /// <summary> /// Represents a parameter to the Command. /// </summary> [DebuggerDisplay("{ParameterName}")] internal sealed class CommandParameterInternal { private class Parameter { internal IScriptExtent extent; internal string parameterName; internal string parameterText; } private class Argument { internal IScriptExtent extent; internal object value; internal bool splatted; internal bool arrayIsSingleArgumentForNativeCommand; } private Parameter _parameter; private Argument _argument; private bool _spaceAfterParameter; internal bool SpaceAfterParameter { get { return _spaceAfterParameter; } } internal bool ParameterNameSpecified { get { return _parameter != null; } } internal bool ArgumentSpecified { get { return _argument != null; } } internal bool ParameterAndArgumentSpecified { get { return ParameterNameSpecified && ArgumentSpecified; } } /// <summary> /// Gets and sets the string that represents parameter name, which does not include the '-' (dash). /// </summary> internal string ParameterName { get { Diagnostics.Assert(ParameterNameSpecified, "Caller must verify parameter name was specified"); return _parameter.parameterName; } set { Diagnostics.Assert(ParameterNameSpecified, "Caller must verify parameter name was specified"); _parameter.parameterName = value; } } /// <summary> /// The text of the parameter, which typically includes the leading '-' (dash) and, if specified, the trailing ':'. /// </summary> internal string ParameterText { get { Diagnostics.Assert(ParameterNameSpecified, "Caller must verify parameter name was specified"); return _parameter.parameterText; } } /// <summary> /// The extent of the parameter, if one was specified. /// </summary> internal IScriptExtent ParameterExtent { get { return _parameter != null ? _parameter.extent : PositionUtilities.EmptyExtent; } } /// <summary> /// The extent of the optional argument, if one was specified. /// </summary> internal IScriptExtent ArgumentExtent { get { return _argument != null ? _argument.extent : PositionUtilities.EmptyExtent; } } /// <summary> /// The value of the optional argument, if one was specified, otherwise UnboundParameter.Value. /// </summary> internal object ArgumentValue { get { return _argument != null ? _argument.value : UnboundParameter.Value; } } /// <summary> /// If an argument was specified and is to be splatted, returns true, otherwise false. /// </summary> internal bool ArgumentSplatted { get { return _argument != null ? _argument.splatted : false; } } /// <summary> /// If an argument was specified and it was an array literal with no spaces around the /// commas, the value should be passed a single argument with it's commas if the command is /// a native command. /// </summary> internal bool ArrayIsSingleArgumentForNativeCommand { get { return _argument != null ? _argument.arrayIsSingleArgumentForNativeCommand : false; } } /// <summary> /// Set the argument value and extent. /// </summary> internal void SetArgumentValue(IScriptExtent extent, object value) { Diagnostics.Assert(extent != null, "Caller to verify extent argument"); if (_argument == null) { _argument = new Argument(); } _argument.value = value; _argument.extent = extent; } /// <summary> /// The extent to use when reporting generic errors. The argument extent is used, if it is not empty, otherwise /// the parameter extent is used. Some errors may prefer the parameter extent and should not use this method. /// </summary> internal IScriptExtent ErrorExtent { get { return _argument != null && _argument.extent != PositionUtilities.EmptyExtent ? _argument.extent : _parameter != null ? _parameter.extent : PositionUtilities.EmptyExtent; } } #region ctor /// <summary> /// Create a parameter when no argument has been specified. /// </summary> /// <param name="extent">The extent in script of the parameter.</param> /// <param name="parameterName">The parameter name (with no leading dash).</param> /// <param name="parameterText">The text of the parameter, as it did, or would, appear in script.</param> internal static CommandParameterInternal CreateParameter( IScriptExtent extent, string parameterName, string parameterText) { Diagnostics.Assert(extent != null, "Caller to verify extent argument"); return new CommandParameterInternal { _parameter = new Parameter { extent = extent, parameterName = parameterName, parameterText = parameterText } }; } /// <summary> /// Create a positional argument to a command. /// </summary> /// <param name="extent">The extent of the argument value in the script.</param> /// <param name="value">The argument value.</param> /// <param name="splatted">True if the argument value is to be splatted, false otherwise.</param> /// <param name="arrayIsSingleArgumentForNativeCommand">If the command is native, pass the string with commas instead of multiple arguments</param> internal static CommandParameterInternal CreateArgument( IScriptExtent extent, object value, bool splatted = false, bool arrayIsSingleArgumentForNativeCommand = false) { Diagnostics.Assert(extent != null, "Caller to verify extent argument"); return new CommandParameterInternal { _argument = new Argument { extent = extent, value = value, splatted = splatted, arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand } }; } /// <summary> /// Create an named argument, where the parameter name is known. This can happen when: /// * The user uses the ':' syntax, as in /// foo -bar:val /// * Splatting, as in /// $x = @{ bar = val } ; foo @x /// * Via an API - when converting a CommandParameter to CommandParameterInternal. /// * In the parameter binder when it resolves a positional argument /// * Other random places that manually construct command processors and know their arguments. /// </summary> /// <param name="parameterExtent">The extent in script of the parameter.</param> /// <param name="parameterName">The parameter name (with no leading dash).</param> /// <param name="parameterText">The text of the parameter, as it did, or would, appear in script.</param> /// <param name="argumentExtent">The extent of the argument value in the script.</param> /// <param name="value">The argument value.</param> /// <param name="spaceAfterParameter">Used in native commands to correctly handle -foo:bar vs. -foo: bar</param> /// <param name="arrayIsSingleArgumentForNativeCommand">If the command is native, pass the string with commas instead of multiple arguments</param> internal static CommandParameterInternal CreateParameterWithArgument( IScriptExtent parameterExtent, string parameterName, string parameterText, IScriptExtent argumentExtent, object value, bool spaceAfterParameter, bool arrayIsSingleArgumentForNativeCommand = false) { Diagnostics.Assert(parameterExtent != null, "Caller to verify parameterExtent argument"); Diagnostics.Assert(argumentExtent != null, "Caller to verify argumentExtent argument"); return new CommandParameterInternal { _parameter = new Parameter { extent = parameterExtent, parameterName = parameterName, parameterText = parameterText }, _argument = new Argument { extent = argumentExtent, value = value, arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand }, _spaceAfterParameter = spaceAfterParameter }; } #endregion ctor internal bool IsDashQuestion() { return ParameterNameSpecified && (ParameterName.Equals("?", StringComparison.OrdinalIgnoreCase)); } } }
// 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 global::System; using global::System.Linq; using global::System.Reflection; using global::System.Diagnostics; using global::System.Collections; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Reflection.Runtime.Types; using global::System.Reflection.Runtime.General; using global::Internal.Reflection.Core; using global::Internal.Reflection.Core.Execution; using global::Internal.Reflection.Core.NonPortable; using global::Internal.Reflection.Extensibility; using global::Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.CustomAttributes { // // The Runtime's implementation of CustomAttributeData for normal metadata-based attributes // internal sealed class RuntimeNormalCustomAttributeData : RuntimeCustomAttributeData { internal RuntimeNormalCustomAttributeData(ReflectionDomain reflectionDomain, MetadataReader reader, CustomAttributeHandle customAttributeHandle) { _reflectionDomain = reflectionDomain; _reader = reader; _customAttribute = customAttributeHandle.GetCustomAttribute(reader); } public sealed override Type AttributeType { get { Type lazyAttributeType = _lazyAttributeType; if (lazyAttributeType == null) { lazyAttributeType = _lazyAttributeType = _reflectionDomain.Resolve(_reader, _customAttribute.GetAttributeTypeHandle(_reader), new TypeContext(null, null)); } return lazyAttributeType; } } internal sealed override String AttributeTypeString { get { return _customAttribute.GetAttributeTypeHandle(_reader).FormatTypeName(_reader, new TypeContext(null, null), _reflectionDomain); } } // // If throwIfMissingMetadata is false, returns null rather than throwing a MissingMetadataException. // internal sealed override IList<CustomAttributeTypedArgument> GetConstructorArguments(bool throwIfMissingMetadata) { int index = 0; LowLevelList<Handle> lazyCtorTypeHandles = null; LowLevelListWithIList<CustomAttributeTypedArgument> customAttributeTypedArguments = new LowLevelListWithIList<CustomAttributeTypedArgument>(); foreach (FixedArgumentHandle fixedArgumentHandle in _customAttribute.FixedArguments) { CustomAttributeTypedArgument customAttributeTypedArgument = ParseFixedArgument( _reader, fixedArgumentHandle, throwIfMissingMetadata, delegate () { // If we got here, the custom attribute blob lacked type information (this is actually the typical case.) We must fallback to // parsing the constructor's signature to get the type info. if (lazyCtorTypeHandles == null) { IEnumerable<ParameterTypeSignatureHandle> parameterTypeSignatureHandles; HandleType handleType = _customAttribute.Constructor.HandleType; switch (handleType) { case HandleType.QualifiedMethod: parameterTypeSignatureHandles = _customAttribute.Constructor.ToQualifiedMethodHandle(_reader).GetQualifiedMethod(_reader).Method.GetMethod(_reader).Signature.GetMethodSignature(_reader).Parameters; break; case HandleType.MemberReference: parameterTypeSignatureHandles = _customAttribute.Constructor.ToMemberReferenceHandle(_reader).GetMemberReference(_reader).Signature.ToMethodSignatureHandle(_reader).GetMethodSignature(_reader).Parameters; break; default: throw new BadImageFormatException(); } LowLevelList<Handle> ctorTypeHandles = new LowLevelList<Handle>(); foreach (ParameterTypeSignatureHandle parameterTypeSignatureHandle in parameterTypeSignatureHandles) { ctorTypeHandles.Add(parameterTypeSignatureHandle.GetParameterTypeSignature(_reader).Type); } lazyCtorTypeHandles = ctorTypeHandles; } Handle typeHandle = lazyCtorTypeHandles[index]; Exception exception = null; RuntimeType argumentType = _reflectionDomain.TryResolve(_reader, typeHandle, new TypeContext(null, null), ref exception); if (argumentType == null) { if (throwIfMissingMetadata) throw exception; return null; } return argumentType; } ); if (customAttributeTypedArgument.ArgumentType == null) { Debug.Assert(!throwIfMissingMetadata); return null; } customAttributeTypedArguments.Add(customAttributeTypedArgument); index++; } return customAttributeTypedArguments; } // // If throwIfMissingMetadata is false, returns null rather than throwing a MissingMetadataException. // internal sealed override IList<CustomAttributeNamedArgument> GetNamedArguments(bool throwIfMissingMetadata) { LowLevelListWithIList<CustomAttributeNamedArgument> customAttributeNamedArguments = new LowLevelListWithIList<CustomAttributeNamedArgument>(); foreach (NamedArgumentHandle namedArgumentHandle in _customAttribute.NamedArguments) { NamedArgument namedArgument = namedArgumentHandle.GetNamedArgument(_reader); String memberName = namedArgument.Name.GetString(_reader); bool isField = (namedArgument.Flags == NamedArgumentMemberKind.Field); CustomAttributeTypedArgument typedValue = ParseFixedArgument( _reader, namedArgument.Value, throwIfMissingMetadata, delegate () { // We got here because the custom attribute blob did not inclue type information. For named arguments, this is considered illegal metadata // (ECMA always includes type info for named arguments.) throw new BadImageFormatException(); } ); if (typedValue.ArgumentType == null) { Debug.Assert(!throwIfMissingMetadata); return null; } customAttributeNamedArguments.Add(ExtensibleCustomAttributeData.CreateCustomAttributeNamedArgument(this.AttributeType, memberName, isField, typedValue)); } return customAttributeNamedArguments; } // Equals/GetHashCode no need to override (they just implement reference equality but desktop never unified these things.) // // Helper for parsing custom attribute arguments. // // If throwIfMissingMetadata is false, returns default(CustomAttributeTypedArgument) rather than throwing a MissingMetadataException. // private CustomAttributeTypedArgument ParseFixedArgument(MetadataReader reader, FixedArgumentHandle fixedArgumentHandle, bool throwIfMissingMetadata, Func<RuntimeType> getTypeFromConstructor) { FixedArgument fixedArgument = fixedArgumentHandle.GetFixedArgument(reader); RuntimeType argumentType = null; if (fixedArgument.Type.IsNull(reader)) { argumentType = getTypeFromConstructor(); if (argumentType == null) { Debug.Assert(!throwIfMissingMetadata); return default(CustomAttributeTypedArgument); } } else { Exception exception = null; argumentType = _reflectionDomain.TryResolve(reader, fixedArgument.Type, new TypeContext(null, null), ref exception); if (argumentType == null) { if (throwIfMissingMetadata) throw exception; else return default(CustomAttributeTypedArgument); } } Object value; Exception e = fixedArgument.Value.TryParseConstantValue(_reflectionDomain, reader, out value); if (e != null) { if (throwIfMissingMetadata) throw e; else return default(CustomAttributeTypedArgument); } return WrapInCustomAttributeTypedArgument(value, argumentType); } // // Wrap a custom attribute argument (or an element of an array-typed custom attribute argument) in a CustomAttributeTypeArgument structure // for insertion into a CustomAttributeData value. // private CustomAttributeTypedArgument WrapInCustomAttributeTypedArgument(Object value, Type argumentType) { // To support reflection domains other than the execution domain, we'll have to translate argumentType to one of the values off // _reflectionDomain.FoundationTypes rather than using the direct value of value.GetType(). It's unclear how to do this for // enum types. Cross that bridge if ever get to it. Debug.Assert(_reflectionDomain is ExecutionDomain); if (argumentType.Equals(typeof(Object))) { // If the declared attribute type is System.Object, we must report the type based on the runtime value. if (value == null) argumentType = typeof(String); // Why is null reported as System.String? Because that's what the desktop CLR does. else if (value is Type) argumentType = typeof(Type); // value.GetType() will not actually be System.Type - rather it will be some internal implementation type. We only want to report it as System.Type. else argumentType = value.GetType(); } Array arrayValue = value as Array; if (arrayValue != null) { if (!argumentType.IsArray) throw new BadImageFormatException(); Type reportedElementType = argumentType.GetElementType(); LowLevelListWithIList<CustomAttributeTypedArgument> elementTypedArguments = new LowLevelListWithIList<CustomAttributeTypedArgument>(); foreach (Object elementValue in arrayValue) { CustomAttributeTypedArgument elementTypedArgument = WrapInCustomAttributeTypedArgument(elementValue, reportedElementType); elementTypedArguments.Add(elementTypedArgument); } return ExtensibleCustomAttributeData.CreateCustomAttributeTypedArgument(argumentType, new ReadOnlyCollection<CustomAttributeTypedArgument>(elementTypedArguments)); } else { return ExtensibleCustomAttributeData.CreateCustomAttributeTypedArgument(argumentType, value); } } private ReflectionDomain _reflectionDomain; private MetadataReader _reader; private CustomAttribute _customAttribute; private volatile Type _lazyAttributeType; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Animation.Storyboard.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Animation { public partial class Storyboard : ParallelTimeline { #region Methods and constructors public void Begin(System.Windows.FrameworkElement containingObject, System.Windows.FrameworkTemplate frameworkTemplate, bool isControllable) { } public void Begin(System.Windows.FrameworkElement containingObject, System.Windows.FrameworkTemplate frameworkTemplate, HandoffBehavior handoffBehavior, bool isControllable) { } public void Begin(System.Windows.FrameworkElement containingObject, System.Windows.FrameworkTemplate frameworkTemplate) { } public void Begin(System.Windows.FrameworkElement containingObject, bool isControllable) { } public void Begin(System.Windows.FrameworkElement containingObject, HandoffBehavior handoffBehavior, bool isControllable) { } public void Begin(System.Windows.FrameworkContentElement containingObject, HandoffBehavior handoffBehavior, bool isControllable) { } public void Begin() { } public void Begin(System.Windows.FrameworkContentElement containingObject, bool isControllable) { } public void Begin(System.Windows.FrameworkContentElement containingObject) { } public void Begin(System.Windows.FrameworkContentElement containingObject, HandoffBehavior handoffBehavior) { } public void Begin(System.Windows.FrameworkElement containingObject, HandoffBehavior handoffBehavior) { } public void Begin(System.Windows.FrameworkElement containingObject, System.Windows.FrameworkTemplate frameworkTemplate, HandoffBehavior handoffBehavior) { } public void Begin(System.Windows.FrameworkElement containingObject) { } public System.Windows.Media.Animation.Storyboard Clone() { return default(System.Windows.Media.Animation.Storyboard); } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } public Nullable<double> GetCurrentGlobalSpeed(System.Windows.FrameworkContentElement containingObject) { return default(Nullable<double>); } public Nullable<double> GetCurrentGlobalSpeed(System.Windows.FrameworkElement containingObject) { return default(Nullable<double>); } public double GetCurrentGlobalSpeed() { return default(double); } public Nullable<int> GetCurrentIteration(System.Windows.FrameworkContentElement containingObject) { return default(Nullable<int>); } public Nullable<int> GetCurrentIteration(System.Windows.FrameworkElement containingObject) { return default(Nullable<int>); } public int GetCurrentIteration() { return default(int); } public Nullable<double> GetCurrentProgress(System.Windows.FrameworkElement containingObject) { return default(Nullable<double>); } public double GetCurrentProgress() { return default(double); } public Nullable<double> GetCurrentProgress(System.Windows.FrameworkContentElement containingObject) { return default(Nullable<double>); } public ClockState GetCurrentState() { return default(ClockState); } public ClockState GetCurrentState(System.Windows.FrameworkContentElement containingObject) { return default(ClockState); } public ClockState GetCurrentState(System.Windows.FrameworkElement containingObject) { return default(ClockState); } public Nullable<TimeSpan> GetCurrentTime(System.Windows.FrameworkElement containingObject) { return default(Nullable<TimeSpan>); } public TimeSpan GetCurrentTime() { return default(TimeSpan); } public Nullable<TimeSpan> GetCurrentTime(System.Windows.FrameworkContentElement containingObject) { return default(Nullable<TimeSpan>); } public bool GetIsPaused(System.Windows.FrameworkContentElement containingObject) { return default(bool); } public bool GetIsPaused() { return default(bool); } public bool GetIsPaused(System.Windows.FrameworkElement containingObject) { return default(bool); } public static System.Windows.DependencyObject GetTarget(System.Windows.DependencyObject element) { return default(System.Windows.DependencyObject); } public static string GetTargetName(System.Windows.DependencyObject element) { return default(string); } public static System.Windows.PropertyPath GetTargetProperty(System.Windows.DependencyObject element) { return default(System.Windows.PropertyPath); } public void Pause(System.Windows.FrameworkContentElement containingObject) { } public void Pause() { } public void Pause(System.Windows.FrameworkElement containingObject) { } public void Remove(System.Windows.FrameworkElement containingObject) { } public void Remove(System.Windows.FrameworkContentElement containingObject) { } public void Remove() { } public void Resume(System.Windows.FrameworkElement containingObject) { } public void Resume(System.Windows.FrameworkContentElement containingObject) { } public void Resume() { } public void Seek(TimeSpan offset, TimeSeekOrigin origin) { } public void Seek(System.Windows.FrameworkElement containingObject, TimeSpan offset, TimeSeekOrigin origin) { } public void Seek(TimeSpan offset) { } public void Seek(System.Windows.FrameworkContentElement containingObject, TimeSpan offset, TimeSeekOrigin origin) { } public void SeekAlignedToLastTick(System.Windows.FrameworkElement containingObject, TimeSpan offset, TimeSeekOrigin origin) { } public void SeekAlignedToLastTick(TimeSpan offset) { } public void SeekAlignedToLastTick(TimeSpan offset, TimeSeekOrigin origin) { } public void SeekAlignedToLastTick(System.Windows.FrameworkContentElement containingObject, TimeSpan offset, TimeSeekOrigin origin) { } public void SetSpeedRatio(double speedRatio) { } public void SetSpeedRatio(System.Windows.FrameworkContentElement containingObject, double speedRatio) { } public void SetSpeedRatio(System.Windows.FrameworkElement containingObject, double speedRatio) { } public static void SetTarget(System.Windows.DependencyObject element, System.Windows.DependencyObject value) { } public static void SetTargetName(System.Windows.DependencyObject element, string name) { } public static void SetTargetProperty(System.Windows.DependencyObject element, System.Windows.PropertyPath path) { } public void SkipToFill(System.Windows.FrameworkContentElement containingObject) { } public void SkipToFill() { } public void SkipToFill(System.Windows.FrameworkElement containingObject) { } public void Stop(System.Windows.FrameworkContentElement containingObject) { } public void Stop(System.Windows.FrameworkElement containingObject) { } public void Stop() { } public Storyboard() { } #endregion #region Fields public readonly static System.Windows.DependencyProperty TargetNameProperty; public readonly static System.Windows.DependencyProperty TargetProperty; public readonly static System.Windows.DependencyProperty TargetPropertyProperty; #endregion } }
using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Entities.Word; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Signum.Engine.Templating; using Signum.Entities.Templating; using Signum.Entities.Basics; namespace Signum.Engine.Word { public class WordTemplateParameters : TemplateParameters { public WordTemplateParameters(IEntity? entity, CultureInfo culture, Dictionary<QueryToken, ResultColumn> columns, IEnumerable<ResultRow> rows, WordTemplateEntity template, IWordModel? wordModel) : base(entity, culture, columns, rows) { this.Template = template; this.Model = wordModel; } public IWordModel? Model; public WordTemplateEntity Template; public override object GetModel() { if (Model == null) throw new ArgumentException("There is no Model set"); return Model; } } public interface IWordModel { ModifiableEntity UntypedEntity { get; } Entity? ApplicableTo { get; } List<Filter> GetFilters(QueryDescription qd); Pagination GetPagination(); List<Order> GetOrders(QueryDescription queryDescription); } public abstract class WordModel<T> : IWordModel where T : ModifiableEntity { public WordModel(T entity) { this.Entity = entity; } public T Entity { get; set; } public virtual Entity? ApplicableTo => this.Entity as Entity; ModifiableEntity IWordModel.UntypedEntity { get { return Entity; } } public virtual List<Filter> GetFilters(QueryDescription qd) { var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value; if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T))) return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, ((Entity)(ModifiableEntity)Entity).ToLite()) }; throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}"); } public virtual List<Order> GetOrders(QueryDescription queryDescription) { return new List<Order>(); } public virtual Pagination GetPagination() { return new Pagination.All(); } } public class MultiEntityWord : WordModel<MultiEntityModel> { public MultiEntityWord(MultiEntityModel entity) : base(entity) { } public override List<Filter> GetFilters(QueryDescription qd) { return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.IsIn, this.Entity.Entities.ToList()) }; } } public class QueryWord : WordModel<QueryModel> { public QueryWord(QueryModel entity) : base(entity) { } public override List<Filter> GetFilters(QueryDescription qd) { return this.Entity.Filters; } public override Pagination GetPagination() { return this.Entity.Pagination; } public override List<Order> GetOrders(QueryDescription queryDescription) { return this.Entity.Orders; } } public static class WordModelLogic { class WordModelInfo { public object QueryName; public Func<WordTemplateEntity>? DefaultTemplateConstructor; public WordModelInfo(object queryName) { QueryName = queryName; } } static ResetLazy<Dictionary<Lite<WordModelEntity>, List<Lite<WordTemplateEntity>>>> WordModelToTemplates = null!; static Dictionary<Type, WordModelInfo> registeredWordModels = new Dictionary<Type, WordModelInfo>(); public static ResetLazy<Dictionary<Type, WordModelEntity>> WordModelTypeToEntity = null!; public static ResetLazy<Dictionary<WordModelEntity, Type>> WordModelEntityToType = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Schema.Generating += Schema_Generating; sb.Schema.Synchronizing += Schema_Synchronizing; sb.Include<WordModelEntity>() .WithQuery(() => se => new { Entity = se, se.Id, se.FullClassName, }); RegisterWordModel<MultiEntityWord>(null); RegisterWordModel<QueryWord>(null); new Graph<WordTemplateEntity>.ConstructFrom<WordModelEntity>(WordTemplateOperation.CreateWordTemplateFromWordModel) { CanConstruct = se => HasDefaultTemplateConstructor(se) ? null : WordTemplateMessage.NoDefaultTemplateDefined.NiceToString(), Construct = (se, _) => CreateDefaultTemplate(se)!.Save() }.Register(); WordModelToTemplates = sb.GlobalLazy(() => ( from et in Database.Query<WordTemplateEntity>() where et.Model != null select new { swe = et.Model, et = et.ToLite() }) .GroupToDictionary(pair => pair.swe!.ToLite(), pair => pair.et!), new InvalidateWith(typeof(WordModelEntity), typeof(WordTemplateEntity))); WordModelTypeToEntity = sb.GlobalLazy(() => { var dbWordModels = Database.RetrieveAll<WordModelEntity>(); return EnumerableExtensions.JoinRelaxed( dbWordModels, registeredWordModels.Keys, swr => swr.FullClassName, type => type.FullName, (swr, type) => KeyValuePair.Create(type, swr), "caching " + nameof(WordModelEntity)).ToDictionary(); }, new InvalidateWith(typeof(WordModelEntity))); sb.Schema.Initializing += () => WordModelTypeToEntity.Load(); WordModelEntityToType = sb.GlobalLazy(() => WordModelTypeToEntity.Value.Inverse(), new InvalidateWith(typeof(WordModelEntity))); } } internal static bool HasDefaultTemplateConstructor(WordModelEntity wordModel) { WordModelInfo info = registeredWordModels.GetOrThrow(wordModel.ToType()); return info.DefaultTemplateConstructor != null; } internal static WordTemplateEntity? CreateDefaultTemplate(WordModelEntity wordModel) { WordModelInfo info = registeredWordModels.GetOrThrow(wordModel.ToType()); if (info.DefaultTemplateConstructor == null) return null; WordTemplateEntity template = info.DefaultTemplateConstructor(); if (template.Name == null) template.Name = wordModel.FullClassName; template.Model = wordModel; template.Query = QueryLogic.GetQueryEntity(info.QueryName); template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName)); return template; } public static byte[] CreateReport(this IWordModel model, bool avoidConversion = false) { return model.CreateReport(out WordTemplateEntity rubish, avoidConversion); } public static byte[] CreateReport(this IWordModel model, out WordTemplateEntity template, bool avoidConversion = false, WordTemplateLogic.FileNameBox? fileNameBox = null) { WordModelEntity wordModel = GetWordModelEntity(model.GetType()); template = GetDefaultTemplate(wordModel, model.UntypedEntity as Entity); return template.ToLite().CreateReport(null, model, avoidConversion, fileNameBox); } public static FileContent CreateReportFileContent(this IWordModel model, bool avoidConversion = false) { var box = new WordTemplateLogic.FileNameBox(); var bytes = model.CreateReport(out WordTemplateEntity rubish, avoidConversion, box); return new FileContent(box.FileName!, bytes); } public static WordModelEntity GetWordModelEntity(Type type) { return WordModelTypeToEntity.Value.GetOrThrow(type); } public static WordTemplateEntity GetDefaultTemplate(WordModelEntity model, Entity? entity) { var templates = WordModelToTemplates.Value.TryGetC(model.ToLite()).EmptyIfNull().Select(a => WordTemplateLogic.WordTemplatesLazy.Value.GetOrThrow(a)); if (templates.IsNullOrEmpty() && HasDefaultTemplateConstructor(model)) { using (ExecutionMode.Global()) using (OperationLogic.AllowSave<WordTemplateEntity>()) using (Transaction tr = Transaction.ForceNew()) { var template = CreateDefaultTemplate(model)!; template.Save(); return tr.Commit(template); } } var isAllowed = Schema.Current.GetInMemoryFilter<WordTemplateEntity>(userInterface: false); var candidates = templates.Where(isAllowed).Where(t => t.IsApplicable(entity)); return GetTemplate(candidates, model, CultureInfo.CurrentCulture) ?? GetTemplate(candidates, model, CultureInfo.CurrentCulture.Parent) ?? candidates.SingleEx( () => $"No active WordTemplate for {registeredWordModels} in {CultureInfo.CurrentCulture} or {CultureInfo.CurrentCulture.Parent}", () => $"More than one active WordTemplate for {registeredWordModels} in {CultureInfo.CurrentCulture} or {CultureInfo.CurrentCulture.Parent}"); } private static WordTemplateEntity? GetTemplate(IEnumerable<WordTemplateEntity> candidates, WordModelEntity model, CultureInfo culture) { return candidates .Where(a => a.Culture.Name == culture.Name) .SingleOrDefaultEx(() => $"More than one active WordTemplate for WordModel {model} in {culture.Name} found"); } static SqlPreCommand? Schema_Generating() { Table table = Schema.Current.Table<WordModelEntity>(); return (from ei in GenerateTemplates() select table.InsertSqlSync(ei)).Combine(Spacing.Simple); } internal static List<WordModelEntity> GenerateTemplates() { var list = (from type in registeredWordModels.Keys select new WordModelEntity { FullClassName = type.FullName! }).ToList(); return list; } static readonly string wordModelReplacementKey = "WordModel"; static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { Table table = Schema.Current.Table<WordModelEntity>(); Dictionary<string, WordModelEntity> should = GenerateTemplates().ToDictionary(s => s.FullClassName); Dictionary<string, WordModelEntity> old = Administrator.TryRetrieveAll<WordModelEntity>(replacements).ToDictionary(c => c.FullClassName); replacements.AskForReplacements( old.Keys.ToHashSet(), should.Keys.ToHashSet(), wordModelReplacementKey); Dictionary<string, WordModelEntity> current = replacements.ApplyReplacementsToOld(old, wordModelReplacementKey); using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScript(Spacing.Double, should, current, createNew: (tn, s) => table.InsertSqlSync(s), removeOld: (tn, c) => table.DeleteSqlSync(c, swt => swt.FullClassName == c.FullClassName), mergeBoth: (tn, s, c) => { var oldClassName = c.FullClassName; c.FullClassName = s.FullClassName; return table.UpdateSqlSync(c, swt => swt.FullClassName == oldClassName); }); } public static void RegisterWordModel<T>(Func<WordTemplateEntity>? defaultTemplateConstructor, object? queryName = null) where T : IWordModel { RegisterWordModel(typeof(T), defaultTemplateConstructor, queryName); } public static void RegisterWordModel(Type wordModelType, Func<WordTemplateEntity>? defaultTemplateConstructor = null, object? queryName = null) { registeredWordModels[wordModelType] = new WordModelInfo(queryName ?? GetEntityType(wordModelType)) { DefaultTemplateConstructor = defaultTemplateConstructor, }; } public static Type GetEntityType(Type wordModelType) { var baseType = wordModelType.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(WordModel<>))); if (baseType != null) { return baseType.GetGenericArguments()[0]; } throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterWordModel".FormatWith(wordModelType.TypeName())); } public static Type ToType(this WordModelEntity modelEntity) { return WordModelEntityToType.Value.GetOrThrow(modelEntity); } public static bool RequiresExtraParameters(WordModelEntity modelEntity) { return GetEntityConstructor(modelEntity.ToType()) == null; } public static ConstructorInfo? GetEntityConstructor(Type wordModelType) { var entityType = GetEntityType(wordModelType); return (from ci in wordModelType.GetConstructors() let pi = ci.GetParameters().Only() where pi != null && pi.ParameterType == entityType select ci).SingleOrDefaultEx(); } public static IWordModel CreateDefaultWordModel(WordModelEntity wordModel, ModifiableEntity? entity) { return (IWordModel)WordModelLogic.GetEntityConstructor(wordModel.ToType())!.Invoke(new[] { entity }); } } }
// 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.Xml; using System.Diagnostics; using System.Text; namespace System.Xml.Schema { /// <summary> /// This enum specifies what format should be used when converting string to XsdDateTime /// </summary> [Flags] internal enum XsdDateTimeFlags { DateTime = 0x01, Time = 0x02, Date = 0x04, GYearMonth = 0x08, GYear = 0x10, GMonthDay = 0x20, GDay = 0x40, GMonth = 0x80, AllXsd = 0xFF //All still does not include the XDR formats } /// <summary> /// This structure extends System.DateTime to support timeInTicks zone and Gregorian types scomponents of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDateTime { // DateTime is being used as an internal representation only // Casting XsdDateTime to DateTime might return a different value private DateTime dt; // Additional information that DateTime is not preserving // Information is stored in the following format: // Bits Info // 31-24 DateTimeTypeCode // 23-16 XsdDateTimeKind // 15-8 Zone Hours // 7-0 Zone Minutes private uint extra; // Subset of XML Schema types XsdDateTime represents enum DateTimeTypeCode { DateTime, Time, Date, GYearMonth, GYear, GMonthDay, GDay, GMonth, } // Internal representation of DateTimeKind enum XsdDateTimeKind { Unspecified, Zulu, LocalWestOfZulu, // GMT-1..14, N..Y LocalEastOfZulu // GMT+1..14, A..M } // Masks and shifts used for packing and unpacking extra private const uint TypeMask = 0xFF000000; private const uint KindMask = 0x00FF0000; private const uint ZoneHourMask = 0x0000FF00; private const uint ZoneMinuteMask = 0x000000FF; private const int TypeShift = 24; private const int KindShift = 16; private const int ZoneHourShift = 8; // Maximum number of fraction digits; private const short maxFractionDigits = 7; static readonly int Lzyyyy = "yyyy".Length; static readonly int Lzyyyy_ = "yyyy-".Length; static readonly int Lzyyyy_MM = "yyyy-MM".Length; static readonly int Lzyyyy_MM_ = "yyyy-MM-".Length; static readonly int Lzyyyy_MM_dd = "yyyy-MM-dd".Length; static readonly int Lzyyyy_MM_ddT = "yyyy-MM-ddT".Length; static readonly int LzHH = "HH".Length; static readonly int LzHH_ = "HH:".Length; static readonly int LzHH_mm = "HH:mm".Length; static readonly int LzHH_mm_ = "HH:mm:".Length; static readonly int LzHH_mm_ss = "HH:mm:ss".Length; static readonly int Lz_ = "-".Length; static readonly int Lz_zz = "-zz".Length; static readonly int Lz_zz_ = "-zz:".Length; static readonly int Lz_zz_zz = "-zz:zz".Length; static readonly int Lz__ = "--".Length; static readonly int Lz__mm = "--MM".Length; static readonly int Lz__mm_ = "--MM-".Length; static readonly int Lz__mm__ = "--MM--".Length; static readonly int Lz__mm_dd = "--MM-dd".Length; static readonly int Lz___ = "---".Length; static readonly int Lz___dd = "---dd".Length; /// <summary> /// Constructs an XsdDateTime from a string using specific format. /// </summary> public XsdDateTime(string text, XsdDateTimeFlags kinds) : this() { Parser parser = new Parser(); if (!parser.Parse(text, kinds)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds)); } InitiateXsdDateTime(parser); } private void InitiateXsdDateTime(Parser parser) { dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second); if (parser.fraction != 0) { dt = dt.AddTicks(parser.fraction); } extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute); } /// <summary> /// Constructs an XsdDateTime from a DateTime. /// </summary> public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds) { Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set."); dt = dateTime; DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1); int zoneHour = 0; int zoneMinute = 0; XsdDateTimeKind kind; switch (dateTime.Kind) { case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break; case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break; default: { Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind); TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime); if (utcOffset.Ticks < 0) { kind = XsdDateTimeKind.LocalWestOfZulu; zoneHour = -utcOffset.Hours; zoneMinute = -utcOffset.Minutes; } else { kind = XsdDateTimeKind.LocalEastOfZulu; zoneHour = utcOffset.Hours; zoneMinute = utcOffset.Minutes; } break; } } extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute); } // Constructs an XsdDateTime from a DateTimeOffset public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime) { } public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds) { Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set."); dt = dateTimeOffset.DateTime; TimeSpan zoneOffset = dateTimeOffset.Offset; DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1); XsdDateTimeKind kind; if (zoneOffset.TotalMinutes < 0) { zoneOffset = zoneOffset.Negate(); kind = XsdDateTimeKind.LocalWestOfZulu; } else if (zoneOffset.TotalMinutes > 0) { kind = XsdDateTimeKind.LocalEastOfZulu; } else { kind = XsdDateTimeKind.Zulu; } extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes); } /// <summary> /// Returns auxiliary enumeration of XSD date type /// </summary> private DateTimeTypeCode InternalTypeCode { get { return (DateTimeTypeCode)((extra & TypeMask) >> TypeShift); } } /// <summary> /// Returns geographical "position" of the value /// </summary> private XsdDateTimeKind InternalKind { get { return (XsdDateTimeKind)((extra & KindMask) >> KindShift); } } /// <summary> /// Returns the year part of XsdDateTime /// The returned value is integer between 1 and 9999 /// </summary> public int Year { get { return dt.Year; } } /// <summary> /// Returns the month part of XsdDateTime /// The returned value is integer between 1 and 12 /// </summary> public int Month { get { return dt.Month; } } /// <summary> /// Returns the day of the month part of XsdDateTime /// The returned value is integer between 1 and 31 /// </summary> public int Day { get { return dt.Day; } } /// <summary> /// Returns the hour part of XsdDateTime /// The returned value is integer between 0 and 23 /// </summary> public int Hour { get { return dt.Hour; } } /// <summary> /// Returns the minute part of XsdDateTime /// The returned value is integer between 0 and 60 /// </summary> public int Minute { get { return dt.Minute; } } /// <summary> /// Returns the second part of XsdDateTime /// The returned value is integer between 0 and 60 /// </summary> public int Second { get { return dt.Second; } } /// <summary> /// Returns number of ticks in the fraction of the second /// The returned value is integer between 0 and 9999999 /// </summary> public int Fraction { get { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); } } /// <summary> /// Returns the hour part of the time zone /// The returned value is integer between -13 and 13 /// </summary> public int ZoneHour { get { uint result = (extra & ZoneHourMask) >> ZoneHourShift; return (int)result; } } /// <summary> /// Returns the minute part of the time zone /// The returned value is integer between 0 and 60 /// </summary> public int ZoneMinute { get { uint result = (extra & ZoneMinuteMask); return (int)result; } } /// <summary> /// Cast to DateTime /// The following table describes the behaviors of getting the default value /// when a certain year/month/day values are missing. /// /// An "X" means that the value exists. And "--" means that value is missing. /// /// Year Month Day => ResultYear ResultMonth ResultDay Note /// /// X X X Parsed year Parsed month Parsed day /// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month. /// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year. /// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year. /// /// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year. /// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day. /// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month. /// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date. /// </summary> public static implicit operator DateTime(XsdDateTime xdt) { DateTime result; switch (xdt.InternalTypeCode) { case DateTimeTypeCode.GMonth: case DateTimeTypeCode.GDay: result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day); break; case DateTimeTypeCode.Time: //back to DateTime.Now DateTime currentDateTime = DateTime.Now; TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day); result = xdt.dt.Add(addDiff); break; default: result = xdt.dt; break; } long ticks; switch (xdt.InternalKind) { case XsdDateTimeKind.Zulu: // set it to UTC result = new DateTime(result.Ticks, DateTimeKind.Utc); break; case XsdDateTimeKind.LocalEastOfZulu: // Adjust to UTC and then convert to local in the current time zone ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks; if (ticks < DateTime.MinValue.Ticks) { // Underflow. Return the DateTime as local time directly ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks; if (ticks < DateTime.MinValue.Ticks) ticks = DateTime.MinValue.Ticks; return new DateTime(ticks, DateTimeKind.Local); } result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); break; case XsdDateTimeKind.LocalWestOfZulu: // Adjust to UTC and then convert to local in the current time zone ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks; if (ticks > DateTime.MaxValue.Ticks) { // Overflow. Return the DateTime as local time directly ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks; if (ticks > DateTime.MaxValue.Ticks) ticks = DateTime.MaxValue.Ticks; return new DateTime(ticks, DateTimeKind.Local); } result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); break; default: break; } return result; } public static implicit operator DateTimeOffset(XsdDateTime xdt) { DateTime dt; switch (xdt.InternalTypeCode) { case DateTimeTypeCode.GMonth: case DateTimeTypeCode.GDay: dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day); break; case DateTimeTypeCode.Time: //back to DateTime.Now DateTime currentDateTime = DateTime.Now; TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day); dt = xdt.dt.Add(addDiff); break; default: dt = xdt.dt; break; } DateTimeOffset result; switch (xdt.InternalKind) { case XsdDateTimeKind.LocalEastOfZulu: result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0)); break; case XsdDateTimeKind.LocalWestOfZulu: result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0)); break; case XsdDateTimeKind.Zulu: result = new DateTimeOffset(dt, new TimeSpan(0)); break; case XsdDateTimeKind.Unspecified: default: result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt)); break; } return result; } /// <summary> /// Serialization to a string /// </summary> public override string ToString() { StringBuilder sb = new StringBuilder(64); char[] text; switch (InternalTypeCode) { case DateTimeTypeCode.DateTime: PrintDate(sb); sb.Append('T'); PrintTime(sb); break; case DateTimeTypeCode.Time: PrintTime(sb); break; case DateTimeTypeCode.Date: PrintDate(sb); break; case DateTimeTypeCode.GYearMonth: text = new char[Lzyyyy_MM]; IntToCharArray(text, 0, Year, 4); text[Lzyyyy] = '-'; ShortToCharArray(text, Lzyyyy_, Month); sb.Append(text); break; case DateTimeTypeCode.GYear: text = new char[Lzyyyy]; IntToCharArray(text, 0, Year, 4); sb.Append(text); break; case DateTimeTypeCode.GMonthDay: text = new char[Lz__mm_dd]; text[0] = '-'; text[Lz_] = '-'; ShortToCharArray(text, Lz__, Month); text[Lz__mm] = '-'; ShortToCharArray(text, Lz__mm_, Day); sb.Append(text); break; case DateTimeTypeCode.GDay: text = new char[Lz___dd]; text[0] = '-'; text[Lz_] = '-'; text[Lz__] = '-'; ShortToCharArray(text, Lz___, Day); sb.Append(text); break; case DateTimeTypeCode.GMonth: text = new char[Lz__mm__]; text[0] = '-'; text[Lz_] = '-'; ShortToCharArray(text, Lz__, Month); text[Lz__mm] = '-'; text[Lz__mm_] = '-'; sb.Append(text); break; } PrintZone(sb); return sb.ToString(); } // Serialize year, month and day private void PrintDate(StringBuilder sb) { char[] text = new char[Lzyyyy_MM_dd]; IntToCharArray(text, 0, Year, 4); text[Lzyyyy] = '-'; ShortToCharArray(text, Lzyyyy_, Month); text[Lzyyyy_MM] = '-'; ShortToCharArray(text, Lzyyyy_MM_, Day); sb.Append(text); } // Serialize hour, minute, second and fraction private void PrintTime(StringBuilder sb) { char[] text = new char[LzHH_mm_ss]; ShortToCharArray(text, 0, Hour); text[LzHH] = ':'; ShortToCharArray(text, LzHH_, Minute); text[LzHH_mm] = ':'; ShortToCharArray(text, LzHH_mm_, Second); sb.Append(text); int fraction = Fraction; if (fraction != 0) { int fractionDigits = maxFractionDigits; while (fraction % 10 == 0) { fractionDigits--; fraction /= 10; } text = new char[fractionDigits + 1]; text[0] = '.'; IntToCharArray(text, 1, fraction, fractionDigits); sb.Append(text); } } // Serialize time zone private void PrintZone(StringBuilder sb) { char[] text; switch (InternalKind) { case XsdDateTimeKind.Zulu: sb.Append('Z'); break; case XsdDateTimeKind.LocalWestOfZulu: text = new char[Lz_zz_zz]; text[0] = '-'; ShortToCharArray(text, Lz_, ZoneHour); text[Lz_zz] = ':'; ShortToCharArray(text, Lz_zz_, ZoneMinute); sb.Append(text); break; case XsdDateTimeKind.LocalEastOfZulu: text = new char[Lz_zz_zz]; text[0] = '+'; ShortToCharArray(text, Lz_, ZoneHour); text[Lz_zz] = ':'; ShortToCharArray(text, Lz_zz_, ZoneMinute); sb.Append(text); break; default: // do nothing break; } } // Serialize integer into character array starting with index [start]. // Number of digits is set by [digits] private void IntToCharArray(char[] text, int start, int value, int digits) { while (digits-- != 0) { text[start + digits] = (char)(value % 10 + '0'); value /= 10; } } // Serialize two digit integer into character array starting with index [start]. private void ShortToCharArray(char[] text, int start, int value) { text[start] = (char)(value / 10 + '0'); text[start + 1] = (char)(value % 10 + '0'); } // Parsing string according to XML schema spec struct Parser { private const int leapYear = 1904; private const int firstMonth = 1; private const int firstDay = 1; public DateTimeTypeCode typeCode; public int year; public int month; public int day; public int hour; public int minute; public int second; public int fraction; public XsdDateTimeKind kind; public int zoneHour; public int zoneMinute; private string text; private int length; public bool Parse(string text, XsdDateTimeFlags kinds) { this.text = text; this.length = text.Length; // Skip leading withitespace int start = 0; while (start < length && char.IsWhiteSpace(text[start])) { start++; } // Choose format starting from the most common and trying not to reparse the same thing too many times if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date)) { if (ParseDate(start)) { if (Test(kinds, XsdDateTimeFlags.DateTime)) { if (ParseChar(start + Lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + Lzyyyy_MM_ddT)) { typeCode = DateTimeTypeCode.DateTime; return true; } } if (Test(kinds, XsdDateTimeFlags.Date)) { if (ParseZoneAndWhitespace(start + Lzyyyy_MM_dd)) { typeCode = DateTimeTypeCode.Date; return true; } } } } if (Test(kinds, XsdDateTimeFlags.Time)) { if (ParseTimeAndZoneAndWhitespace(start)) { //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time year = leapYear; month = firstMonth; day = firstDay; typeCode = DateTimeTypeCode.Time; return true; } } if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear)) { if (Parse4Dig(start, ref year) && 1 <= year) { if (Test(kinds, XsdDateTimeFlags.GYearMonth)) { if ( ParseChar(start + Lzyyyy, '-') && Parse2Dig(start + Lzyyyy_, ref month) && 1 <= month && month <= 12 && ParseZoneAndWhitespace(start + Lzyyyy_MM) ) { day = firstDay; typeCode = DateTimeTypeCode.GYearMonth; return true; } } if (Test(kinds, XsdDateTimeFlags.GYear)) { if (ParseZoneAndWhitespace(start + Lzyyyy)) { month = firstMonth; day = firstDay; typeCode = DateTimeTypeCode.GYear; return true; } } } } if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth)) { if ( ParseChar(start, '-') && ParseChar(start + Lz_, '-') && Parse2Dig(start + Lz__, ref month) && 1 <= month && month <= 12 ) { if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + Lz__mm, '-')) { if ( Parse2Dig(start + Lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) && ParseZoneAndWhitespace(start + Lz__mm_dd) ) { year = leapYear; typeCode = DateTimeTypeCode.GMonthDay; return true; } } if (Test(kinds, XsdDateTimeFlags.GMonth)) { if (ParseZoneAndWhitespace(start + Lz__mm) || (ParseChar(start + Lz__mm, '-') && ParseChar(start + Lz__mm_, '-') && ParseZoneAndWhitespace(start + Lz__mm__))) { year = leapYear; day = firstDay; typeCode = DateTimeTypeCode.GMonth; return true; } } } } if (Test(kinds, XsdDateTimeFlags.GDay)) { if ( ParseChar(start, '-') && ParseChar(start + Lz_, '-') && ParseChar(start + Lz__, '-') && Parse2Dig(start + Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) && ParseZoneAndWhitespace(start + Lz___dd) ) { year = leapYear; month = firstMonth; typeCode = DateTimeTypeCode.GDay; return true; } } return false; } private bool ParseDate(int start) { return Parse4Dig(start, ref year) && 1 <= year && ParseChar(start + Lzyyyy, '-') && Parse2Dig(start + Lzyyyy_, ref month) && 1 <= month && month <= 12 && ParseChar(start + Lzyyyy_MM, '-') && Parse2Dig(start + Lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month); } private bool ParseTimeAndZoneAndWhitespace(int start) { if (ParseTime(ref start)) { if (ParseZoneAndWhitespace(start)) { return true; } } return false; } static int[] Power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 }; private bool ParseTime(ref int start) { if ( Parse2Dig(start, ref hour) && hour < 24 && ParseChar(start + LzHH, ':') && Parse2Dig(start + LzHH_, ref minute) && minute < 60 && ParseChar(start + LzHH_mm, ':') && Parse2Dig(start + LzHH_mm_, ref second) && second < 60 ) { start += LzHH_mm_ss; if (ParseChar(start, '.')) { // Parse factional part of seconds // We allow any number of digits, but keep only first 7 this.fraction = 0; int fractionDigits = 0; int round = 0; while (++start < length) { int d = text[start] - '0'; if (9u < (uint)d) { // d < 0 || 9 < d break; } if (fractionDigits < maxFractionDigits) { this.fraction = (this.fraction * 10) + d; } else if (fractionDigits == maxFractionDigits) { if (5 < d) { round = 1; } else if (d == 5) { round = -1; } } else if (round < 0 && d != 0) { round = 1; } fractionDigits++; } if (fractionDigits < maxFractionDigits) { if (fractionDigits == 0) { return false; // cannot end with . } fraction *= Power10[maxFractionDigits - fractionDigits]; } else { if (round < 0) { round = fraction & 1; } fraction += round; } } return true; } // cleanup - conflict with gYear hour = 0; return false; } private bool ParseZoneAndWhitespace(int start) { if (start < length) { char ch = text[start]; if (ch == 'Z' || ch == 'z') { kind = XsdDateTimeKind.Zulu; start++; } else if (start + 5 < length) { if ( Parse2Dig(start + Lz_, ref zoneHour) && zoneHour <= 99 && ParseChar(start + Lz_zz, ':') && Parse2Dig(start + Lz_zz_, ref zoneMinute) && zoneMinute <= 99 ) { if (ch == '-') { kind = XsdDateTimeKind.LocalWestOfZulu; start += Lz_zz_zz; } else if (ch == '+') { kind = XsdDateTimeKind.LocalEastOfZulu; start += Lz_zz_zz; } } } } while (start < length && char.IsWhiteSpace(text[start])) { start++; } return start == length; } private bool Parse4Dig(int start, ref int num) { if (start + 3 < length) { int d4 = text[start] - '0'; int d3 = text[start + 1] - '0'; int d2 = text[start + 2] - '0'; int d1 = text[start + 3] - '0'; if (0 <= d4 && d4 < 10 && 0 <= d3 && d3 < 10 && 0 <= d2 && d2 < 10 && 0 <= d1 && d1 < 10 ) { num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1; return true; } } return false; } private bool Parse2Dig(int start, ref int num) { if (start + 1 < length) { int d2 = text[start] - '0'; int d1 = text[start + 1] - '0'; if (0 <= d2 && d2 < 10 && 0 <= d1 && d1 < 10 ) { num = d2 * 10 + d1; return true; } } return false; } private bool ParseChar(int start, char ch) { return start < length && text[start] == ch; } private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right) { return (left & right) != 0; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; #if UNITY_EDITOR using UnityEditor; #endif namespace Pathfinding { /** Connects two nodes via two intermediate point nodes. * In contrast to the NodeLink component, this link type will not connect the nodes directly * instead it will create two point nodes at the start and end position of this link and connect * through those nodes. * * If the closest node to this object is called A and the closest node to the end transform is called * D, then it will create one point node at this object's position (call it B) and one point node at * the position of the end transform (call it C), it will then connect A to B, B to C and C to D. * * This link type is possible to detect while following since it has these special point nodes in the middle. * The link corresponding to one of those intermediate nodes can be retrieved using the #GetNodeLink method * which can be of great use if you want to, for example, play a link specific animation when reaching the link. * * \see The example scene RecastExample2 contains a few links which you can take a look at to see how they are used. */ [AddComponentMenu("Pathfinding/Link2")] [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_node_link2.php")] public class NodeLink2 : GraphModifier { protected static Dictionary<GraphNode, NodeLink2> reference = new Dictionary<GraphNode, NodeLink2>(); public static NodeLink2 GetNodeLink (GraphNode node) { NodeLink2 v; reference.TryGetValue(node, out v); return v; } /** End position of the link */ public Transform end; /** The connection will be this times harder/slower to traverse. * Note that values lower than 1 will not always make the pathfinder choose this path instead of another path even though this one should * lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether. */ public float costFactor = 1.0f; /** Make a one-way connection */ public bool oneWay = false; public Transform StartTransform { get { return transform; } } public Transform EndTransform { get { return end; } } public PointNode startNode { get; private set; } public PointNode endNode { get; private set; } GraphNode connectedNode1, connectedNode2; Vector3 clamped1, clamped2; bool postScanCalled = false; [System.Obsolete("Use startNode instead (lowercase s)")] public GraphNode StartNode { get { return startNode; } } [System.Obsolete("Use endNode instead (lowercase e)")] public GraphNode EndNode { get { return endNode; } } public override void OnPostScan () { InternalOnPostScan(); } public void InternalOnPostScan () { if (EndTransform == null || StartTransform == null) return; if (AstarPath.active.astarData.pointGraph == null) { var graph = AstarPath.active.astarData.AddGraph(typeof(PointGraph)) as PointGraph; graph.name = "PointGraph (used for node links)"; } if (startNode != null) reference.Remove(startNode); if (endNode != null) reference.Remove(endNode); // Create new nodes on the point graph startNode = AstarPath.active.astarData.pointGraph.AddNode((Int3)StartTransform.position); endNode = AstarPath.active.astarData.pointGraph.AddNode((Int3)EndTransform.position); connectedNode1 = null; connectedNode2 = null; if (startNode == null || endNode == null) { startNode = null; endNode = null; return; } postScanCalled = true; reference[startNode] = this; reference[endNode] = this; Apply(true); } public override void OnGraphsPostUpdate () { // Don't bother running it now since OnPostScan will be called later anyway if (AstarPath.active.isScanning) return; if (connectedNode1 != null && connectedNode1.Destroyed) { connectedNode1 = null; } if (connectedNode2 != null && connectedNode2.Destroyed) { connectedNode2 = null; } if (!postScanCalled) { OnPostScan(); } else { Apply(false); } } protected override void OnEnable () { base.OnEnable(); if (Application.isPlaying && AstarPath.active != null && AstarPath.active.astarData != null && AstarPath.active.astarData.pointGraph != null && !AstarPath.active.isScanning) { // Call OnGraphsPostUpdate as soon as possible when it is safe to update the graphs AstarPath.RegisterSafeUpdate(OnGraphsPostUpdate); } } protected override void OnDisable () { base.OnDisable(); postScanCalled = false; if (startNode != null) reference.Remove(startNode); if (endNode != null) reference.Remove(endNode); if (startNode != null && endNode != null) { startNode.RemoveConnection(endNode); endNode.RemoveConnection(startNode); if (connectedNode1 != null && connectedNode2 != null) { startNode.RemoveConnection(connectedNode1); connectedNode1.RemoveConnection(startNode); endNode.RemoveConnection(connectedNode2); connectedNode2.RemoveConnection(endNode); } } } void RemoveConnections (GraphNode node) { //TODO, might be better to replace connection node.ClearConnections(true); } [ContextMenu("Recalculate neighbours")] void ContextApplyForce () { if (Application.isPlaying) { Apply(true); if (AstarPath.active != null) { AstarPath.active.FloodFill(); } } } public void Apply (bool forceNewCheck) { //TODO //This function assumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something) NNConstraint nn = NNConstraint.None; int graph = (int)startNode.GraphIndex; //Search all graphs but the one which start and end nodes are on nn.graphMask = ~(1 << graph); startNode.SetPosition((Int3)StartTransform.position); endNode.SetPosition((Int3)EndTransform.position); RemoveConnections(startNode); RemoveConnections(endNode); uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor); startNode.AddConnection(endNode, cost); endNode.AddConnection(startNode, cost); if (connectedNode1 == null || forceNewCheck) { NNInfo n1 = AstarPath.active.GetNearest(StartTransform.position, nn); connectedNode1 = n1.node; clamped1 = n1.clampedPosition; } if (connectedNode2 == null || forceNewCheck) { NNInfo n2 = AstarPath.active.GetNearest(EndTransform.position, nn); connectedNode2 = n2.node; clamped2 = n2.clampedPosition; } if (connectedNode2 == null || connectedNode1 == null) return; //Add connections between nodes, or replace old connections if existing connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor)); if (!oneWay) connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor)); if (!oneWay) startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor)); endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor)); } void DrawCircle (Vector3 o, float r, int detail, Color col) { Vector3 prev = new Vector3(Mathf.Cos(0)*r, 0, Mathf.Sin(0)*r) + o; Gizmos.color = col; for (int i = 0; i <= detail; i++) { float t = (i*Mathf.PI*2f)/detail; Vector3 c = new Vector3(Mathf.Cos(t)*r, 0, Mathf.Sin(t)*r) + o; Gizmos.DrawLine(prev, c); prev = c; } } private readonly static Color GizmosColor = new Color(206.0f/255.0f, 136.0f/255.0f, 48.0f/255.0f, 0.5f); private readonly static Color GizmosColorSelected = new Color(235.0f/255.0f, 123.0f/255.0f, 32.0f/255.0f, 1.0f); void DrawGizmoBezier (Vector3 p1, Vector3 p2) { Vector3 dir = p2-p1; if (dir == Vector3.zero) return; Vector3 normal = Vector3.Cross(Vector3.up, dir); Vector3 normalUp = Vector3.Cross(dir, normal); normalUp = normalUp.normalized; normalUp *= dir.magnitude*0.1f; Vector3 p1c = p1+normalUp; Vector3 p2c = p2+normalUp; Vector3 prev = p1; for (int i = 1; i <= 20; i++) { float t = i/20.0f; Vector3 p = AstarSplines.CubicBezier(p1, p1c, p2c, p2, t); Gizmos.DrawLine(prev, p); prev = p; } } public virtual void OnDrawGizmosSelected () { OnDrawGizmos(true); } public void OnDrawGizmos () { OnDrawGizmos(false); } public void OnDrawGizmos (bool selected) { Color col = selected ? GizmosColorSelected : GizmosColor; if (StartTransform != null) { DrawCircle(StartTransform.position, 0.4f, 10, col); } if (EndTransform != null) { DrawCircle(EndTransform.position, 0.4f, 10, col); } if (StartTransform != null && EndTransform != null) { Gizmos.color = col; DrawGizmoBezier(StartTransform.position, EndTransform.position); if (selected) { Vector3 cross = Vector3.Cross(Vector3.up, (EndTransform.position-StartTransform.position)).normalized; DrawGizmoBezier(StartTransform.position+cross*0.1f, EndTransform.position+cross*0.1f); DrawGizmoBezier(StartTransform.position-cross*0.1f, EndTransform.position-cross*0.1f); } } } internal static void SerializeReferences (Pathfinding.Serialization.GraphSerializationContext ctx) { var links = GetModifiersOfType<NodeLink2>(); ctx.writer.Write(links.Count); foreach (var link in links) { ctx.writer.Write(link.uniqueID); ctx.SerializeNodeReference(link.startNode); ctx.SerializeNodeReference(link.endNode); ctx.SerializeNodeReference(link.connectedNode1); ctx.SerializeNodeReference(link.connectedNode2); ctx.SerializeVector3(link.clamped1); ctx.SerializeVector3(link.clamped2); ctx.writer.Write(link.postScanCalled); } } internal static void DeserializeReferences (Pathfinding.Serialization.GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); for (int i = 0; i < count; i++) { var linkID = ctx.reader.ReadUInt64(); var startNode = ctx.DeserializeNodeReference(); var endNode = ctx.DeserializeNodeReference(); var connectedNode1 = ctx.DeserializeNodeReference(); var connectedNode2 = ctx.DeserializeNodeReference(); var clamped1 = ctx.DeserializeVector3(); var clamped2 = ctx.DeserializeVector3(); var postScanCalled = ctx.reader.ReadBoolean(); GraphModifier link; if (usedIDs.TryGetValue(linkID, out link)) { var link2 = link as NodeLink2; if (link2 != null) { reference[startNode] = link2; reference[endNode] = link2; // If any nodes happened to be registered right now if (link2.startNode != null) reference.Remove(link2.startNode); if (link2.endNode != null) reference.Remove(link2.endNode); link2.startNode = startNode as PointNode; link2.endNode = endNode as PointNode; link2.connectedNode1 = connectedNode1; link2.connectedNode2 = connectedNode2; link2.postScanCalled = postScanCalled; link2.clamped1 = clamped1; link2.clamped2 = clamped2; } else { throw new System.Exception("Tried to deserialize a NodeLink2 reference, but the link was not of the correct type or it has been destroyed.\nIf a NodeLink2 is included in serialized graph data, the same NodeLink2 component must be present in the scene when loading the graph data."); } } else { throw new System.Exception("Tried to deserialize a NodeLink2 reference, but the link could not be found in the scene.\nIf a NodeLink2 is included in serialized graph data, the same NodeLink2 component must be present in the scene when loading the graph data."); } } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Threading; using MindTouch.Tasking; namespace MindTouch.Threading { /// <summary> /// RendezVousEvent is a lightweight synchronization primitive. It used to align exactly one signal source to a signal receiver (i.e. a rendez-vous). /// The order in which the signal is set and waited on are not important. The RendezVousEvent will remember that it was signaled and immediately /// trigger the receiver. <br/> /// The receiver must be a continuation. The RendezVousEvent does not allow for blocking wait. /// </summary> public sealed class RendezVousEvent { // NOTE (steveb): 'RendezVousEvent' is as a tuple-space implementation; it is succesful only when // both Signal() and Wait() have been invoked once and exactly once; the invocation order is irrelevant. //--- Constants --- private readonly static object TOKEN = new object(); private readonly static object USED = new object(); //--- Class Fields --- // TODO (steveb): there is a race condition where pending events get added, but not removed; the reason is that we don't have a hint that the event // was already removed and hence should not be added; note that since '_pendingCounter' uses atomic operation, it is not affected. /// <summary> /// Capture the state of the task (set to <see langword="False"/> by default.) /// </summary> public static bool CaptureTaskState = false; /// <summary> /// Dictionary of pending events. /// </summary> public static readonly Dictionary<object, KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>> Pending = new Dictionary<object, KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>>(); private static log4net.ILog _log = MindTouch.LogUtils.CreateLog(); private static int _pendingCounter = 0; //--- Class Properties --- /// <summary> /// Returns the number of pending RendezVousEvent instances. A pending RendezVousEvent instance has a continuation, but has not been signaled yet. /// </summary> public static int PendingCounter { get { return _pendingCounter; } } //--- Fields --- private object _placeholder; private System.Diagnostics.StackTrace _stacktrace = DebugUtil.GetStackTrace(); private bool _captured; //--- Properties --- /// <summary> /// Returns true if the RendezVousEvent instance has been signaled and the receiver continuation has been triggered. /// </summary> public bool HasCompleted { get { return ReferenceEquals(_placeholder, USED); } } //--- Methods --- /// <summary> /// Signal the RendezVousEvent. If a receiver continuation is present, trigger it. /// Otherwise, store the signal until a continuation is registered. /// </summary> /// <exception cref="InvalidOperationException">The RendezVousEvent instance has already been signaled.</exception> public void Signal() { if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object value = Interlocked.Exchange(ref _placeholder, TOKEN); if(value != null) { if(!(value is Action)) { throw new InvalidOperationException("event has already been signaled"); } Action handler = (Action)value; Interlocked.Decrement(ref _pendingCounter); if(_captured) { lock(Pending) { Pending.Remove(this); } } _placeholder = USED; try { handler(); } catch(Exception e) { // log exception, but ignore it; outer task is immune to it _log.WarnExceptionMethodCall(e, "Signal: unhandled exception in continuation"); } } } /// <summary> /// Register the receiver continuation to activate when the RendezVousEvent instance is signaled. /// </summary> /// <param name="handler">Receiver continuation to invoke when RendezVousEvent instance is signaled.</param> /// <exception cref="InvalidOperationException">The RendezVousEvent instance has already a continuation.</exception> public void Wait(Action handler) { if(handler == null) { throw new ArgumentNullException("handler"); } if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object token = Interlocked.Exchange(ref _placeholder, handler); if(token != null) { if(!ReferenceEquals(token, TOKEN)) { throw new InvalidOperationException("event has already a continuation"); } _placeholder = USED; try { handler(); } catch(Exception e) { // log exception, but ignore it; outer task is immune to it _log.WarnExceptionMethodCall(e, "Wait: unhandled exception in continuation"); } } else { Interlocked.Increment(ref _pendingCounter); if(CaptureTaskState) { lock(Pending) { if(!HasCompleted) { Pending.Add(this, new KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>(TaskEnv.CurrentOrNull, DebugUtil.GetStackTrace())); _captured = true; } } } } } /// <summary> /// Reset RendezVousEvent instance to its initial state without a signal and a continuation. /// </summary> public void Abandon() { object value = Interlocked.Exchange(ref _placeholder, null); if(ReferenceEquals(value, USED)) { // rendez-vous already happened; nothing to do } else if(ReferenceEquals(value, TOKEN)) { // only signal was set; nothing to do } else if(!ReferenceEquals(value, null)) { // decrease counter and remove stack trace if one exists Interlocked.Decrement(ref _pendingCounter); if(_captured) { lock(Pending) { Pending.Remove(this); } } } } /// <summary> /// Atomically check if RendezVousEvent is already signaled. If so, return true and mark the RendezVousEvent instance as having /// completed its synchronization operation. Otherwise, register the receiver continuation to activate when the RendezVousEvent /// instance is signaled. /// </summary> /// <param name="handler">Receiver continuation to invoke when RendezVousEvent instance is signaled.</param> /// <returns>Returns true if RendezVousEvent instance is already signaled.</returns> public bool IsReadyOrWait(Action handler) { if(handler == null) { throw new ArgumentNullException("handler"); } if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object token = Interlocked.Exchange(ref _placeholder, handler); if(token != null) { if(!ReferenceEquals(token, TOKEN)) { throw new InvalidOperationException("event has already a continuation"); } _placeholder = USED; return true; } else { Interlocked.Increment(ref _pendingCounter); if(CaptureTaskState) { lock(Pending) { if(!HasCompleted) { Pending.Add(this, new KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>(TaskEnv.CurrentOrNull, DebugUtil.GetStackTrace())); _captured = true; } } } } return false; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.InkCanvas.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class InkCanvas : System.Windows.FrameworkElement, System.Windows.Markup.IAddChild { #region Methods and constructors protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize) { return default(System.Windows.Size); } public bool CanPaste() { return default(bool); } public void CopySelection() { } public void CutSelection() { } public static double GetBottom(System.Windows.UIElement element) { return default(double); } public System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Ink.ApplicationGesture> GetEnabledGestures() { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Ink.ApplicationGesture>>() != null); return default(System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Ink.ApplicationGesture>); } public static double GetLeft(System.Windows.UIElement element) { return default(double); } public static double GetRight(System.Windows.UIElement element) { return default(double); } public System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.UIElement> GetSelectedElements() { return default(System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.UIElement>); } public System.Windows.Ink.StrokeCollection GetSelectedStrokes() { Contract.Ensures(Contract.Result<System.Windows.Ink.StrokeCollection>() != null); return default(System.Windows.Ink.StrokeCollection); } public System.Windows.Rect GetSelectionBounds() { return default(System.Windows.Rect); } public static double GetTop(System.Windows.UIElement element) { return default(double); } protected override System.Windows.Media.Visual GetVisualChild(int index) { return default(System.Windows.Media.Visual); } protected override System.Windows.Media.HitTestResult HitTestCore(System.Windows.Media.PointHitTestParameters hitTestParams) { return default(System.Windows.Media.HitTestResult); } public InkCanvasSelectionHitResult HitTestSelection(System.Windows.Point point) { return default(InkCanvasSelectionHitResult); } public InkCanvas() { } protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize) { return default(System.Windows.Size); } protected virtual new void OnActiveEditingModeChanged(System.Windows.RoutedEventArgs e) { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnDefaultDrawingAttributesReplaced(System.Windows.Ink.DrawingAttributesReplacedEventArgs e) { } protected virtual new void OnEditingModeChanged(System.Windows.RoutedEventArgs e) { } protected virtual new void OnEditingModeInvertedChanged(System.Windows.RoutedEventArgs e) { } protected virtual new void OnGesture(InkCanvasGestureEventArgs e) { } protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e) { } protected virtual new void OnSelectionChanged(EventArgs e) { } protected virtual new void OnSelectionChanging(InkCanvasSelectionChangingEventArgs e) { } protected virtual new void OnSelectionMoved(EventArgs e) { } protected virtual new void OnSelectionMoving(InkCanvasSelectionEditingEventArgs e) { } protected virtual new void OnSelectionResized(EventArgs e) { } protected virtual new void OnSelectionResizing(InkCanvasSelectionEditingEventArgs e) { } protected virtual new void OnStrokeCollected(InkCanvasStrokeCollectedEventArgs e) { } protected virtual new void OnStrokeErased(System.Windows.RoutedEventArgs e) { } protected virtual new void OnStrokeErasing(InkCanvasStrokeErasingEventArgs e) { } protected virtual new void OnStrokesReplaced(InkCanvasStrokesReplacedEventArgs e) { } public void Paste() { } public void Paste(System.Windows.Point point) { Contract.Ensures(!double.IsInfinity(point.X)); Contract.Ensures(!double.IsInfinity(point.Y)); } public void Select(System.Windows.Ink.StrokeCollection selectedStrokes) { } public void Select(IEnumerable<System.Windows.UIElement> selectedElements) { } public void Select(System.Windows.Ink.StrokeCollection selectedStrokes, IEnumerable<System.Windows.UIElement> selectedElements) { } public static void SetBottom(System.Windows.UIElement element, double length) { } public void SetEnabledGestures(IEnumerable<System.Windows.Ink.ApplicationGesture> applicationGestures) { } public static void SetLeft(System.Windows.UIElement element, double length) { } public static void SetRight(System.Windows.UIElement element, double length) { } public static void SetTop(System.Windows.UIElement element, double length) { } void System.Windows.Markup.IAddChild.AddChild(Object value) { } void System.Windows.Markup.IAddChild.AddText(string textData) { } #endregion #region Properties and indexers public InkCanvasEditingMode ActiveEditingMode { get { return default(InkCanvasEditingMode); } } public System.Windows.Media.Brush Background { get { return default(System.Windows.Media.Brush); } set { } } public UIElementCollection Children { get { return default(UIElementCollection); } } public System.Windows.Ink.DrawingAttributes DefaultDrawingAttributes { get { return default(System.Windows.Ink.DrawingAttributes); } set { } } public System.Windows.Input.StylusPointDescription DefaultStylusPointDescription { get { return default(System.Windows.Input.StylusPointDescription); } set { } } protected System.Windows.Input.StylusPlugIns.DynamicRenderer DynamicRenderer { get { return default(System.Windows.Input.StylusPlugIns.DynamicRenderer); } set { } } public InkCanvasEditingMode EditingMode { get { return default(InkCanvasEditingMode); } set { } } public InkCanvasEditingMode EditingModeInverted { get { return default(InkCanvasEditingMode); } set { } } public System.Windows.Ink.StylusShape EraserShape { get { Contract.Ensures(Contract.Result<System.Windows.Ink.StylusShape>() != null); return default(System.Windows.Ink.StylusShape); } set { } } protected InkPresenter InkPresenter { get { Contract.Ensures(Contract.Result<System.Windows.Controls.InkPresenter>() != null); return default(InkPresenter); } } public bool IsGestureRecognizerAvailable { get { return default(bool); } } internal protected override System.Collections.IEnumerator LogicalChildren { get { return default(System.Collections.IEnumerator); } } public bool MoveEnabled { get { return default(bool); } set { } } public IEnumerable<InkCanvasClipboardFormat> PreferredPasteFormats { get { return default(IEnumerable<InkCanvasClipboardFormat>); } set { } } public bool ResizeEnabled { get { return default(bool); } set { } } public System.Windows.Ink.StrokeCollection Strokes { get { return default(System.Windows.Ink.StrokeCollection); } set { } } public bool UseCustomCursor { get { return default(bool); } set { } } protected override int VisualChildrenCount { get { return default(int); } } #endregion #region Events public event System.Windows.RoutedEventHandler ActiveEditingModeChanged { add { } remove { } } public event System.Windows.Ink.DrawingAttributesReplacedEventHandler DefaultDrawingAttributesReplaced { add { } remove { } } public event System.Windows.RoutedEventHandler EditingModeChanged { add { } remove { } } public event System.Windows.RoutedEventHandler EditingModeInvertedChanged { add { } remove { } } public event InkCanvasGestureEventHandler Gesture { add { } remove { } } public event EventHandler SelectionChanged { add { } remove { } } public event InkCanvasSelectionChangingEventHandler SelectionChanging { add { } remove { } } public event EventHandler SelectionMoved { add { } remove { } } public event InkCanvasSelectionEditingEventHandler SelectionMoving { add { } remove { } } public event EventHandler SelectionResized { add { } remove { } } public event InkCanvasSelectionEditingEventHandler SelectionResizing { add { } remove { } } public event InkCanvasStrokeCollectedEventHandler StrokeCollected { add { } remove { } } public event System.Windows.RoutedEventHandler StrokeErased { add { } remove { } } public event InkCanvasStrokeErasingEventHandler StrokeErasing { add { } remove { } } public event InkCanvasStrokesReplacedEventHandler StrokesReplaced { add { } remove { } } #endregion #region Fields public readonly static System.Windows.RoutedEvent ActiveEditingModeChangedEvent; public readonly static System.Windows.DependencyProperty ActiveEditingModeProperty; public readonly static System.Windows.DependencyProperty BackgroundProperty; public readonly static System.Windows.DependencyProperty BottomProperty; public readonly static System.Windows.DependencyProperty DefaultDrawingAttributesProperty; public readonly static System.Windows.RoutedEvent EditingModeChangedEvent; public readonly static System.Windows.RoutedEvent EditingModeInvertedChangedEvent; public readonly static System.Windows.DependencyProperty EditingModeInvertedProperty; public readonly static System.Windows.DependencyProperty EditingModeProperty; public readonly static System.Windows.RoutedEvent GestureEvent; public readonly static System.Windows.DependencyProperty LeftProperty; public readonly static System.Windows.DependencyProperty RightProperty; public readonly static System.Windows.RoutedEvent StrokeCollectedEvent; public readonly static System.Windows.RoutedEvent StrokeErasedEvent; public readonly static System.Windows.DependencyProperty StrokesProperty; public readonly static System.Windows.DependencyProperty TopProperty; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using UnityEngine; namespace MixedRealityToolkit.SpatialSound.Sources { /// <summary> /// Currently active AudioEvents along with their AudioSource components for instance limiting events /// </summary> public class ActiveEvent : IDisposable { private AudioSource primarySource = null; public AudioSource PrimarySource { get { return primarySource; } private set { primarySource = value; if (primarySource != null) { primarySource.enabled = true; } } } private AudioSource secondarySource = null; public AudioSource SecondarySource { get { return secondarySource; } private set { secondarySource = value; if (secondarySource != null) { secondarySource.enabled = true; } } } public bool IsPlaying { get { return (primarySource != null && primarySource.isPlaying) || (secondarySource != null && secondarySource.isPlaying); } } public GameObject AudioEmitter { get; private set; } public string MessageOnAudioEnd { get; private set; } public AudioEvent AudioEvent = null; public bool IsStoppable = true; public float VolDest = 1; public float AltVolDest = 1; public float CurrentFade = 0; public bool PlayingAlt = false; public bool IsActiveTimeComplete = false; public float ActiveTime = 0; public bool CancelEvent = false; public ActiveEvent(AudioEvent audioEvent, GameObject emitter, AudioSource primarySource, AudioSource secondarySource, string messageOnAudioEnd = null) { this.AudioEvent = audioEvent; AudioEmitter = emitter; PrimarySource = primarySource; SecondarySource = secondarySource; MessageOnAudioEnd = messageOnAudioEnd; SetSourceProperties(); } public static AnimationCurve SpatialRolloff; /// <summary> /// Set the volume, spatialization, etc., on our AudioSources to match the settings on the event to play. /// </summary> private void SetSourceProperties() { Action<Action<AudioSource>> forEachSource = (action) => { action(PrimarySource); if (SecondarySource != null) { action(SecondarySource); } }; AudioEvent audioEvent = this.AudioEvent; switch (audioEvent.Spatialization) { case SpatialPositioningType.TwoD: forEachSource((source) => { source.spatialBlend = 0f; source.spatialize = false; }); break; case SpatialPositioningType.ThreeD: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = false; }); break; case SpatialPositioningType.SpatialSound: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = true; }); break; default: Debug.LogErrorFormat("Unexpected spatialization type: {0}", audioEvent.Spatialization.ToString()); break; } if (audioEvent.Spatialization == SpatialPositioningType.SpatialSound) { forEachSource((source) => { SpatialSoundSettings.SetRoomSize(source, audioEvent.RoomSize); source.rolloffMode = AudioRolloffMode.Custom; source.maxDistance = audioEvent.MaxDistanceAttenuation3D; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.AttenuationCurve); }); } else { forEachSource((source) => { if (audioEvent.Spatialization == SpatialPositioningType.ThreeD) { source.rolloffMode = AudioRolloffMode.Custom; source.maxDistance = audioEvent.MaxDistanceAttenuation3D; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.AttenuationCurve); source.SetCustomCurve(AudioSourceCurveType.SpatialBlend, audioEvent.SpatialCurve); source.SetCustomCurve(AudioSourceCurveType.Spread, audioEvent.SpreadCurve); source.SetCustomCurve(AudioSourceCurveType.ReverbZoneMix, audioEvent.ReverbCurve); } else { source.rolloffMode = AudioRolloffMode.Logarithmic; } }); } if (audioEvent.AudioBus != null) { forEachSource((source) => source.outputAudioMixerGroup = audioEvent.AudioBus); } float pitch = 1f; if (audioEvent.PitchRandomization != 0) { pitch = UnityEngine.Random.Range(audioEvent.PitchCenter - audioEvent.PitchRandomization, audioEvent.PitchCenter + audioEvent.PitchRandomization); } else { pitch = audioEvent.PitchCenter; } forEachSource((source) => source.pitch = pitch); float vol = 1f; if (audioEvent.FadeInTime > 0) { forEachSource((source) => source.volume = 0f); this.CurrentFade = audioEvent.FadeInTime; if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } this.VolDest = vol; } else { if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } forEachSource((source) => source.volume = vol); } float pan = audioEvent.PanCenter; if (audioEvent.PanRandomization != 0) { pan = UnityEngine.Random.Range(audioEvent.PanCenter - audioEvent.PanRandomization, audioEvent.PanCenter + audioEvent.PanRandomization); } forEachSource((source) => source.panStereo = pan); } /// <summary> /// Sets the pitch value for the primary source. /// </summary> /// <param name="newPitch">The value to set the pitch, between 0 (exclusive) and 3 (inclusive).</param> public void SetPitch(float newPitch) { if (newPitch <= 0 || newPitch > 3) { Debug.LogErrorFormat("Invalid pitch {0} set for event", newPitch); return; } this.PrimarySource.pitch = newPitch; } public void Dispose() { if (this.primarySource != null) { this.primarySource.enabled = false; this.primarySource = null; } if (this.secondarySource != null) { this.secondarySource.enabled = false; this.secondarySource = null; } } /// <summary> /// Creates a flat animation curve to negate Unity's distance attenuation when using Spatial Sound /// </summary> public static void CreateFlatSpatialRolloffCurve() { if (SpatialRolloff != null) { return; } SpatialRolloff = new AnimationCurve(); SpatialRolloff.AddKey(0, 1); SpatialRolloff.AddKey(1, 1); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Linq; using NetGore.IO; using NetGore.World; using SFML.Graphics; namespace NetGore.Graphics { /// <summary> /// A single image that resides in the background of the map. /// </summary> public abstract class BackgroundImage : IDrawable { const string _valueKeyAlignment = "Alignment"; const string _valueKeyColor = "Color"; const string _valueKeyDepth = "Depth"; const string _valueKeyGrhIndex = "GrhIndex"; const string _valueKeyName = "Name"; const string _valueKeyOffset = "Offset"; readonly ICamera2DProvider _cameraProvider; readonly IMap _map; Color _color = Color.White; float _depth; bool _isVisible = true; string _name; Grh _sprite; /// <summary> /// Initializes a new instance of the <see cref="BackgroundImage"/> class. /// </summary> /// <param name="cameraProvider">The camera provider.</param> /// <param name="map">The map that this <see cref="BackgroundImage"/> is on.</param> /// <exception cref="ArgumentNullException"><paramref name="cameraProvider" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="map" /> is <c>null</c>.</exception> protected BackgroundImage(ICamera2DProvider cameraProvider, IMap map) { if (cameraProvider == null) throw new ArgumentNullException("cameraProvider"); if (map == null) throw new ArgumentNullException("map"); _cameraProvider = cameraProvider; _map = map; // Set the default values Offset = Vector2.Zero; Alignment = Alignment.TopLeft; _sprite = new Grh(null, AnimType.Loop, map.GetTime()); } /// <summary> /// Initializes a new instance of the <see cref="BackgroundImage"/> class. /// </summary> /// <param name="cameraProvider">The camera provider.</param> /// <param name="map">The map that this <see cref="BackgroundImage"/> is on.</param> /// <param name="reader">The <see cref="IValueReader"/> to read the values from.</param> /// <exception cref="ArgumentNullException"><paramref name="cameraProvider" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="map" /> is <c>null</c>.</exception> protected BackgroundImage(ICamera2DProvider cameraProvider, IMap map, IValueReader reader) { if (cameraProvider == null) throw new ArgumentNullException("cameraProvider"); if (map == null) throw new ArgumentNullException("map"); _cameraProvider = cameraProvider; _map = map; Read(reader); } /// <summary> /// Gets or sets how the background image is aligned to the map. Default is TopLeft. /// </summary> [Category("Position")] [DisplayName("Alignment")] [Description("How the background image is aligned to the map.")] [DefaultValue(Alignment.TopLeft)] [Browsable(true)] public Alignment Alignment { get; set; } /// <summary> /// Gets the <see cref="ICamera2D"/> used to view the <see cref="BackgroundImage"/>. /// </summary> [Browsable(false)] protected ICamera2D Camera { get { return _cameraProvider.Camera; } } /// <summary> /// Gets or sets the depth of the image relative to other background images, and how fast the /// image moves with the camera. A depth of 1.0 will move as fast as the camera, while a depth of /// 2.0 will move at half the speed of the camera. Must be greater than or equal to 1.0. Default is 1.0. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than 1.0.</exception> [Category("Position")] [DisplayName("Depth")] [Description( "Defines the drawing order and movement speed, where 1.0 is same speed of the camera, and 2.0 is half the speed.")] [DefaultValue(1)] [Browsable(true)] public float Depth { get { return _depth; } set { if (value < 1.0f) throw new ArgumentOutOfRangeException("value"); _depth = value; } } /// <summary> /// Gets the <see cref="IMap"/> the <see cref="BackgroundImage"/> is on. /// </summary> [Browsable(false)] protected IMap Map { get { return _map; } } /// <summary> /// Gets or sets the optional name of this BackgroundImage. This is only used for personal purposes and /// has absolutely no affect on the BackgroundImage itself. /// </summary> [Category("Design")] [DisplayName("Name")] [Description("The optional name of this BackgroundImage. Used for development purposes only.")] [Browsable(true)] public string Name { get { return _name; } set { _name = value ?? string.Empty; } } /// <summary> /// Gets or sets the pixel offset of the image from the Alignment. /// </summary> [Category("Position")] [DisplayName("Offset")] [Description("The pixel offset of the image from the Alignment.")] [DefaultValue(typeof(Vector2), "0, 0")] [Browsable(true)] public Vector2 Offset { get; set; } /// <summary> /// Gets the sprite to draw. /// </summary> [Category("Display")] [DisplayName("Sprite")] [Description("The sprite to draw.")] [Browsable(true)] public Grh Sprite { get { return _sprite; } } /// <summary> /// Gets the size of the Sprite source image. /// </summary> [Browsable(false)] protected Vector2 SpriteSourceSize { get { if (!IsSpriteSet()) return Vector2.Zero; return new Vector2(Sprite.Source.Width, Sprite.Source.Height); } } /// <summary> /// Gets the multiplier to use to offset an <see cref="Alignment"/>. /// </summary> /// <param name="alignment">The <see cref="Alignment"/>.</param> /// <returns>The offset to use for the <paramref name="alignment"/>.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="alignment"/> contains a value not defined by the /// <see cref="Alignment"/> enum.</exception> static Vector2 GetOffsetMultiplier(Alignment alignment) { switch (alignment) { case Alignment.TopLeft: return new Vector2(0, 0); case Alignment.TopRight: return new Vector2(1, 0); case Alignment.BottomLeft: return new Vector2(0, 1); case Alignment.BottomRight: return new Vector2(1, 1); case Alignment.Top: return new Vector2(0.5f, 0); case Alignment.Bottom: return new Vector2(0.5f, 1f); case Alignment.Left: return new Vector2(0, 0.5f); case Alignment.Right: return new Vector2(1, 0.5f); case Alignment.Center: return new Vector2(0.5f, 0.5f); default: throw new ArgumentOutOfRangeException("alignment"); } } /// <summary> /// Finds the map position of the image using the given <paramref name="camera"/>. /// </summary> /// <param name="mapSize">Size of the map that this image is on.</param> /// <param name="camera">Camera that describes the current view.</param> /// <param name="spriteSize">Size of the Sprite that will be drawn.</param> /// <returns>The map position of the image using the given <paramref name="camera"/>.</returns> protected Vector2 GetPosition(Vector2 mapSize, ICamera2D camera, Vector2 spriteSize) { // Can't draw a sprite that has no size... if (spriteSize == Vector2.Zero) return Vector2.Zero; // Get the position from the alignment var alignmentPosition = AlignmentHelper.FindOffset(Alignment, spriteSize, mapSize); // Add the custom offset var position = alignmentPosition + Offset; // Find the difference between the position and the camera's min position var diff = camera.Min - position; // Use the multiplier to align it to the correct part of the camera diff += (camera.Size - spriteSize) * GetOffsetMultiplier(Alignment); // Compensate for the depth diff *= ((1 / Depth) - 1); // Add the difference to the position position -= diff; return position; } /// <summary> /// Finds the map position of the image using the given <paramref name="camera"/>. /// </summary> /// <param name="mapSize">Size of the map that this image is on.</param> /// <param name="camera">Camera that describes the current view.</param> /// <returns>The map position of the image using the given <paramref name="camera"/>.</returns> protected Vector2 GetPosition(Vector2 mapSize, ICamera2D camera) { return GetPosition(mapSize, camera, SpriteSourceSize); } /// <summary> /// Handles drawing the <see cref="BackgroundImage"/>. /// </summary> /// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param> protected virtual void HandleDraw(ISpriteBatch spriteBatch) { var position = GetPosition(Map.Size, Camera); Sprite.Draw(spriteBatch, position, Color); } /// <summary> /// Gets the <see cref="BackgroundImage.LayerDepth"/> value from the <see cref="IDrawable.LayerDepth"/>. /// </summary> /// <param name="imageDepth">The <see cref="BackgroundImage.LayerDepth"/> value.</param> /// <returns>The <see cref="IDrawable.LayerDepth"/> value for the <paramref name="imageDepth"/>.</returns> public static int ImageDepthToLayerDepth(float imageDepth) { return (int)(imageDepth * -100); } /// <summary> /// Gets if the Sprite is set and valid. /// </summary> /// <returns>True if the Sprite is set; otherwise false.</returns> protected virtual bool IsSpriteSet() { return Sprite != null && Sprite.GrhData != null; } /// <summary> /// Gets the <see cref="IDrawable.LayerDepth"/> value from the <see cref="BackgroundImage.LayerDepth"/>. /// </summary> /// <param name="layerDepth">The <see cref="IDrawable.LayerDepth"/> value.</param> /// <returns>The <see cref="BackgroundImage.LayerDepth"/> value for the <paramref name="layerDepth"/>.</returns> public static float LayerDepthToImageDepth(int layerDepth) { return layerDepth * -0.01f; } /// <summary> /// Reads the <see cref="BackgroundImage"/> from an <see cref="IValueReader"/>. /// </summary> /// <param name="reader">The <see cref="IValueReader"/> to read from.</param> protected virtual void Read(IValueReader reader) { Name = reader.ReadString(_valueKeyName); Alignment = reader.ReadEnum<Alignment>(_valueKeyAlignment); Color = reader.ReadColor(_valueKeyColor); Depth = reader.ReadFloat(_valueKeyDepth); Offset = reader.ReadVector2(_valueKeyOffset); var grhIndex = reader.ReadGrhIndex(_valueKeyGrhIndex); _sprite = new Grh(grhIndex, AnimType.Loop, Map.GetTime()); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { string name; if (string.IsNullOrEmpty(Name)) name = "Unnamed"; else name = Name; return string.Format("[{0}] {1}", GetType().Name, name); } /// <summary> /// Updates the <see cref="BackgroundImage"/>. /// </summary> /// <param name="currentTime">Current game time.</param> public virtual void Update(TickCount currentTime) { if (!IsSpriteSet()) return; Sprite.Update(currentTime); } /// <summary> /// Writes the <see cref="BackgroundImage"/> to an <see cref="IValueWriter"/>. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> to write to.</param> public virtual void Write(IValueWriter writer) { writer.Write(_valueKeyName, Name); writer.WriteEnum(_valueKeyAlignment, Alignment); writer.Write(_valueKeyColor, Color); writer.Write(_valueKeyDepth, Depth); writer.Write(_valueKeyOffset, Offset); GrhIndex grhIndex; if (IsSpriteSet()) grhIndex = Sprite.GrhData.GrhIndex; else { grhIndex = GrhIndex.Invalid; Debug.Fail("Why is the Sprite not set? That doesn't seem right..."); } writer.Write(_valueKeyGrhIndex, grhIndex); } #region IDrawable Members /// <summary> /// Notifies listeners immediately after this <see cref="IDrawable"/> is drawn. /// This event will be raised even if <see cref="IDrawable.IsVisible"/> is false. /// </summary> public event TypedEventHandler<IDrawable, EventArgs<ISpriteBatch>> AfterDraw; /// <summary> /// Notifies listeners immediately before this <see cref="IDrawable"/> is drawn. /// This event will be raised even if <see cref="IDrawable.IsVisible"/> is false. /// </summary> public event TypedEventHandler<IDrawable, EventArgs<ISpriteBatch>> BeforeDraw; /// <summary> /// Notifies listeners when the <see cref="IDrawable.Color"/> property has changed. /// </summary> public event TypedEventHandler<IDrawable> ColorChanged; /// <summary> /// Unused by the <see cref="BackgroundImage"/> since the layer never changes. /// </summary> event TypedEventHandler<IDrawable, ValueChangedEventArgs<MapRenderLayer>> IDrawable.RenderLayerChanged { add { } remove { } } /// <summary> /// Notifies listeners when the <see cref="IDrawable.IsVisible"/> property has changed. /// </summary> public event TypedEventHandler<IDrawable> VisibleChanged; /// <summary> /// Gets or sets the <see cref="IDrawable.Color"/> to use when drawing this <see cref="IDrawable"/>. By default, this /// value will be equal to white (ARGB: 255,255,255,255). /// </summary> [Category("Display")] [DisplayName("Color")] [Description("The color to use when drawing the image where RGBA 255,255,255,255 will draw the image unaltered.")] [DefaultValue(typeof(Color), "255, 255, 255, 255")] [Browsable(true)] public Color Color { get { return _color; } set { if (_color == value) return; _color = value; if (ColorChanged != null) ColorChanged.Raise(this, EventArgs.Empty); } } /// <summary> /// Gets or sets if this <see cref="IDrawable"/> will be drawn. All <see cref="IDrawable"/>s are initially /// visible. /// </summary> [Browsable(false)] public bool IsVisible { get { return _isVisible; } set { if (_isVisible == value) return; _isVisible = value; if (VisibleChanged != null) VisibleChanged.Raise(this, EventArgs.Empty); } } /// <summary> /// Gets the depth of the object for the <see cref="IDrawable.MapRenderLayer"/> the object is on. A higher /// layer depth results in the object being drawn on top of (in front of) objects with a lower value. /// </summary> [Browsable(false)] public int LayerDepth { get { return ImageDepthToLayerDepth(Depth); } } /// <summary> /// Gets the <see cref="IDrawable.MapRenderLayer"/> that this object is rendered on. /// </summary> [Browsable(false)] public MapRenderLayer MapRenderLayer { get { return MapRenderLayer.Background; } } /// <summary> /// Makes the object draw itself. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> the object can use to draw itself with.</param> public void Draw(ISpriteBatch sb) { // Ensure the sprite is set if (!IsSpriteSet()) return; // Pre-drawing if (BeforeDraw != null) BeforeDraw.Raise(this, EventArgsHelper.Create(sb)); // Draw if (IsVisible) HandleDraw(sb); // Post-drawing if (AfterDraw != null) AfterDraw.Raise(this, EventArgsHelper.Create(sb)); } /// <summary> /// Checks if in the object is in view of the specified <paramref name="camera"/>. /// </summary> /// <param name="camera">The <see cref="ICamera2D"/> to check if this object is in view of.</param> /// <returns>True if the object is in view of the camera, else False.</returns> public bool InView(ICamera2D camera) { if (!IsSpriteSet()) return false; // FUTURE: Implement properly return true; /* Vector2 position = GetPosition(Map.Size, Camera); if (position.X > camera.Max.X || position.Y > camera.Max.Y) return false; Vector2 max = position + Sprite.Size; if (max.X < camera.Min.X || max.Y < camera.Min.Y) return false; return true; */ } #endregion /// <summary> /// Not supported by BackgroundImage. Always returns Vector2.Zero. /// </summary> Vector2 IPositionable.Position { get { return Vector2.Zero; } } /// <summary> /// Not supported by BackgroundImage. Always returns Vector2.Zero. /// </summary> Vector2 IPositionable.Size { get { return Vector2.Zero; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Buffers; using System.IO; using System.Text.Encodings.Web; namespace System.Text.Json.Tests { public sealed class JsonDocumentWriteTests : JsonDomWriteTests { protected override JsonDocument PrepareDocument(string jsonIn) { var jsonDocument = JsonDocument.Parse(jsonIn, s_options); return jsonDocument; } protected override void WriteSingleValue(JsonDocument document, Utf8JsonWriter writer) { document.WriteTo(writer); } protected override void WriteDocument(JsonDocument document, Utf8JsonWriter writer) { document.WriteTo(writer); } [Fact] public static void CheckByPassingNullWriter() { using (JsonDocument doc = JsonDocument.Parse("true", default)) { AssertExtensions.Throws<ArgumentNullException>("writer", () => doc.WriteTo(null)); } } } public sealed class JsonNodeWriteTests : JsonDomWriteTests { protected override JsonDocument PrepareDocument(string jsonIn) { JsonNode jsonNode = JsonNode.Parse(jsonIn, new JsonNodeOptions { AllowTrailingCommas = s_options.AllowTrailingCommas, CommentHandling = s_options.CommentHandling, MaxDepth = s_options.MaxDepth }); using (MemoryStream stream = new MemoryStream()) { using (Utf8JsonWriter writer = new Utf8JsonWriter(stream)) { jsonNode.WriteTo(writer); stream.Seek(0, SeekOrigin.Begin); var jsonDocument = JsonDocument.Parse(stream, s_options); return jsonDocument; } } } protected override void WriteSingleValue(JsonDocument document, Utf8JsonWriter writer) { document.WriteTo(writer); } protected override void WriteDocument(JsonDocument document, Utf8JsonWriter writer) { document.WriteTo(writer); } [Fact] public static void CheckByPassingNullWriter() { using (JsonDocument doc = JsonDocument.Parse("true", default)) { AssertExtensions.Throws<ArgumentNullException>("writer", () => doc.WriteTo(null)); } } } public sealed class JsonElementWriteTests : JsonDomWriteTests { protected override JsonDocument PrepareDocument(string jsonIn) { return JsonDocument.Parse($" [ {jsonIn} ]", s_options); } protected override void WriteSingleValue(JsonDocument document, Utf8JsonWriter writer) { document.RootElement[0].WriteTo(writer); } protected override void WriteDocument(JsonDocument document, Utf8JsonWriter writer) { document.RootElement.WriteTo(writer); } [Fact] public void CheckByPassingNullWriter() { using (JsonDocument doc = JsonDocument.Parse("true", default)) { JsonElement root = doc.RootElement; AssertExtensions.Throws<ArgumentNullException>("writer", () => root.WriteTo(null)); } } [Theory] [InlineData(false)] [InlineData(true)] public void WritePropertyOutsideObject(bool skipValidation) { var buffer = new ArrayBufferWriter<byte>(1024); using (var doc = JsonDocument.Parse("[ null, false, true, \"hi\", 5, {}, [] ]", s_options)) { JsonElement root = doc.RootElement; var options = new JsonWriterOptions { SkipValidation = skipValidation, }; const string CharLabel = "char"; byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte"); using var writer = new Utf8JsonWriter(buffer, options); if (skipValidation) { foreach (JsonElement val in root.EnumerateArray()) { writer.WritePropertyName(CharLabel); val.WriteTo(writer); writer.WritePropertyName(CharLabel.AsSpan()); val.WriteTo(writer); writer.WritePropertyName(byteUtf8); val.WriteTo(writer); writer.WritePropertyName(JsonEncodedText.Encode(CharLabel)); val.WriteTo(writer); } writer.Flush(); JsonTestHelper.AssertContents( "\"char\":null,\"char\":null,\"byte\":null,\"char\":null," + "\"char\":false,\"char\":false,\"byte\":false,\"char\":false," + "\"char\":true,\"char\":true,\"byte\":true,\"char\":true," + "\"char\":\"hi\",\"char\":\"hi\",\"byte\":\"hi\",\"char\":\"hi\"," + "\"char\":5,\"char\":5,\"byte\":5,\"char\":5," + "\"char\":{},\"char\":{},\"byte\":{},\"char\":{}," + "\"char\":[],\"char\":[],\"byte\":[],\"char\":[]", buffer); } else { Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel)); Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel.AsSpan())); Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(byteUtf8)); Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(JsonEncodedText.Encode(CharLabel))); writer.Flush(); JsonTestHelper.AssertContents("", buffer); } } } [Theory] [InlineData(false)] [InlineData(true)] public void WriteValueInsideObject(bool skipValidation) { var buffer = new ArrayBufferWriter<byte>(1024); using (var doc = JsonDocument.Parse("[ null, false, true, \"hi\", 5, {}, [] ]", s_options)) { JsonElement root = doc.RootElement; var options = new JsonWriterOptions { SkipValidation = skipValidation, }; using var writer = new Utf8JsonWriter(buffer, options); writer.WriteStartObject(); if (skipValidation) { foreach (JsonElement val in root.EnumerateArray()) { val.WriteTo(writer); } writer.WriteEndObject(); writer.Flush(); JsonTestHelper.AssertContents( "{null,false,true,\"hi\",5,{},[]}", buffer); } else { foreach (JsonElement val in root.EnumerateArray()) { Assert.Throws<InvalidOperationException>(() => val.WriteTo(writer)); } writer.WriteEndObject(); writer.Flush(); JsonTestHelper.AssertContents("{}", buffer); } } } } public abstract class JsonDomWriteTests { protected static readonly JsonDocumentOptions s_options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, }; protected abstract JsonDocument PrepareDocument(string jsonIn); protected abstract void WriteSingleValue(JsonDocument document, Utf8JsonWriter writer); protected abstract void WriteDocument(JsonDocument document, Utf8JsonWriter writer); [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumber(bool indented) { WriteSimpleValue(indented, "42"); } [Theory] [InlineData("12E-3", false)] [InlineData("1e6", false)] [InlineData("1e6", true)] [InlineData("1e+6", false)] [InlineData("1e+6", true)] [InlineData("1e-6", false)] [InlineData("1e-6", true)] [InlineData("-1e6", false)] [InlineData("-1e6", true)] [InlineData("-1e+6", false)] [InlineData("-1e+6", true)] [InlineData("-1e-6", false)] [InlineData("-1e-6", true)] public void WriteNumberScientific(string value, bool indented) { WriteSimpleValue(indented, value); } [Theory] [InlineData("1.2E+3", false)] [InlineData("5.012e-20", false)] [InlineData("5.012e-20", true)] [InlineData("5.012e20", false)] [InlineData("5.012e20", true)] [InlineData("5.012e+20", false)] [InlineData("5.012e+20", true)] [InlineData("-5.012e-20", false)] [InlineData("-5.012e-20", true)] [InlineData("-5.012e20", false)] [InlineData("-5.012e20", true)] [InlineData("-5.012e+20", false)] [InlineData("-5.012e+20", true)] public void WriteNumberDecimalScientific(string value, bool indented) { WriteSimpleValue(indented, value); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberOverprecise(bool indented) { // This value is a reference "potential interoperability problem" from // https://tools.ietf.org/html/rfc7159#section-6 const string PrecisePi = "3.141592653589793238462643383279"; // To confirm that this test is doing what it intends, one could // confirm the printing precision of double, like // //double precisePi = double.Parse(PrecisePi); //Assert.NotEqual(PrecisePi, precisePi.ToString(JsonTestHelper.DoubleFormatString)); WriteSimpleValue(indented, PrecisePi); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberTooLargeScientific(bool indented) { // This value is a reference "potential interoperability problem" from // https://tools.ietf.org/html/rfc7159#section-6 const string OneQuarticGoogol = "1e400"; // This just validates we write the literal number 1e400 even though it is too // large to be represented by System.Double and would be converted to // PositiveInfinity instead (or throw if using double.Parse on frameworks // older than .NET Core 3.0). WriteSimpleValue(indented, OneQuarticGoogol); } [Theory] [InlineData("6.022e+23", "6,022e+23")] [InlineData("6.022e+23", "6.022f+23")] [InlineData("6.022e+23", "6.022e+ 3")] [InlineData("6.022e+23", "6e022e+23")] [InlineData("6.022e+23", "6.022e+f3")] [InlineData("1", "-")] [InlineData("12", "+2")] [InlineData("12", "1e")] [InlineData("12", "1.")] [InlineData("12", "02")] [InlineData("123", "1e+")] [InlineData("123", "1e-")] [InlineData("0.12", "0.1e")] [InlineData("0.123", "0.1e+")] [InlineData("0.123", "0.1e-")] [InlineData("10", "+0")] [InlineData("101", "-01")] [InlineData("12", "1a")] [InlineData("10", "00")] [InlineData("11", "01")] [InlineData("10.5e-012", "10.5e-0.2")] [InlineData("10.5e012", "10.5.012")] [InlineData("0.123", "0.-23")] [InlineData("12345", "hello")] public void WriteCorruptedNumber(string parseJson, string overwriteJson) { if (overwriteJson.Length != parseJson.Length) { throw new InvalidOperationException("Invalid test, parseJson and overwriteJson must have the same length"); } byte[] utf8Data = Encoding.UTF8.GetBytes(parseJson); using (JsonDocument document = JsonDocument.Parse(utf8Data)) using (MemoryStream stream = new MemoryStream(Array.Empty<byte>())) using (Utf8JsonWriter writer = new Utf8JsonWriter(stream)) { // Use fixed and the older version of GetBytes-in-place because of the NetFX build. unsafe { fixed (byte* dataPtr = utf8Data) fixed (char* inputPtr = overwriteJson) { // Overwrite the number in the memory buffer still referenced by the document. // If it doesn't hit a 100% overlap then we're not testing what we thought we were. Assert.Equal( utf8Data.Length, Encoding.UTF8.GetBytes(inputPtr, overwriteJson.Length, dataPtr, utf8Data.Length)); } } JsonElement rootElement = document.RootElement; Assert.Equal(overwriteJson, rootElement.GetRawText()); AssertExtensions.Throws<ArgumentException>( "utf8FormattedNumber", () => WriteDocument(document, writer)); } } [Theory] [InlineData(false)] [InlineData(true)] public void WriteAsciiString(bool indented) { WriteSimpleValue(indented, "\"pizza\""); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEscapedString(bool indented) { WriteSimpleValue(indented, "\"p\\u0069zza\"", "\"pizza\""); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNonAsciiString(bool indented) { // In the JSON input the U+00ED (lowercase i, acute) is a literal char, // therefore is ingested as the UTF-8 sequence [ C3 AD ]. // // When writing it back out, the writer turns it into a JSON string // using escaped codepoint syntax. // // The subtlety of the input vs output is the number of backslashes (and // the hex casing is different to show the difference more aggressively). WriteSimpleValue(indented, "\"p\u00cdzza\"", "\"p\\u00CDzza\""); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEscapedNonAsciiString(bool indented) { // In the JSON input the U+00ED (lowercase i, acute) is a literal char, // therefore is ingested as the UTF-8 sequence [ C3 AD ]. // // When writing it back out, the writer turns it into a JSON string // using escaped codepoint syntax. // // The subtlety of the input vs output is the number of backslashes (and // the hex casing is different to show the difference more aggressively). // // The U+007A (lowercase z) is just to make sure nothing weird happens // between the de-escape and the UTF-8. WriteSimpleValue(indented, "\"p\u00cdz\\u007Aa\"", "\"p\\u00CDzza\""); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteTrue(bool indented) { WriteSimpleValue(indented, "true"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteFalse(bool indented) { WriteSimpleValue(indented, "false"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNull(bool indented) { WriteSimpleValue(indented, "null"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyArray(bool indented) { WriteComplexValue( indented, "[ ]", "[]", "[]"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyObject(bool indented) { WriteComplexValue( indented, "{ }", "{}", "{}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyCommentedArray(bool indented) { WriteComplexValue( indented, "[ /* \"No values here\" */ ]", "[]", "[]"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyCommentedObject(bool indented) { WriteComplexValue( indented, "{ /* Technically empty */ }", "{}", "{}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteSimpleArray(bool indented) { WriteComplexValue( indented, @"[ 2, 4, 6 , 0 , 1 ]".NormalizeLineEndings(), @"[ 2, 4, 6, 0, 1 ]".NormalizeLineEndings(), "[2,4,6,0,1]"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteSimpleObject(bool indented) { WriteComplexValue( indented, @"{ ""r"" : 2, // Comments make everything more interesting. ""d"": 2 }".NormalizeLineEndings(), @"{ ""r"": 2, ""d"": 2 }".NormalizeLineEndings(), "{\"r\":2,\"d\":2}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteSimpleObjectNeedsEscaping(bool indented) { WriteComplexValue( indented, @"{ ""prop><erty"" : 3, ""> This is one long & unusual property name. <"": 4 }", @"{ ""prop\u003E\u003Certy"": 3, ""\u003E This is one long \u0026 unusual property name. \u003C"": 4 }", "{\"prop\\u003E\\u003Certy\":3,\"\\u003E This is one long \\u0026 unusual property name. \\u003C\":4}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEverythingArray(bool indented) { WriteComplexValue( indented, (@" [ ""Once upon a midnight dreary"", 42, /* Yep */ 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not requ\u0069red"", // More comments, more problems? ""Some th\u0069ngs get lost in the " + "m\u00EAl\u00E9e" + @""", // Array with an array (primes) [ 2, 3, 5, 7, /*9,*/ 11], { ""obj"": [ 21, { ""deep obj"": [ ""Once upon a midnight dreary"", 42, /* Yep */ 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not requ\u0069red"", // More comments, more problems? ""Some th\u0069ngs get lost in the " + "m\u00EAl\u00E9e" + @""" ], ""more deep"": false }, 12 ], ""second property"": null }] ").NormalizeLineEndings(), @"[ ""Once upon a midnight dreary"", 42, 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not required"", ""Some things get lost in the m\u00EAl\u00E9e"", [ 2, 3, 5, 7, 11 ], { ""obj"": [ 21, { ""deep obj"": [ ""Once upon a midnight dreary"", 42, 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not required"", ""Some things get lost in the m\u00EAl\u00E9e"" ], ""more deep"": false }, 12 ], ""second property"": null } ]".NormalizeLineEndings(), "[\"Once upon a midnight dreary\",42,1e400,3.141592653589793238462643383279," + "false,true,null,\"Escaping is not required\"," + "\"Some things get lost in the m\\u00EAl\\u00E9e\",[2,3,5,7,11]," + "{\"obj\":[21,{\"deep obj\":[\"Once upon a midnight dreary\",42,1e400," + "3.141592653589793238462643383279,false,true,null,\"Escaping is not required\"," + "\"Some things get lost in the m\\u00EAl\\u00E9e\"],\"more deep\":false},12]," + "\"second property\":null}]"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEverythingObject(bool indented) { WriteComplexValue( indented, "{" + "\"int\": 42," + "\"quadratic googol\": 1e400," + "\"precisePi\": 3.141592653589793238462643383279," + "\"lit0\": null,\"lit1\": false,/*guess next*/\"lit2\": true," + "\"ascii\": \"pizza\"," + "\"escaped\": \"p\\u0069zza\"," + "\"utf8\": \"p\u00CDzza\"," + "\"utf8ExtraEscape\": \"p\u00CDz\\u007Aa\"," + "\"arr\": [\"hello\", \"sa\\u0069lor\", 21, \"blackjack!\" ]," + "\"obj\": {" + "\"arr\": [ 1, 3, 5, 7, /*9,*/ 11] " + "}}", @"{ ""int"": 42, ""quadratic googol"": 1e400, ""precisePi"": 3.141592653589793238462643383279, ""lit0"": null, ""lit1"": false, ""lit2"": true, ""ascii"": ""pizza"", ""escaped"": ""pizza"", ""utf8"": ""p\u00CDzza"", ""utf8ExtraEscape"": ""p\u00CDzza"", ""arr"": [ ""hello"", ""sailor"", 21, ""blackjack!"" ], ""obj"": { ""arr"": [ 1, 3, 5, 7, 11 ] } }".NormalizeLineEndings(), "{\"int\":42,\"quadratic googol\":1e400,\"precisePi\":3.141592653589793238462643383279," + "\"lit0\":null,\"lit1\":false,\"lit2\":true,\"ascii\":\"pizza\",\"escaped\":\"pizza\"," + "\"utf8\":\"p\\u00CDzza\",\"utf8ExtraEscape\":\"p\\u00CDzza\"," + "\"arr\":[\"hello\",\"sailor\",21,\"blackjack!\"]," + "\"obj\":{\"arr\":[1,3,5,7,11]}}"); } [Theory] [InlineData(false)] [InlineData(true)] public void ReadWriteEscapedPropertyNames(bool indented) { const string jsonIn = " { \"p\\u0069zza\": 1, \"hello\\u003c\\u003e\": 2, \"normal\": 3 }"; WriteComplexValue( indented, jsonIn, @"{ ""pizza"": 1, ""hello\u003c\u003e"": 2, ""normal"": 3 }", "{\"pizza\":1,\"hello\\u003c\\u003e\":2,\"normal\":3}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberAsProperty(bool indented) { WritePropertyValueBothForms( indented, "ectoplasm", "42", @"{ ""ectoplasm"": 42 }".NormalizeLineEndings(), "{\"ectoplasm\":42}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberAsPropertyWithLargeName(bool indented) { var charArray = new char[300]; charArray.AsSpan().Fill('a'); charArray[0] = (char)0xEA; var propertyName = new string(charArray); WritePropertyValueBothForms( indented, propertyName, "42", (@"{ ""\u00EA" + propertyName.Substring(1) + @""": 42 }").NormalizeLineEndings(), $"{{\"\\u00EA{propertyName.Substring(1)}\":42}}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberScientificAsProperty(bool indented) { WritePropertyValueBothForms( indented, "m\u00EAl\u00E9e", "1e6", @"{ ""m\u00EAl\u00E9e"": 1e6 }".NormalizeLineEndings(), "{\"m\\u00EAl\\u00E9e\":1e6}"); } [Fact] public void WriteValueSurrogatesEscapeString() { string unicodeString = "\uD800\uDC00\uD803\uDE6D \uD834\uDD1E\uDBFF\uDFFF"; string expectedStr = "\"\\uD800\\uDC00\\uD803\\uDE6D \\uD834\\uDD1E\\uDBFF\\uDFFF\""; string json = $"\"{unicodeString}\""; var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(json)) { using (var writer = new Utf8JsonWriter(buffer)) { WriteSingleValue(doc, writer); } JsonTestHelper.AssertContents(expectedStr, buffer); } } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberOverpreciseAsProperty(bool indented) { WritePropertyValueBothForms( indented, "test property", "3.141592653589793238462643383279", @"{ ""test property"": 3.141592653589793238462643383279 }".NormalizeLineEndings(), "{\"test property\":3.141592653589793238462643383279}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNumberTooLargeAsProperty(bool indented) { WritePropertyValueBothForms( indented, // Arabic "kabir" => "big" "\u0643\u0628\u064A\u0631", "1e400", @"{ ""\u0643\u0628\u064A\u0631"": 1e400 }".NormalizeLineEndings(), "{\"\\u0643\\u0628\\u064A\\u0631\":1e400}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteAsciiStringAsProperty(bool indented) { WritePropertyValueBothForms( indented, "dinner", "\"pizza\"", @"{ ""dinner"": ""pizza"" }".NormalizeLineEndings(), "{\"dinner\":\"pizza\"}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEscapedStringAsProperty(bool indented) { WritePropertyValueBothForms( indented, "dinner", "\"p\\u0069zza\"", @"{ ""dinner"": ""pizza"" }".NormalizeLineEndings(), "{\"dinner\":\"pizza\"}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNonAsciiStringAsProperty(bool indented) { WritePropertyValueBothForms( indented, "lunch", "\"p\u00CDzza\"", @"{ ""lunch"": ""p\u00CDzza"" }".NormalizeLineEndings(), "{\"lunch\":\"p\\u00CDzza\"}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEscapedNonAsciiStringAsProperty(bool indented) { WritePropertyValueBothForms( indented, "lunch", "\"p\u00CDz\\u007Aa\"", @"{ ""lunch"": ""p\u00CDzza"" }".NormalizeLineEndings(), "{\"lunch\":\"p\\u00CDzza\"}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteTrueAsProperty(bool indented) { WritePropertyValueBothForms( indented, " boolean ", "true", @"{ "" boolean "": true }".NormalizeLineEndings(), "{\" boolean \":true}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteFalseAsProperty(bool indented) { WritePropertyValueBothForms( indented, " boolean ", "false", @"{ "" boolean "": false }".NormalizeLineEndings(), "{\" boolean \":false}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteNullAsProperty(bool indented) { WritePropertyValueBothForms( indented, "someProp", "null", @"{ ""someProp"": null }".NormalizeLineEndings(), "{\"someProp\":null}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyArrayAsProperty(bool indented) { WritePropertyValueBothForms( indented, "arr", "[ ]", @"{ ""arr"": [] }".NormalizeLineEndings(), "{\"arr\":[]}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyObjectAsProperty(bool indented) { WritePropertyValueBothForms( indented, "obj", "{ }", @"{ ""obj"": {} }".NormalizeLineEndings(), "{\"obj\":{}}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyCommentedArrayAsProperty(bool indented) { WritePropertyValueBothForms( indented, "arr", "[ /* 5 */ ]", @"{ ""arr"": [] }".NormalizeLineEndings(), "{\"arr\":[]}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEmptyCommentedObjectAsProperty(bool indented) { WritePropertyValueBothForms( indented, "obj", "{ /* Technically empty */ }", @"{ ""obj"": {} }".NormalizeLineEndings(), "{\"obj\":{}}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteSimpleArrayAsProperty(bool indented) { WritePropertyValueBothForms( indented, "valjean", "[ 2, 4, 6, 0, 1 /* Did you know that there's an asteroid: 24601 Valjean? */ ]", @"{ ""valjean"": [ 2, 4, 6, 0, 1 ] }".NormalizeLineEndings(), "{\"valjean\":[2,4,6,0,1]}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteSimpleObjectAsProperty(bool indented) { WritePropertyValueBothForms( indented, "bestMinorCharacter", @"{ ""r"" : 2, // Comments make everything more interesting. ""d"": 2 }".NormalizeLineEndings(), @"{ ""bestMinorCharacter"": { ""r"": 2, ""d"": 2 } }".NormalizeLineEndings(), "{\"bestMinorCharacter\":{\"r\":2,\"d\":2}}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEverythingArrayAsProperty(bool indented) { WritePropertyValueBothForms( indented, "data", @" [ ""Once upon a midnight dreary"", 42, /* Yep */ 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not requ\u0069red"", // More comments, more problems? ""Some th\u0069ngs get lost in the " + "m\u00EAl\u00E9e" + @""", // Array with an array (primes) [ 2, 3, 5, 7, /*9,*/ 11], { ""obj"": [ 21, { ""deep obj"": [ ""Once upon a midnight dreary"", 42, /* Yep */ 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not requ\u0069red"", // More comments, more problems? ""Some th\u0069ngs get lost in the " + "m\u00EAl\u00E9e" + @""" ], ""more deep"": false }, 12 ], ""second property"": null }] ", @"{ ""data"": [ ""Once upon a midnight dreary"", 42, 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not required"", ""Some things get lost in the m\u00EAl\u00E9e"", [ 2, 3, 5, 7, 11 ], { ""obj"": [ 21, { ""deep obj"": [ ""Once upon a midnight dreary"", 42, 1e400, 3.141592653589793238462643383279, false, true, null, ""Escaping is not required"", ""Some things get lost in the m\u00EAl\u00E9e"" ], ""more deep"": false }, 12 ], ""second property"": null } ] }".NormalizeLineEndings(), "{\"data\":[\"Once upon a midnight dreary\",42,1e400,3.141592653589793238462643383279," + "false,true,null,\"Escaping is not required\"," + "\"Some things get lost in the m\\u00EAl\\u00E9e\",[2,3,5,7,11]," + "{\"obj\":[21,{\"deep obj\":[\"Once upon a midnight dreary\",42,1e400," + "3.141592653589793238462643383279,false,true,null,\"Escaping is not required\"," + "\"Some things get lost in the m\\u00EAl\\u00E9e\"],\"more deep\":false},12]," + "\"second property\":null}]}"); } [Theory] [InlineData(false)] [InlineData(true)] public void WriteEverythingObjectAsProperty(bool indented) { WritePropertyValueBothForms( indented, "data", "{" + "\"int\": 42," + "\"quadratic googol\": 1e400," + "\"precisePi\": 3.141592653589793238462643383279," + "\"lit0\": null,\"lit1\": false,/*guess next*/\"lit2\": true," + "\"ascii\": \"pizza\"," + "\"escaped\": \"p\\u0069zza\"," + "\"utf8\": \"p\u00CDzza\"," + "\"utf8ExtraEscape\": \"p\u00CDz\\u007Aa\"," + "\"arr\": [\"hello\", \"sa\\u0069lor\", 21, \"blackjack!\" ]," + "\"obj\": {" + "\"arr\": [ 1, 3, 5, 7, /*9,*/ 11] " + "}}", @"{ ""data"": { ""int"": 42, ""quadratic googol"": 1e400, ""precisePi"": 3.141592653589793238462643383279, ""lit0"": null, ""lit1"": false, ""lit2"": true, ""ascii"": ""pizza"", ""escaped"": ""pizza"", ""utf8"": ""p\u00CDzza"", ""utf8ExtraEscape"": ""p\u00CDzza"", ""arr"": [ ""hello"", ""sailor"", 21, ""blackjack!"" ], ""obj"": { ""arr"": [ 1, 3, 5, 7, 11 ] } } }".NormalizeLineEndings(), "{\"data\":" + "{\"int\":42,\"quadratic googol\":1e400,\"precisePi\":3.141592653589793238462643383279," + "\"lit0\":null,\"lit1\":false,\"lit2\":true,\"ascii\":\"pizza\",\"escaped\":\"pizza\"," + "\"utf8\":\"p\\u00CDzza\",\"utf8ExtraEscape\":\"p\\u00CDzza\"," + "\"arr\":[\"hello\",\"sailor\",21,\"blackjack!\"]," + "\"obj\":{\"arr\":[1,3,5,7,11]}}}"); } [Fact] public void WriteIncredibleDepth() { const int TargetDepth = 500; JsonDocumentOptions optionsCopy = s_options; optionsCopy.MaxDepth = TargetDepth + 1; const int SpacesPre = 12; const int SpacesSplit = 85; const int SpacesPost = 4; byte[] jsonIn = new byte[SpacesPre + TargetDepth + SpacesSplit + TargetDepth + SpacesPost]; jsonIn.AsSpan(0, SpacesPre).Fill((byte)' '); Span<byte> openBrackets = jsonIn.AsSpan(SpacesPre, TargetDepth); openBrackets.Fill((byte)'['); jsonIn.AsSpan(SpacesPre + TargetDepth, SpacesSplit).Fill((byte)' '); Span<byte> closeBrackets = jsonIn.AsSpan(SpacesPre + TargetDepth + SpacesSplit, TargetDepth); closeBrackets.Fill((byte)']'); jsonIn.AsSpan(SpacesPre + TargetDepth + SpacesSplit + TargetDepth).Fill((byte)' '); var buffer = new ArrayBufferWriter<byte>(jsonIn.Length); using (JsonDocument doc = JsonDocument.Parse(jsonIn, optionsCopy)) { using (var writer = new Utf8JsonWriter(buffer)) { WriteDocument(doc, writer); } ReadOnlySpan<byte> formatted = buffer.WrittenSpan; Assert.Equal(TargetDepth + TargetDepth, formatted.Length); Assert.True(formatted.Slice(0, TargetDepth).SequenceEqual(openBrackets), "OpenBrackets match"); Assert.True(formatted.Slice(TargetDepth).SequenceEqual(closeBrackets), "CloseBrackets match"); } } [Theory] [InlineData(false, "\"message\"", "\"message\"", true)] [InlineData(true, "\"message\"", "\"message\"", true)] [InlineData(false, "\">><++>>>\\\">>\\\\>>&>>>\u6f22\u5B57>>>\"", "\">><++>>>\\\">>\\\\>>&>>>\u6f22\u5B57>>>\"", false)] [InlineData(true, "\">><++>>>\\\">>\\\\>>&>>>\u6f22\u5B57>>>\"", "\">><++>>>\\\">>\\\\>>&>>>\u6f22\u5B57>>>\"", false)] [InlineData(false, "\"mess\\r\\nage\\u0008\\u0001!\"", "\"mess\\r\\nage\\b\\u0001!\"", true)] [InlineData(true, "\"mess\\r\\nage\\u0008\\u0001!\"", "\"mess\\r\\nage\\b\\u0001!\"", true)] public void WriteWithRelaxedEscaper(bool indented, string jsonIn, string jsonOut, bool matchesRelaxedEscaping) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { WriteSingleValue(doc, writer); } if (matchesRelaxedEscaping) { JsonTestHelper.AssertContents(jsonOut, buffer); } else { JsonTestHelper.AssertContentsNotEqual(jsonOut, buffer); } } buffer.Clear(); { var options = new JsonWriterOptions { Indented = indented, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; using (var writer = new Utf8JsonWriter(buffer, options)) { WriteSingleValue(doc, writer); } JsonTestHelper.AssertContents(jsonOut, buffer); } } } private void WriteSimpleValue(bool indented, string jsonIn, string jsonOut = null) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { WriteSingleValue(doc, writer); } JsonTestHelper.AssertContents(jsonOut ?? jsonIn, buffer); } } private void WriteComplexValue( bool indented, string jsonIn, string expectedIndent, string expectedMinimal) { var buffer = new ArrayBufferWriter<byte>(1024); byte[] bufferOutput; var options = new JsonWriterOptions { Indented = indented }; using (JsonDocument doc = PrepareDocument(jsonIn)) { using (var writer = new Utf8JsonWriter(buffer, options)) { WriteSingleValue(doc, writer); } JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer); bufferOutput = buffer.WrittenSpan.ToArray(); } // After reading the output and writing it again, it should be byte-for-byte identical. { string bufferString = Encoding.UTF8.GetString(bufferOutput); buffer.Clear(); using (JsonDocument doc2 = PrepareDocument(bufferString)) { using (var writer = new Utf8JsonWriter(buffer, options)) { WriteSingleValue(doc2, writer); } } Assert.True(buffer.WrittenSpan.SequenceEqual(bufferOutput)); } } private void WritePropertyValueBothForms( bool indented, string propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { WritePropertyValue( indented, propertyName, jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, propertyName.AsSpan(), jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, Encoding.UTF8.GetBytes(propertyName ?? ""), jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, JsonEncodedText.Encode(propertyName.AsSpan()), jsonIn, expectedIndent, expectedMinimal); } private void WritePropertyValue( bool indented, string propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { writer.WriteStartObject(); writer.WritePropertyName(propertyName); WriteSingleValue(doc, writer); writer.WriteEndObject(); } JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer); } } private void WritePropertyValue( bool indented, ReadOnlySpan<char> propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { writer.WriteStartObject(); writer.WritePropertyName(propertyName); WriteSingleValue(doc, writer); writer.WriteEndObject(); } JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer); } } private void WritePropertyValue( bool indented, ReadOnlySpan<byte> propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { writer.WriteStartObject(); writer.WritePropertyName(propertyName); WriteSingleValue(doc, writer); writer.WriteEndObject(); } JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer); } } private void WritePropertyValue( bool indented, JsonEncodedText propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { var buffer = new ArrayBufferWriter<byte>(1024); using (JsonDocument doc = PrepareDocument(jsonIn)) { var options = new JsonWriterOptions { Indented = indented, }; using (var writer = new Utf8JsonWriter(buffer, options)) { writer.WriteStartObject(); writer.WritePropertyName(propertyName); WriteSingleValue(doc, writer); writer.WriteEndObject(); } JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenMetaverse; namespace Aurora.Framework { public delegate void RaycastCallback( bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 normal); public delegate void RayCallback(List<ContactResult> list); public struct ContactResult { public uint ConsumerID; public float Depth; public Vector3 Normal; public Vector3 Pos; } public delegate void OnCollisionEvent(PhysicsActor actor, PhysicsActor collidedActor, ContactPoint contact); public abstract class PhysicsScene { public virtual float TimeDilation { get { return 1.0f; } set { } } public virtual float StepTime { get { return 0; } } public virtual bool IsThreaded { get { return false; } } public virtual bool DisableCollisions { get; set; } public virtual List<PhysicsObject> ActiveObjects { get { return null; } } public virtual bool UseUnderWaterPhysics { get { return false; } } public virtual int StatPhysicsTaintTime { get; protected set; } public virtual int StatPhysicsMoveTime { get; protected set; } public virtual int StatCollisionOptimizedTime { get; protected set; } public virtual int StatSendCollisionsTime { get; protected set; } public virtual int StatAvatarUpdatePosAndVelocity { get; protected set; } public virtual int StatPrimUpdatePosAndVelocity { get; protected set; } public virtual int StatUnlockedArea { get; protected set; } public virtual int StatFindContactsTime { get; protected set; } public virtual int StatContactLoopTime { get; protected set; } public virtual int StatCollisionAccountingTime { get; protected set; } public abstract void Initialise(IMesher meshmerizer, RegionInfo region, IRegistryCore registry); public abstract void PostInitialise(IConfigSource config); public abstract PhysicsCharacter AddAvatar(string avName, Vector3 position, Quaternion rotation, Vector3 size, bool isFlying, uint LocalID, UUID UUID); public abstract void RemoveAvatar(PhysicsCharacter actor); public abstract void RemovePrim(PhysicsObject prim); public abstract void DeletePrim(PhysicsObject prim); public abstract PhysicsObject AddPrimShape(ISceneChildEntity entity); public abstract void Simulate(float timeStep); public virtual void GetResults() { } public abstract void SetTerrain(ITerrainChannel channel, short[] heightMap); public abstract void SetWaterLevel(double height, short[] map); public abstract void Dispose(); public abstract Dictionary<uint, float> GetTopColliders(); /// <summary> /// True if the physics plugin supports raycasting against the physics scene /// </summary> public virtual bool SupportsRayCast() { return false; } /// <summary> /// Queue a raycast against the physics scene. /// The provided callback method will be called when the raycast is complete /// /// Many physics engines don't support collision testing at the same time as /// manipulating the physics scene, so we queue the request up and callback /// a custom method when the raycast is complete. /// This allows physics engines that give an immediate result to callback immediately /// and ones that don't, to callback when it gets a result back. /// /// ODE for example will not allow you to change the scene while collision testing or /// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene. /// /// This is named RayCastWorld to not conflict with modrex's Raycast method. /// </summary> /// <param name = "position">Origin of the ray</param> /// <param name = "direction">Direction of the ray</param> /// <param name = "length">Length of ray in meters</param> /// <param name = "retMethod">Method to call when the raycast is complete</param> public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod) { if (retMethod != null) retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero); } public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod) { if (retMethod != null) retMethod(new List<ContactResult>()); } public virtual List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count) { return new List<ContactResult>(); } public virtual void SetGravityForce(bool enabled, float forceX, float forceY, float forceZ) { } public virtual float[] GetGravityForce() { return new float[3] {0, 0, 0}; } public virtual void AddGravityPoint(bool isApplyingForces, Vector3 position, float forceX, float forceY, float forceZ, float gravForce, float radius, int identifier) { } public virtual void UpdatesLoop() { } } public class NullPhysicsScene : PhysicsScene { private static int m_workIndicator; public override bool DisableCollisions { get { return false; } set { } } public override bool UseUnderWaterPhysics { get { return false; } } public override void Initialise(IMesher meshmerizer, RegionInfo region, IRegistryCore registry) { // Does nothing right now } public override void PostInitialise(IConfigSource config) { } public override PhysicsCharacter AddAvatar(string avName, Vector3 position, Quaternion rotation, Vector3 size, bool isFlying, uint localID, UUID UUID) { MainConsole.Instance.InfoFormat("[PHYSICS]: NullPhysicsScene : AddAvatar({0})", position); return new NullCharacterPhysicsActor(); } public override void RemoveAvatar(PhysicsCharacter actor) { } public override void RemovePrim(PhysicsObject prim) { } public override void DeletePrim(PhysicsObject prim) { } public override void SetWaterLevel(double height, short[] map) { } /* public override PhysicsActor AddPrim(Vector3 position, Vector3 size, Quaternion rotation) { MainConsole.Instance.InfoFormat("NullPhysicsScene : AddPrim({0},{1})", position, size); return PhysicsActor.Null; } */ public override PhysicsObject AddPrimShape(ISceneChildEntity entity) { return new NullObjectPhysicsActor(); } public override void Simulate(float timeStep) { m_workIndicator = (m_workIndicator + 1)%10; } public override void SetTerrain(ITerrainChannel channel, short[] heightMap) { MainConsole.Instance.InfoFormat("[PHYSICS]: NullPhysicsScene : SetTerrain({0} items)", heightMap.Length); } public override void Dispose() { } public override Dictionary<uint, float> GetTopColliders() { Dictionary<uint, float> returncolliders = new Dictionary<uint, float>(); return returncolliders; } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Xml.XPath; using System.Xml.Schema; using System.Xml.Xsl.Qil; using System.Xml.Xsl.XPath; namespace System.Xml.Xsl.Xslt { using T = XmlQueryTypeFactory; internal class XPathPatternBuilder : XPathPatternParser.IPatternBuilder { private XPathPredicateEnvironment _predicateEnvironment; private XPathBuilder _predicateBuilder; private bool _inTheBuild; private XPathQilFactory _f; private QilNode _fixupNode; private IXPathEnvironment _environment; public XPathPatternBuilder(IXPathEnvironment environment) { Debug.Assert(environment != null); _environment = environment; _f = environment.Factory; _predicateEnvironment = new XPathPredicateEnvironment(environment); _predicateBuilder = new XPathBuilder(_predicateEnvironment); _fixupNode = _f.Unknown(T.NodeNotRtfS); } public QilNode FixupNode { get { return _fixupNode; } } public virtual void StartBuild() { Debug.Assert(!_inTheBuild, "XPathBuilder is buisy!"); _inTheBuild = true; return; } [Conditional("DEBUG")] public void AssertFilter(QilLoop filter) { Debug.Assert(filter.NodeType == QilNodeType.Filter, "XPathPatternBuilder expected to generate list of Filters on top level"); Debug.Assert(filter.Variable.XmlType.IsSubtypeOf(T.NodeNotRtf)); Debug.Assert(filter.Variable.Binding.NodeType == QilNodeType.Unknown); // fixupNode Debug.Assert(filter.Body.XmlType.IsSubtypeOf(T.Boolean)); } private void FixupFilterBinding(QilLoop filter, QilNode newBinding) { AssertFilter(filter); filter.Variable.Binding = newBinding; } public virtual QilNode EndBuild(QilNode result) { Debug.Assert(_inTheBuild, "StartBuild() wasn't called"); if (result == null) { // Special door to clean builder state in exception handlers } // All these variables will be positive for "false() and (. = position() + last())" // since QilPatternFactory eliminates the right operand of 'and' Debug.Assert(_predicateEnvironment.numFixupCurrent >= 0, "Context fixup error"); Debug.Assert(_predicateEnvironment.numFixupPosition >= 0, "Context fixup error"); Debug.Assert(_predicateEnvironment.numFixupLast >= 0, "Context fixup error"); _inTheBuild = false; return result; } public QilNode Operator(XPathOperator op, QilNode left, QilNode right) { Debug.Assert(op == XPathOperator.Union); Debug.Assert(left != null); Debug.Assert(right != null); // It is important to not create nested lists here Debug.Assert(right.NodeType == QilNodeType.Filter, "LocationPathPattern must be compiled into a filter"); if (left.NodeType == QilNodeType.Sequence) { ((QilList)left).Add(right); return left; } else { Debug.Assert(left.NodeType == QilNodeType.Filter, "LocationPathPattern must be compiled into a filter"); return _f.Sequence(left, right); } } private static QilLoop BuildAxisFilter(QilPatternFactory f, QilIterator itr, XPathAxis xpathAxis, XPathNodeType nodeType, string name, string nsUri) { QilNode nameTest = ( name != null && nsUri != null ? f.Eq(f.NameOf(itr), f.QName(name, nsUri)) : // ns:bar || bar nsUri != null ? f.Eq(f.NamespaceUriOf(itr), f.String(nsUri)) : // ns:* name != null ? f.Eq(f.LocalNameOf(itr), f.String(name)) : // *:foo /*name == nsUri == null*/ f.True() // * ); XmlNodeKindFlags intersection = XPathBuilder.AxisTypeMask(itr.XmlType.NodeKinds, nodeType, xpathAxis); QilNode typeTest = ( intersection == 0 ? f.False() : // input & required doesn't intersect intersection == itr.XmlType.NodeKinds ? f.True() : // input is subset of required /*else*/ f.IsType(itr, T.NodeChoice(intersection)) ); QilLoop filter = f.BaseFactory.Filter(itr, f.And(typeTest, nameTest)); filter.XmlType = T.PrimeProduct(T.NodeChoice(intersection), filter.XmlType.Cardinality); return filter; } public QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string prefix, string name) { Debug.Assert( xpathAxis == XPathAxis.Child || xpathAxis == XPathAxis.Attribute || xpathAxis == XPathAxis.DescendantOrSelf || xpathAxis == XPathAxis.Root ); QilLoop result; double priority; switch (xpathAxis) { case XPathAxis.DescendantOrSelf: Debug.Assert(nodeType == XPathNodeType.All && prefix == null && name == null, " // is the only d-o-s axes that we can have in pattern"); return _f.Nop(_fixupNode); // We using Nop as a flag that DescendantOrSelf exis was used between steps. case XPathAxis.Root: QilIterator i; result = _f.BaseFactory.Filter(i = _f.For(_fixupNode), _f.IsType(i, T.Document)); priority = 0.5; break; default: string nsUri = prefix == null ? null : _environment.ResolvePrefix(prefix); result = BuildAxisFilter(_f, _f.For(_fixupNode), xpathAxis, nodeType, name, nsUri); switch (nodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: if (name != null) { priority = 0; } else { if (prefix != null) { priority = -0.25; } else { priority = -0.5; } } break; case XPathNodeType.ProcessingInstruction: priority = name != null ? 0 : -0.5; break; default: priority = -0.5; break; } break; } SetPriority(result, priority); SetLastParent(result, result); return result; } // a/b/c -> self::c[parent::b[parent::a]] // a/b//c -> self::c[ancestor::b[parent::a]] // a/b -> self::b[parent::a] // -> JoinStep(Axis('a'), Axis('b')) // -> Filter('b' & Parent(Filter('a'))) // a//b // -> JoinStep(Axis('a'), JoingStep(Axis(DescendantOrSelf), Axis('b'))) // -> JoinStep(Filter('a'), JoingStep(Nop(null), Filter('b'))) // -> JoinStep(Filter('a'), Nop(Filter('b'))) // -> Filter('b' & Ancestor(Filter('a'))) public QilNode JoinStep(QilNode left, QilNode right) { Debug.Assert(left != null); Debug.Assert(right != null); if (left.NodeType == QilNodeType.Nop) { QilUnary nop = (QilUnary)left; Debug.Assert(nop.Child == _fixupNode); nop.Child = right; // We use Nop as a flag that DescendantOrSelf axis was used between steps. return nop; } Debug.Assert(GetLastParent(left) == left, "Left is always single axis and never the step"); Debug.Assert(left.NodeType == QilNodeType.Filter); CleanAnnotation(left); QilLoop parentFilter = (QilLoop)left; bool ancestor = false; { if (right.NodeType == QilNodeType.Nop) { ancestor = true; QilUnary nop = (QilUnary)right; Debug.Assert(nop.Child != null); right = nop.Child; } } Debug.Assert(right.NodeType == QilNodeType.Filter); QilLoop lastParent = GetLastParent(right); FixupFilterBinding(parentFilter, ancestor ? _f.Ancestor(lastParent.Variable) : _f.Parent(lastParent.Variable)); lastParent.Body = _f.And(lastParent.Body, _f.Not(_f.IsEmpty(parentFilter))); SetPriority(right, 0.5); SetLastParent(right, parentFilter); return right; } QilNode IXPathBuilder<QilNode>.Predicate(QilNode node, QilNode condition, bool isReverseStep) { Debug.Assert(false, "Should not call to this function."); return null; } //The structure of result is a Filter, variable is current node, body is the match condition. //Previous predicate build logic in XPathPatternBuilder is match from right to left, which have 2^n complexiy when have lots of position predicates. TFS #368771 //Now change the logic to: If predicates contains position/last predicates, given the current node, filter out all the nodes that match the predicates, //and then check if current node is in the result set. public QilNode BuildPredicates(QilNode nodeset, List<QilNode> predicates) { //convert predicates to boolean type List<QilNode> convertedPredicates = new List<QilNode>(predicates.Count); foreach (var predicate in predicates) { convertedPredicates.Add(XPathBuilder.PredicateToBoolean(predicate, _f, _predicateEnvironment)); } QilLoop nodeFilter = (QilLoop)nodeset; QilIterator current = nodeFilter.Variable; //If no last() and position() in predicates, use nodeFilter.Variable to fixup current //because all the predicates only based on the input variable, no matter what other predicates are. if (_predicateEnvironment.numFixupLast == 0 && _predicateEnvironment.numFixupPosition == 0) { foreach (var predicate in convertedPredicates) { nodeFilter.Body = _f.And(nodeFilter.Body, predicate); } nodeFilter.Body = _predicateEnvironment.fixupVisitor.Fixup(nodeFilter.Body, current, null); } //If any preidcate contains last() or position() node, then the current node is based on previous predicates, //for instance, a[...][2] is match second node after filter 'a[...]' instead of second 'a'. else { //filter out the siblings QilIterator parentIter = _f.For(_f.Parent(current)); QilNode sibling = _f.Content(parentIter); //generate filter based on input filter QilLoop siblingFilter = (QilLoop)nodeset.DeepClone(_f.BaseFactory); siblingFilter.Variable.Binding = sibling; siblingFilter = (QilLoop)_f.Loop(parentIter, siblingFilter); //build predicates from left to right to get all the matching nodes QilNode matchingSet = siblingFilter; foreach (var predicate in convertedPredicates) { matchingSet = XPathBuilder.BuildOnePredicate(matchingSet, predicate, /*isReverseStep*/false, _f, _predicateEnvironment.fixupVisitor, ref _predicateEnvironment.numFixupCurrent, ref _predicateEnvironment.numFixupPosition, ref _predicateEnvironment.numFixupLast); } //check if the matching nodes contains the current node QilIterator matchNodeIter = _f.For(matchingSet); QilNode filterCurrent = _f.Filter(matchNodeIter, _f.Is(matchNodeIter, current)); nodeFilter.Body = _f.Not(_f.IsEmpty(filterCurrent)); //for passing type check, explicit say the result is target type nodeFilter.Body = _f.And(_f.IsType(current, nodeFilter.XmlType), nodeFilter.Body); } SetPriority(nodeset, 0.5); return nodeset; } public QilNode Function(string prefix, string name, IList<QilNode> args) { Debug.Assert(prefix.Length == 0); QilIterator i = _f.For(_fixupNode); QilNode matches; if (name == "id") { Debug.Assert( args.Count == 1 && args[0].NodeType == QilNodeType.LiteralString, "Function id() must have one literal string argument" ); matches = _f.Id(i, args[0]); } else { Debug.Assert(name == "key", "Unexpected function"); Debug.Assert( args.Count == 2 && args[0].NodeType == QilNodeType.LiteralString && args[1].NodeType == QilNodeType.LiteralString, "Function key() must have two literal string arguments" ); matches = _environment.ResolveFunction(prefix, name, args, new XsltFunctionFocus(i)); } QilIterator j; QilLoop result = _f.BaseFactory.Filter(i, _f.Not(_f.IsEmpty(_f.Filter(j = _f.For(matches), _f.Is(j, i))))); SetPriority(result, 0.5); SetLastParent(result, result); return result; } public QilNode String(string value) { return _f.String(value); } // As argument of id() or key() function public QilNode Number(double value) { return UnexpectedToken("Literal number"); } public QilNode Variable(string prefix, string name) { return UnexpectedToken("Variable"); } private QilNode UnexpectedToken(string tokenName) { string prompt = string.Format(CultureInfo.InvariantCulture, "Internal Error: {0} is not allowed in XSLT pattern outside of predicate.", tokenName); Debug.Assert(false, prompt); throw new Exception(prompt); } // -------------------------------------- Priority / Parent --------------------------------------- private class Annotation { public double Priority; public QilLoop Parent; } public static void SetPriority(QilNode node, double priority) { Annotation ann = (Annotation)node.Annotation ?? new Annotation(); ann.Priority = priority; node.Annotation = ann; } public static double GetPriority(QilNode node) { return ((Annotation)node.Annotation).Priority; } private static void SetLastParent(QilNode node, QilLoop parent) { Debug.Assert(parent.NodeType == QilNodeType.Filter); Annotation ann = (Annotation)node.Annotation ?? new Annotation(); ann.Parent = parent; node.Annotation = ann; } private static QilLoop GetLastParent(QilNode node) { return ((Annotation)node.Annotation).Parent; } public static void CleanAnnotation(QilNode node) { node.Annotation = null; } // -------------------------------------- GetPredicateBuilder() --------------------------------------- public IXPathBuilder<QilNode> GetPredicateBuilder(QilNode ctx) { QilLoop context = (QilLoop)ctx; Debug.Assert(context != null, "Predicate always has step so it can't have context == null"); Debug.Assert(context.Variable.NodeType == QilNodeType.For, "It shouldn't be Let, becaus predicates in PatternBuilder don't produce cached tuples."); return _predicateBuilder; } private class XPathPredicateEnvironment : IXPathEnvironment { private readonly IXPathEnvironment _baseEnvironment; private readonly XPathQilFactory _f; public readonly XPathBuilder.FixupVisitor fixupVisitor; private readonly QilNode _fixupCurrent, _fixupPosition, _fixupLast; // Number of unresolved fixup nodes public int numFixupCurrent, numFixupPosition, numFixupLast; public XPathPredicateEnvironment(IXPathEnvironment baseEnvironment) { _baseEnvironment = baseEnvironment; _f = baseEnvironment.Factory; _fixupCurrent = _f.Unknown(T.NodeNotRtf); _fixupPosition = _f.Unknown(T.DoubleX); _fixupLast = _f.Unknown(T.DoubleX); this.fixupVisitor = new XPathBuilder.FixupVisitor(_f, _fixupCurrent, _fixupPosition, _fixupLast); } /* ---------------------------------------------------------------------------- IXPathEnvironment interface */ public XPathQilFactory Factory { get { return _f; } } public QilNode ResolveVariable(string prefix, string name) { return _baseEnvironment.ResolveVariable(prefix, name); } public QilNode ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env) { return _baseEnvironment.ResolveFunction(prefix, name, args, env); } public string ResolvePrefix(string prefix) { return _baseEnvironment.ResolvePrefix(prefix); } public QilNode GetCurrent() { numFixupCurrent++; return _fixupCurrent; } public QilNode GetPosition() { numFixupPosition++; return _fixupPosition; } public QilNode GetLast() { numFixupLast++; return _fixupLast; } } private class XsltFunctionFocus : IFocus { private QilIterator _current; public XsltFunctionFocus(QilIterator current) { Debug.Assert(current != null); _current = current; } /* ---------------------------------------------------------------------------- IFocus interface */ public QilNode GetCurrent() { return _current; } public QilNode GetPosition() { Debug.Fail("GetPosition() must not be called"); return null; } public QilNode GetLast() { Debug.Fail("GetLast() must not be called"); return null; } } } }
// InflaterInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 11-08-2009 GeoffHart T9121 Added Multi-member gzip support using System; using System.IO; #if !NETCF_1_0 && !XBOX using System.Security.Cryptography; #endif namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// An input buffer customised for use by <see cref="InflaterInputStream"/> /// </summary> /// <remarks> /// The buffer supports decryption of incoming data. /// </remarks> public class InflaterInputBuffer { #region Constructors /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size /// </summary> /// <param name="stream">The stream to buffer.</param> public InflaterInputBuffer(Stream stream) : this(stream , 4096) { } /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> /// </summary> /// <param name="stream">The stream to buffer.</param> /// <param name="bufferSize">The size to use for the buffer</param> /// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks> public InflaterInputBuffer(Stream stream, int bufferSize) { inputStream = stream; if ( bufferSize < 1024 ) { bufferSize = 1024; } rawData = new byte[bufferSize]; clearText = rawData; } #endregion /// <summary> /// Get the length of bytes bytes in the <see cref="RawData"/> /// </summary> public int RawLength { get { return rawLength; } } /// <summary> /// Get the contents of the raw data buffer. /// </summary> /// <remarks>This may contain encrypted data.</remarks> public byte[] RawData { get { return rawData; } } /// <summary> /// Get the number of useable bytes in <see cref="ClearText"/> /// </summary> public int ClearTextLength { get { return clearTextLength; } } /// <summary> /// Get the contents of the clear text buffer. /// </summary> public byte[] ClearText { get { return clearText; } } /// <summary> /// Get/set the number of bytes available /// </summary> public int Available { get { return available; } set { available = value; } } /// <summary> /// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents. /// </summary> /// <param name="inflater">The inflater to set input for.</param> public void SetInflaterInput(Inflater inflater) { if ( available > 0 ) { inflater.SetInput(clearText, clearTextLength - available, available); available = 0; } } /// <summary> /// Fill the buffer from the underlying input stream. /// </summary> public void Fill() { rawLength = 0; int toRead = rawData.Length; while (toRead > 0) { int count = inputStream.Read(rawData, rawLength, toRead); if ( count <= 0 ) { break; } rawLength += count; toRead -= count; } #if !NETCF_1_0 && !XBOX if ( cryptoTransform != null ) { clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); } else #endif { clearTextLength = rawLength; } available = clearTextLength; } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="buffer">The buffer to fill</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] buffer) { return ReadRawBuffer(buffer, 0, buffer.Length); } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="outBuffer">The buffer to read into</param> /// <param name="offset">The offset to start reading data into.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read clear text data from the input stream. /// </summary> /// <param name="outBuffer">The buffer to add data to.</param> /// <param name="offset">The offset to start adding data at.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read a <see cref="byte"/> from the input stream. /// </summary> /// <returns>Returns the byte read.</returns> public int ReadLeByte() { if (available <= 0) { Fill(); if (available <= 0) { throw new ZipException("EOF in header"); } } byte result = rawData[rawLength - available]; available -= 1; return result; } /// <summary> /// Read an <see cref="short"/> in little endian byte order. /// </summary> /// <returns>The short value read case to an int.</returns> public int ReadLeShort() { return ReadLeByte() | (ReadLeByte() << 8); } /// <summary> /// Read an <see cref="int"/> in little endian byte order. /// </summary> /// <returns>The int value read.</returns> public int ReadLeInt() { return ReadLeShort() | (ReadLeShort() << 16); } /// <summary> /// Read a <see cref="long"/> in little endian byte order. /// </summary> /// <returns>The long value read.</returns> public long ReadLeLong() { return (uint)ReadLeInt() | ((long)ReadLeInt() << 32); } #if !NETCF_1_0 && !XBOX /// <summary> /// Get/set the <see cref="ICryptoTransform"/> to apply to any data. /// </summary> /// <remarks>Set this value to null to have no transform applied.</remarks> public ICryptoTransform CryptoTransform { set { cryptoTransform = value; if ( cryptoTransform != null ) { if ( rawData == clearText ) { if ( internalClearText == null ) { internalClearText = new byte[rawData.Length]; } clearText = internalClearText; } clearTextLength = rawLength; if ( available > 0 ) { cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); } } else { clearText = rawData; clearTextLength = rawLength; } } } #endif #region Instance Fields int rawLength; byte[] rawData; int clearTextLength; byte[] clearText; #if !NETCF_1_0 && !XBOX byte[] internalClearText; #endif int available; #if !NETCF_1_0 && !XBOX ICryptoTransform cryptoTransform; #endif Stream inputStream; #endregion } /// <summary> /// This filter stream is used to decompress data compressed using the "deflate" /// format. The "deflate" format is described in RFC 1951. /// /// This stream may form the basis for other decompression filters, such /// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>. /// /// Author of the original java version : John Leuner. /// </summary> public class InflaterInputStream : Stream { #region Constructors /// <summary> /// Create an InflaterInputStream with the default decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> public InflaterInputStream(Stream baseInputStream) : this(baseInputStream, new Inflater(), 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and the specified buffer size. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> /// <param name = "inflater"> /// The decompressor to use /// </param> /// <param name = "bufferSize"> /// Size of the buffer to use /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { if (baseInputStream == null) { throw new ArgumentNullException("baseInputStream"); } if (inflater == null) { throw new ArgumentNullException("inflater"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); } #endregion /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"/> will close the underlying stream also. /// </summary> /// <remarks> /// The default value is true. /// </remarks> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } /// <summary> /// Skip specified number of bytes of uncompressed data /// </summary> /// <param name ="count"> /// Number of bytes to skip /// </param> /// <returns> /// The number of bytes skipped, zero if the end of /// stream has been reached /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero. /// </exception> public long Skip(long count) { if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } // v0.80 Skip by seeking if underlying stream supports it... if (baseInputStream.CanSeek) { baseInputStream.Seek(count, SeekOrigin.Current); return count; } else { int length = 2048; if (count < length) { length = (int) count; } byte[] tmp = new byte[length]; int readCount = 1; long toSkip = count; while ((toSkip > 0) && (readCount > 0) ) { if (toSkip < length) { length = (int)toSkip; } readCount = baseInputStream.Read(tmp, 0, length); toSkip -= readCount; } return count - toSkip; } } /// <summary> /// Clear any cryptographic state. /// </summary> protected void StopDecrypting() { #if !NETCF_1_0 && !XBOX inputBuffer.CryptoTransform = null; #endif } /// <summary> /// Returns 0 once the end of the stream (EOF) has been reached. /// Otherwise returns 1. /// </summary> public virtual int Available { get { return inf.IsFinished ? 0 : 1; } } /// <summary> /// Fills the buffer with more data to decompress. /// </summary> /// <exception cref="SharpZipBaseException"> /// Stream ends early /// </exception> protected void Fill() { // Protect against redundant calls if (inputBuffer.Available <= 0) { inputBuffer.Fill(); if (inputBuffer.Available <= 0) { throw new SharpZipBaseException("Unexpected EOF"); } } inputBuffer.SetInflaterInput(inf); } #region Stream Overrides /// <summary> /// Gets a value indicating whether the current stream supports reading /// </summary> public override bool CanRead { get { return baseInputStream.CanRead; } } /// <summary> /// Gets a value of false indicating seeking is not supported for this stream. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value of false indicating that this stream is not writeable. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// A value representing the length of the stream in bytes. /// </summary> public override long Length { get { return inputBuffer.RawLength; } } /// <summary> /// The current position within the stream. /// Throws a NotSupportedException when attempting to set the position /// </summary> /// <exception cref="NotSupportedException">Attempting to set the position</exception> public override long Position { get { return baseInputStream.Position; } set { throw new NotSupportedException("InflaterInputStream Position not supported"); } } /// <summary> /// Flushes the baseInputStream /// </summary> public override void Flush() { baseInputStream.Flush(); } /// <summary> /// Sets the position within the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="offset">The relative offset to seek to.</param> /// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seek not supported"); } /// <summary> /// Set the length of the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="value">The new length value for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("InflaterInputStream SetLength not supported"); } /// <summary> /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException /// </summary> /// <param name="buffer">Thew buffer containing data to write.</param> /// <param name="offset">The offset of the first byte to write.</param> /// <param name="count">The number of bytes to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("InflaterInputStream Write not supported"); } /// <summary> /// Writes one byte to the current stream and advances the current position /// Always throws a NotSupportedException /// </summary> /// <param name="value">The byte to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("InflaterInputStream WriteByte not supported"); } /// <summary> /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. /// </summary> /// <param name="buffer">The buffer to write data from</param> /// <param name="offset">Offset of first byte to write</param> /// <param name="count">The maximum number of bytes to write</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param> /// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); } /// <summary> /// Closes the input stream. When <see cref="IsStreamOwner"></see> /// is true the underlying stream is also closed. /// </summary> public override void Close() { if ( !isClosed ) { isClosed = true; if ( isStreamOwner ) { baseInputStream.Close(); } } } /// <summary> /// Reads decompressed data into the provided buffer byte array /// </summary> /// <param name ="buffer"> /// The array to read and decompress data into /// </param> /// <param name ="offset"> /// The offset indicating where the data should be placed /// </param> /// <param name ="count"> /// The number of bytes to decompress /// </param> /// <returns>The number of bytes read. Zero signals the end of stream</returns> /// <exception cref="SharpZipBaseException"> /// Inflater needs a dictionary /// </exception> public override int Read(byte[] buffer, int offset, int count) { if (inf.IsNeedingDictionary) { throw new SharpZipBaseException("Need a dictionary"); } int remainingBytes = count; while (true) { int bytesRead = inf.Inflate(buffer, offset, remainingBytes); offset += bytesRead; remainingBytes -= bytesRead; if (remainingBytes == 0 || inf.IsFinished) { break; } if ( inf.IsNeedingInput ) { Fill(); } else if ( bytesRead == 0 ) { throw new ZipException("Dont know what to do"); } } return count - remainingBytes; } #endregion #region Instance Fields /// <summary> /// Decompressor for this stream /// </summary> protected Inflater inf; /// <summary> /// <see cref="InflaterInputBuffer">Input buffer</see> for this stream. /// </summary> protected InflaterInputBuffer inputBuffer; /// <summary> /// Base stream the inflater reads from. /// </summary> private Stream baseInputStream; /// <summary> /// The compressed size /// </summary> protected long csize; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Flag indicating wether this instance is designated the stream owner. /// When closing if this flag is true the underlying stream is closed. /// </summary> bool isStreamOwner = true; #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// BrandResources /// </summary> [DataContract] public partial class BrandResources : IEquatable<BrandResources>, IValidatableObject { public BrandResources() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="BrandResources" /> class. /// </summary> /// <param name="CreatedByUserInfo">CreatedByUserInfo.</param> /// <param name="CreatedDate">.</param> /// <param name="ModifiedByUserInfo">ModifiedByUserInfo.</param> /// <param name="ModifiedDate">.</param> /// <param name="ModifiedTemplates">.</param> /// <param name="ResourcesContentType">.</param> /// <param name="ResourcesContentUri">.</param> public BrandResources(UserInfo CreatedByUserInfo = default(UserInfo), string CreatedDate = default(string), UserInfo ModifiedByUserInfo = default(UserInfo), string ModifiedDate = default(string), List<string> ModifiedTemplates = default(List<string>), string ResourcesContentType = default(string), string ResourcesContentUri = default(string)) { this.CreatedByUserInfo = CreatedByUserInfo; this.CreatedDate = CreatedDate; this.ModifiedByUserInfo = ModifiedByUserInfo; this.ModifiedDate = ModifiedDate; this.ModifiedTemplates = ModifiedTemplates; this.ResourcesContentType = ResourcesContentType; this.ResourcesContentUri = ResourcesContentUri; } /// <summary> /// Gets or Sets CreatedByUserInfo /// </summary> [DataMember(Name="createdByUserInfo", EmitDefaultValue=false)] public UserInfo CreatedByUserInfo { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="createdDate", EmitDefaultValue=false)] public string CreatedDate { get; set; } /// <summary> /// Gets or Sets ModifiedByUserInfo /// </summary> [DataMember(Name="modifiedByUserInfo", EmitDefaultValue=false)] public UserInfo ModifiedByUserInfo { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="modifiedDate", EmitDefaultValue=false)] public string ModifiedDate { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="modifiedTemplates", EmitDefaultValue=false)] public List<string> ModifiedTemplates { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="resourcesContentType", EmitDefaultValue=false)] public string ResourcesContentType { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="resourcesContentUri", EmitDefaultValue=false)] public string ResourcesContentUri { 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 BrandResources {\n"); sb.Append(" CreatedByUserInfo: ").Append(CreatedByUserInfo).Append("\n"); sb.Append(" CreatedDate: ").Append(CreatedDate).Append("\n"); sb.Append(" ModifiedByUserInfo: ").Append(ModifiedByUserInfo).Append("\n"); sb.Append(" ModifiedDate: ").Append(ModifiedDate).Append("\n"); sb.Append(" ModifiedTemplates: ").Append(ModifiedTemplates).Append("\n"); sb.Append(" ResourcesContentType: ").Append(ResourcesContentType).Append("\n"); sb.Append(" ResourcesContentUri: ").Append(ResourcesContentUri).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 BrandResources); } /// <summary> /// Returns true if BrandResources instances are equal /// </summary> /// <param name="other">Instance of BrandResources to be compared</param> /// <returns>Boolean</returns> public bool Equals(BrandResources other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CreatedByUserInfo == other.CreatedByUserInfo || this.CreatedByUserInfo != null && this.CreatedByUserInfo.Equals(other.CreatedByUserInfo) ) && ( this.CreatedDate == other.CreatedDate || this.CreatedDate != null && this.CreatedDate.Equals(other.CreatedDate) ) && ( this.ModifiedByUserInfo == other.ModifiedByUserInfo || this.ModifiedByUserInfo != null && this.ModifiedByUserInfo.Equals(other.ModifiedByUserInfo) ) && ( this.ModifiedDate == other.ModifiedDate || this.ModifiedDate != null && this.ModifiedDate.Equals(other.ModifiedDate) ) && ( this.ModifiedTemplates == other.ModifiedTemplates || this.ModifiedTemplates != null && this.ModifiedTemplates.SequenceEqual(other.ModifiedTemplates) ) && ( this.ResourcesContentType == other.ResourcesContentType || this.ResourcesContentType != null && this.ResourcesContentType.Equals(other.ResourcesContentType) ) && ( this.ResourcesContentUri == other.ResourcesContentUri || this.ResourcesContentUri != null && this.ResourcesContentUri.Equals(other.ResourcesContentUri) ); } /// <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.CreatedByUserInfo != null) hash = hash * 59 + this.CreatedByUserInfo.GetHashCode(); if (this.CreatedDate != null) hash = hash * 59 + this.CreatedDate.GetHashCode(); if (this.ModifiedByUserInfo != null) hash = hash * 59 + this.ModifiedByUserInfo.GetHashCode(); if (this.ModifiedDate != null) hash = hash * 59 + this.ModifiedDate.GetHashCode(); if (this.ModifiedTemplates != null) hash = hash * 59 + this.ModifiedTemplates.GetHashCode(); if (this.ResourcesContentType != null) hash = hash * 59 + this.ResourcesContentType.GetHashCode(); if (this.ResourcesContentUri != null) hash = hash * 59 + this.ResourcesContentUri.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Diagnostics; using System.Text; namespace CleanSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { /* ** 2008 June 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements the sqlite3_status() interface and related ** functionality. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" /* ** Variables in which to record status information. */ //typedef struct sqlite3StatType sqlite3StatType; public class sqlite3StatType { public int[] nowValue = new int[10]; /* Current value */ public int[] mxValue = new int[10]; /* Maximum value */ } public static sqlite3StatType sqlite3Stat = new sqlite3StatType(); /* The "wsdStat" macro will resolve to the status information ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Stat" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) //# define wsdStat x[0] #else //# define wsdStatInit static void wsdStatInit() { } //# define wsdStat sqlite3Stat static sqlite3StatType wsdStat = sqlite3Stat; #endif /* ** Return the current value of a status parameter. */ static int sqlite3StatusValue( int op ) { wsdStatInit(); Debug.Assert( op >= 0 && op < ArraySize( wsdStat.nowValue ) ); return wsdStat.nowValue[op]; } /* ** Add N to the value of a status record. It is assumed that the ** caller holds appropriate locks. */ static void sqlite3StatusAdd( int op, int N ) { wsdStatInit(); Debug.Assert( op >= 0 && op < ArraySize( wsdStat.nowValue ) ); wsdStat.nowValue[op] += N; if ( wsdStat.nowValue[op] > wsdStat.mxValue[op] ) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } /* ** Set the value of a status to X. */ static void sqlite3StatusSet( int op, int X ) { wsdStatInit(); Debug.Assert( op >= 0 && op < ArraySize( wsdStat.nowValue ) ); wsdStat.nowValue[op] = X; if ( wsdStat.nowValue[op] > wsdStat.mxValue[op] ) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } /* ** Query status information. ** ** This implementation assumes that reading or writing an aligned ** 32-bit integer is an atomic operation. If that assumption is not true, ** then this routine is not threadsafe. */ static public int sqlite3_status( int op, ref int pCurrent, ref int pHighwater, int resetFlag ) { wsdStatInit(); if ( op < 0 || op >= ArraySize( wsdStat.nowValue ) ) { return SQLITE_MISUSE_BKPT(); } pCurrent = wsdStat.nowValue[op]; pHighwater = wsdStat.mxValue[op]; if ( resetFlag != 0 ) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } return SQLITE_OK; } /* ** Query status information for a single database connection */ static public int sqlite3_db_status( sqlite3 db, /* The database connection whose status is desired */ int op, /* Status verb */ ref int pCurrent, /* Write current value here */ ref int pHighwater, /* Write high-water mark here */ int resetFlag /* Reset high-water mark if true */ ) { int rc = SQLITE_OK; /* Return code */ sqlite3_mutex_enter( db.mutex ); switch ( op ) { case SQLITE_DBSTATUS_LOOKASIDE_USED: { pCurrent = db.lookaside.nOut; pHighwater = db.lookaside.mxOut; if ( resetFlag != 0 ) { db.lookaside.mxOut = db.lookaside.nOut; } break; } case SQLITE_DBSTATUS_LOOKASIDE_HIT: case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { testcase( op == SQLITE_DBSTATUS_LOOKASIDE_HIT ); testcase( op == SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); testcase( op == SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); Debug.Assert( ( op - SQLITE_DBSTATUS_LOOKASIDE_HIT ) >= 0 ); Debug.Assert( ( op - SQLITE_DBSTATUS_LOOKASIDE_HIT ) < 3 ); pCurrent = 0; pHighwater = db.lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; if ( resetFlag != 0 ) { db.lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; } break; } /* ** Return an approximation for the amount of memory currently used ** by all pagers associated with the given database connection. The ** highwater mark is meaningless and is returned as zero. */ case SQLITE_DBSTATUS_CACHE_USED: { int totalUsed = 0; int i; sqlite3BtreeEnterAll( db ); for ( i = 0; i < db.nDb; i++ ) { Btree pBt = db.aDb[i].pBt; if ( pBt != null ) { Pager pPager = sqlite3BtreePager( pBt ); totalUsed += sqlite3PagerMemUsed( pPager ); } } sqlite3BtreeLeaveAll( db ); pCurrent = totalUsed; pHighwater = 0; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store the schema for all databases (main, temp, and any ATTACHed ** databases. *pHighwater is set to zero. */ case SQLITE_DBSTATUS_SCHEMA_USED: { int i; /* Used to iterate through schemas */ int nByte = 0; /* Used to accumulate return value */ sqlite3BtreeEnterAll( db ); //db.pnBytesFreed = nByte; for ( i = 0; i < db.nDb; i++ ) { Schema pSchema = db.aDb[i].pSchema; if ( ALWAYS( pSchema != null ) ) { HashElem p; //nByte += (int)(sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( // pSchema.tblHash.count // + pSchema.trigHash.count // + pSchema.idxHash.count // + pSchema.fkeyHash.count //)); //nByte += (int)sqlite3MallocSize( pSchema.tblHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.trigHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.idxHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.fkeyHash.ht ); for ( p = sqliteHashFirst( pSchema.trigHash ); p != null; p = sqliteHashNext( p ) ) { Trigger t = (Trigger)sqliteHashData( p ); sqlite3DeleteTrigger( db, ref t ); } for ( p = sqliteHashFirst( pSchema.tblHash ); p != null; p = sqliteHashNext( p ) ) { Table t = (Table)sqliteHashData( p ); sqlite3DeleteTable( db, ref t ); } } } db.pnBytesFreed = 0; sqlite3BtreeLeaveAll( db ); pHighwater = 0; pCurrent = nByte; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store all prepared statements. ** *pHighwater is set to zero. */ case SQLITE_DBSTATUS_STMT_USED: { Vdbe pVdbe; /* Used to iterate through VMs */ int nByte = 0; /* Used to accumulate return value */ //db.pnBytesFreed = nByte; for ( pVdbe = db.pVdbe; pVdbe != null; pVdbe = pVdbe.pNext ) { sqlite3VdbeDeleteObject( db, ref pVdbe ); } db.pnBytesFreed = 0; pHighwater = 0; pCurrent = nByte; break; } default: { rc = SQLITE_ERROR; break; } } sqlite3_mutex_leave( db.mutex ); return rc; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; namespace System.Reflection.Tests { public class MethodInfoToStringTests { //Verify Method Signatures [Fact] public static void TestMethodSignature1() { VerifyMethodSignature("DummyMethod1", "Void DummyMethod1(System.String, Int32, Int64)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature2() { VerifyMethodSignature("PrintStringArray", "Void PrintStringArray(System.String[])"); } //Verify Method Signatures for ref parameters [Fact] public static void TestMethodSignature3() { Type type = typeof(MethodInfoInterlocked3); //case 1 VerifyMethodSignature(type, "Increment", "Int32 Increment(Int32 ByRef)"); //case 2 VerifyMethodSignature(type, "Decrement", "Int32 Decrement(Int32 ByRef)"); //case 3 VerifyMethodSignature(type, "Exchange", "Int32 Exchange(Int32 ByRef, Int32)"); //case 4 VerifyMethodSignature(type, "CompareExchange", "Int32 CompareExchange(Int32 ByRef, Int32, Int32)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature4() { VerifyMethodSignature("DummyMethod2", "Void DummyMethod2()"); } //Verify Method Signatures [Fact] public static void TestMethodSignature5() { VerifyMethodSignature(typeof(MethodInfoToStringSample), "Method1", "System.String Method1(System.DateTime)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature6() { VerifyMethodSignature(typeof(MethodInfoToStringSample), "Method2", "System.String Method2[T,S](System.String, T, S)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature7() { VerifyMethodSignature(typeof(MethodInfoToStringSampleG<>), "Method1", "T Method1(T)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature8() { VerifyMethodSignature(typeof(MethodInfoToStringSampleG<>), "Method2", "T Method2[S](S, T, System.String)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature9() { VerifyMethodSignature(typeof(MethodInfoToStringSampleG<string>), "Method1", "System.String Method1(System.String)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature10() { VerifyMethodSignature(typeof(MethodInfoToStringSampleG<string>), "Method2", "System.String Method2[S](S, System.String, System.String)"); } //Verify Method Signatures [Fact] public static void TestMethodSignature11() { //Make generic method MethodInfo gmi = getMethod(typeof(MethodInfoToStringSampleG<string>), "Method2").MakeGenericMethod(new Type[] { typeof(DateTime) }); String sign = "System.String Method2[DateTime](System.DateTime, System.String, System.String)"; Assert.True(gmi.ToString().Equals(sign)); } //Helper Method to Verify Method Signature public static void VerifyMethodSignature(string methodName, string methodsign) { VerifyMethodSignature(typeof(MethodInfoToStringTests), methodName, methodsign); } //Helper Method to Verify Signatures public static void VerifyMethodSignature(Type type, string methodName, string methodsign) { MethodInfo mi = getMethod(type, methodName); Assert.NotNull(mi); Assert.True(mi.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase)); Assert.True(mi.ToString().Equals(methodsign, StringComparison.CurrentCultureIgnoreCase)); } public static MethodInfo getMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } //Methods for Reflection Metadata public void DummyMethod1(String str, int iValue, long lValue) { } public void DummyMethod2() { } public void PrintStringArray(String[] strArray) { for (int ii = 0; ii < strArray.Length; ++ii) { } } } // Classes For Reflection Metadata public class MethodInfoInterlocked3 { public MethodInfoInterlocked3() { } public static int Increment(ref int location) { return 0; } public static int Decrement(ref int location) { return 0; } public static int Exchange(ref int location1, int value) { return 0; } public static int CompareExchange(ref int location1, int value, int comparand) { return 0; } public static float Exchange(ref float location1, float value) { return 0; } public static float CompareExchange(ref float location1, float value, float comparand) { return 0; } public static Object Exchange(ref Object location1, Object value) { return null; } public static Object CompareExchange(ref Object location1, Object value, Object comparand) { return null; } } public class MethodInfoToStringSample { public string Method1(DateTime t) { return ""; } public string Method2<T, S>(string t2, T t1, S t3) { return ""; } } public class MethodInfoToStringSampleG<T> { public T Method1(T t) { return t; } public T Method2<S>(S t1, T t2, string t3) { return t2; } } }
using System.IO; using System.Linq; using System.Threading.Tasks; using Telegram.Bot.Tests.Integ.Framework; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InlineQueryResults; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Integ.Inline_Mode { [Collection(Constants.TestCollections.InlineQuery)] [Trait(Constants.CategoryTraitName, Constants.InteractiveCategoryValue)] [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)] public class InlineQueryTests { private ITelegramBotClient BotClient => _fixture.BotClient; private readonly TestsFixture _fixture; public InlineQueryTests(TestsFixture fixture) { _fixture = fixture; } [OrderedFact("Should answer inline query with an article")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Article() { await _fixture.SendTestInstructionsAsync( "1. Start an inline query\n" + "2. Wait for bot to answer it\n" + "3. Choose the answer", startInlineQuery: true ); // Wait for tester to start an inline query // This looks for an Update having a value on "inline_query" field Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); // Prepare results of the query InlineQueryResultBase[] results = { new InlineQueryResultArticle( id: "article:bot-api", title: "Telegram Bot API", inputMessageContent: new InputTextMessageContent( "https://core.telegram.org/bots/api") ) { Description = "The Bot API is an HTTP-based interface created for developers", }, }; // Answer the query await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); // Wait for tester to choose a result and send it(as a message) to the chat ( Update messageUpdate, Update chosenResultUpdate ) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Text); Assert.Equal(MessageType.Text, messageUpdate.Message.Type); Assert.Equal("article:bot-api", chosenResultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, chosenResultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithContact)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Contact() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithContact, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "contact:john-doe"; InlineQueryResultBase[] results = { new InlineQueryResultContact( id: resultId, phoneNumber: "+1234567", firstName: "John") { LastName = "Doe" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Contact); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Contact, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithLocation)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Location() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithLocation, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "location:hobitton"; InlineQueryResultBase[] results = { new InlineQueryResultLocation( id: resultId, latitude: -37.8721897f, longitude: 175.6810213f, title: "Hobbiton Movie Set") }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Location); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Location, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithVenue)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Venue() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithVenue, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "venue:hobbiton"; InlineQueryResultBase[] results = { new InlineQueryResultVenue( id: resultId, latitude: -37.8721897f, longitude: 175.6810213f, title: "Hobbiton Movie Set", address: "501 Buckland Rd, Hinuera, Matamata 3472, New Zealand") }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Venue); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Venue, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithPhoto)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Photo() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithPhoto, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:rainbow-girl"; const string url = "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg"; const string caption = "Rainbow Girl"; InlineQueryResultBase[] results = { new InlineQueryResultPhoto( id: resultId, photoUrl: url, thumbUrl: url ) { Caption = caption } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Photo); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Photo, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); Assert.Equal(caption, messageUpdate.Message.Caption); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedPhoto)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Photo() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedPhoto); Message photoMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Photos.Apes)) { photoMessage = await BotClient.SendPhotoAsync( chatId: _fixture.SupergroupChat, photo: stream, replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:apes"; const string caption = "Apes smoking shisha"; InlineQueryResultBase[] results = { new InlineQueryResultCachedPhoto( id: resultId, photoFileId: photoMessage.Photo.First().FileId ) { Caption = caption } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Photo); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Photo, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); Assert.Equal(caption, messageUpdate.Message.Caption); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithVideo)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Video() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithVideo, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "sunset_video"; InlineQueryResultBase[] results = { new InlineQueryResultVideo( id: resultId, videoUrl: "https://pixabay.com/en/videos/download/video-10737_medium.mp4", mimeType: "video/mp4", thumbUrl: "https://i.vimeocdn.com/video/646283246_640x360.jpg", title: "Sunset Landscape" ) { Description = "A beautiful scene" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Video); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithHtmlVideo)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_HTML_Video() { // ToDo exception when input_message_content not specified. Bad Request: SEND_MESSAGE_MEDIA_INVALID await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithHtmlVideo, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "fireworks_video"; InlineQueryResultBase[] results = { new InlineQueryResultVideo( id: resultId, videoUrl: "https://www.youtube.com/watch?v=56MDJ9tD6MY", mimeType: "text/html", thumbUrl: "https://www.youtube.com/watch?v=56MDJ9tD6MY", title: "30 Rare Goals We See in Football" ) { InputMessageContent = new InputTextMessageContent( "[30 Rare Goals We See in Football](https://www.youtube.com/watch?v=56MDJ9tD6MY)") { ParseMode = ParseMode.Markdown } } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Text); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Text, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedVideo)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Video() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedVideo); // Video from https://pixabay.com/en/videos/fireworks-rocket-new-year-s-eve-7122/ Message videoMessage = await BotClient.SendVideoAsync( chatId: _fixture.SupergroupChat, video: "https://pixabay.com/en/videos/download/video-7122_medium.mp4", replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "fireworks_video"; InlineQueryResultBase[] results = { new InlineQueryResultCachedVideo( id: resultId, videoFileId: videoMessage.Video.FileId, title: "New Year's Eve Fireworks" ) { Description = "2017 Fireworks in Germany" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Video); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Audio() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithAudio, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "audio_result"; InlineQueryResultBase[] results = { new InlineQueryResultAudio( id: resultId, audioUrl: "https://upload.wikimedia.org/wikipedia/commons/transcoded/b/bb/Test_ogg_mp3_48kbps.wav/Test_ogg_mp3_48kbps.wav.mp3", title: "Test ogg mp3" ) { Performer = "Shishirdasika", AudioDuration = 25 } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Audio); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Audio, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Audio() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedAudio); Message audioMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Audio.CantinaRagMp3)) { audioMessage = await BotClient.SendAudioAsync( chatId: _fixture.SupergroupChat, audio: stream, performer: "Jackson F. Smith", duration: 201, replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "audio_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedAudio( id: resultId, audioFileId: audioMessage.Audio.FileId ) { Caption = "Jackson F. Smith - Cantina Rag" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Audio); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Audio, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Voice() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithAudio, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "voice_result"; InlineQueryResultBase[] results = { new InlineQueryResultVoice( id: resultId, voiceUrl: "http://www.vorbis.com/music/Hydrate-Kenny_Beltrey.ogg", title: "Hydrate - Kenny Beltrey" ) { Caption = "Hydrate - Kenny Beltrey", VoiceDuration = 265 } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Voice); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Voice, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Voice() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedAudio); Message voiceMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Audio.TestOgg)) { voiceMessage = await BotClient.SendVoiceAsync( chatId: _fixture.SupergroupChat, voice: stream, duration: 24, replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "voice_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedVoice( id: resultId, fileId: voiceMessage.Voice.FileId, title: "Test Voice" ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Voice); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Voice, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithDocument)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Document() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithDocument, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "document_result"; InlineQueryResultBase[] results = { new InlineQueryResultDocument( id: resultId, documentUrl: "http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf", title: "Parameters for Opening PDF Files", mimeType: "application/pdf" ) { Caption = "Parameters for Opening PDF Files", Description = "Sample PDF file", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedDocument)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Document() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedDocument); Message documentMessage; using (FileStream stream = System.IO.File.OpenRead(Constants.FileNames.Documents.Hamlet)) { documentMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: stream, replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "document_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedDocument( id: resultId, documentFileId: documentMessage.Document.FileId, title: "Test Document" ) { Caption = "The Tragedy of Hamlet, Prince of Denmark", Description = "Sample PDF Document", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithGif)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Gif() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithGif, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "gif_result"; InlineQueryResultBase[] results = { new InlineQueryResultGif( id: resultId, gifUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", thumbUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif" ) { Caption = "Rotating Earth", GifDuration = 4, GifHeight = 400, GifWidth = 400, Title = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedGif)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Gif() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedGif); Message gifMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "gif_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedGif( id: resultId, gifFileId: gifMessage.Document.FileId ) { Caption = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithMpeg4Gif)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Mpeg4Gif() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithMpeg4Gif, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "mpeg4_gif_result"; InlineQueryResultBase[] results = { new InlineQueryResultMpeg4Gif( id: resultId, mpeg4Url: "https://pixabay.com/en/videos/download/video-10737_medium.mp4", thumbUrl: "https://i.vimeocdn.com/video/646283246_640x360.jpg" ) { Caption = "A beautiful scene", }, }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Video); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedMpeg4Gif)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Mpeg4Gif() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedMpeg4Gif); Message gifMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup: (InlineKeyboardMarkup) InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "mpeg4_gif_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedMpeg4Gif( id: resultId, mpeg4FileId: gifMessage.Document.FileId ) { Caption = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithCachedSticker)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetStickerSet)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Sticker() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedSticker, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); StickerSet stickerSet = await BotClient.GetStickerSetAsync("EvilMinds"); const string resultId = "sticker_result"; InlineQueryResultBase[] results = { new InlineQueryResultCachedSticker( id: resultId, stickerFileId: stickerSet.Stickers[0].FileId ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Sticker); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Sticker, messageUpdate.Message.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact(DisplayName = FactTitles.ShouldAnswerInlineQueryWithPhotoWithMarkdownEncodedCaption)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Photo_With_Markdown_Encoded_Caption() { await _fixture.SendTestCaseNotificationAsync( FactTitles.ShouldAnswerInlineQueryWithPhotoWithMarkdownEncodedCaption, startInlineQuery: true); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:rainbow-girl-caption"; const string url = "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg"; const string photoCaption = "Rainbow Girl"; InlineQueryResultBase[] results = { new InlineQueryResultPhoto( id: resultId, photoUrl: url, thumbUrl: url ) { Caption = $"*{photoCaption}*", ParseMode = ParseMode.Markdown } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Photo); Assert.Equal(MessageType.Photo, messageUpdate.Message.Type); Assert.Equal(photoCaption, messageUpdate.Message.Caption); Assert.Equal(MessageEntityType.Bold, messageUpdate.Message.CaptionEntities.Single().Type); Assert.Equal(UpdateType.ChosenInlineResult, chosenResultUpdate.Type); Assert.Equal(resultId, chosenResultUpdate.ChosenInlineResult.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, chosenResultUpdate.ChosenInlineResult.Query); } private static class FactTitles { public const string ShouldAnswerInlineQueryWithContact = "Should answer inline query with a contact"; public const string ShouldAnswerInlineQueryWithLocation = "Should answer inline query with a location"; public const string ShouldAnswerInlineQueryWithVenue = "Should answer inline query with a venue"; public const string ShouldAnswerInlineQueryWithPhoto = "Should answer inline query with a photo"; public const string ShouldAnswerInlineQueryWithCachedPhoto = "Should send a photo and answer inline query with a cached photo using its file_id"; public const string ShouldAnswerInlineQueryWithVideo = "Should answer inline query with a video"; public const string ShouldAnswerInlineQueryWithHtmlVideo = "Should answer inline query with a YouTube video (HTML page)"; public const string ShouldAnswerInlineQueryWithCachedVideo = "Should send a video and answer inline query with a cached video using its file_id"; public const string ShouldAnswerInlineQueryWithAudio = "Should answer inline query with an audio"; public const string ShouldAnswerInlineQueryWithCachedAudio = "Should send an audio and answer inline query with a cached audio using its file_id"; public const string ShouldAnswerInlineQueryWithDocument = "Should answer inline query with a document"; public const string ShouldAnswerInlineQueryWithCachedDocument = "Should send a document and answer inline query with a cached document using its file_id"; public const string ShouldAnswerInlineQueryWithGif = "Should answer inline query with a gif"; public const string ShouldAnswerInlineQueryWithCachedGif = "Should send a gif and answer inline query with a cached gif using its file_id"; public const string ShouldAnswerInlineQueryWithMpeg4Gif = "Should answer inline query with an mpeg4 gif"; public const string ShouldAnswerInlineQueryWithCachedMpeg4Gif = "Should send an mpeg4 gif and answer inline query with a cached mpeg4 gif using its file_id"; public const string ShouldAnswerInlineQueryWithCachedSticker = "Should answer inline query with a cached sticker using its file_id"; public const string ShouldAnswerInlineQueryWithPhotoWithMarkdownEncodedCaption = "Should answer inline query with a photo with markdown encoded caption"; } } }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections; using System.Collections.Generic; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers.ProtoGen { /// <summary> /// Generator for the class describing the .proto file in general, /// containing things like the message descriptor. /// </summary> internal sealed class UmbrellaClassGenerator : SourceGeneratorBase<FileDescriptor>, ISourceGenerator { internal UmbrellaClassGenerator(FileDescriptor descriptor) : base(descriptor) { } // Recursively searches the given message to see if it contains any extensions. private static bool UsesExtensions(IMessage message) { // We conservatively assume that unknown fields are extensions. if (message.UnknownFields.FieldDictionary.Count > 0) { return true; } foreach (KeyValuePair<FieldDescriptor, object> keyValue in message.AllFields) { FieldDescriptor field = keyValue.Key; if (field.IsExtension) { return true; } if (field.MappedType == MappedType.Message) { if (field.IsRepeated) { foreach (IMessage subMessage in (IEnumerable)keyValue.Value) { if (UsesExtensions(subMessage)) { return true; } } } else { if (UsesExtensions((IMessage)keyValue.Value)) { return true; } } } } return false; } public string UmbrellaClassName { get { throw new NotImplementedException(); } } public void Generate(TextGenerator writer) { WriteIntroduction(writer); WriteExtensionRegistration(writer); WriteChildren(writer, "Extensions", Descriptor.Extensions); writer.WriteLine("#region Static variables"); foreach (MessageDescriptor message in Descriptor.MessageTypes) { new MessageGenerator(message).GenerateStaticVariables(writer); } writer.WriteLine("#endregion"); WriteDescriptor(writer); // The class declaration either gets closed before or after the children are written. if (!Descriptor.CSharpOptions.NestClasses) { writer.Outdent(); writer.WriteLine("}"); } WriteChildren(writer, "Enums", Descriptor.EnumTypes); WriteChildren(writer, "Messages", Descriptor.MessageTypes); WriteChildren(writer, "Services", Descriptor.Services); if (Descriptor.CSharpOptions.NestClasses) { writer.Outdent(); writer.WriteLine("}"); } if (Descriptor.CSharpOptions.Namespace != "") { writer.Outdent(); writer.WriteLine("}"); } } private void WriteIntroduction(TextGenerator writer) { writer.WriteLine("// Generated by the protocol buffer compiler. DO NOT EDIT!"); writer.WriteLine(); Helpers.WriteNamespaces(writer); if (Descriptor.CSharpOptions.Namespace != "") { writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.Namespace); writer.Indent(); writer.WriteLine(); } if (Descriptor.CSharpOptions.CodeContracts) { writer.WriteLine("[global::System.Diagnostics.Contracts.ContractVerificationAttribute(false)]"); } writer.WriteLine("{0} static partial class {1} {{", ClassAccessLevel, Descriptor.CSharpOptions.UmbrellaClassname); writer.WriteLine(); writer.Indent(); } private void WriteExtensionRegistration(TextGenerator writer) { writer.WriteLine("#region Extension registration"); writer.WriteLine("public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {"); writer.Indent(); foreach (FieldDescriptor extension in Descriptor.Extensions) { new ExtensionGenerator(extension).GenerateExtensionRegistrationCode(writer); } foreach (MessageDescriptor message in Descriptor.MessageTypes) { new MessageGenerator(message).GenerateExtensionRegistrationCode(writer); } writer.Outdent(); writer.WriteLine("}"); writer.WriteLine("#endregion"); } private void WriteDescriptor(TextGenerator writer) { writer.WriteLine("#region Descriptor"); writer.WriteLine("public static pbd::FileDescriptor Descriptor {"); writer.WriteLine(" get { return descriptor; }"); writer.WriteLine("}"); writer.WriteLine("private static pbd::FileDescriptor descriptor;"); writer.WriteLine(); writer.WriteLine("static {0}() {{", Descriptor.CSharpOptions.UmbrellaClassname); writer.Indent(); writer.WriteLine("byte[] descriptorData = global::System.Convert.FromBase64String("); writer.Indent(); writer.Indent(); // TODO(jonskeet): Consider a C#-escaping format here instead of just Base64. byte[] bytes = Descriptor.Proto.ToByteArray(); string base64 = Convert.ToBase64String(bytes); while (base64.Length > 60) { writer.WriteLine("\"{0}\" + ", base64.Substring(0, 60)); base64 = base64.Substring(60); } writer.WriteLine("\"{0}\");", base64); writer.Outdent(); writer.Outdent(); writer.WriteLine("pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {"); writer.Indent(); writer.WriteLine("descriptor = root;"); foreach (MessageDescriptor message in Descriptor.MessageTypes) { new MessageGenerator(message).GenerateStaticVariableInitializers(writer); } foreach (FieldDescriptor extension in Descriptor.Extensions) { new ExtensionGenerator(extension).GenerateStaticVariableInitializers(writer); } if (UsesExtensions(Descriptor.Proto)) { // Must construct an ExtensionRegistry containing all possible extensions // and return it. writer.WriteLine("pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();"); writer.WriteLine("RegisterAllExtensions(registry);"); foreach (FileDescriptor dependency in Descriptor.Dependencies) { writer.WriteLine("{0}.RegisterAllExtensions(registry);", DescriptorUtil.GetFullUmbrellaClassName(dependency)); } writer.WriteLine("return registry;"); } else { writer.WriteLine("return null;"); } writer.Outdent(); writer.WriteLine("};"); // ----------------------------------------------------------------- // Invoke internalBuildGeneratedFileFrom() to build the file. writer.WriteLine("pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,"); writer.WriteLine(" new pbd::FileDescriptor[] {"); foreach (FileDescriptor dependency in Descriptor.Dependencies) { writer.WriteLine(" {0}.Descriptor, ", DescriptorUtil.GetFullUmbrellaClassName(dependency)); } writer.WriteLine(" }, assigner);"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine("#endregion"); writer.WriteLine(); } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; namespace SoftLogik.Win { namespace UI { /// <summary> /// Wrap the TabOrderManager class and supply extendee controls with a custom tab scheme. /// </summary> [ProvideProperty("TabScheme", typeof(Control)), Description("Wrap the TabOrderManager class and supply extendee controls with a custom tab scheme"), ToolboxBitmap(typeof(TabSchemeProvider), "TabSchemeProvider")]public class TabSchemeProvider : Component, IExtenderProvider { #region MEMBER VARIABLES /// <summary> /// Hashtable to store the controls that use our extender property. /// </summary> private Hashtable extendees = new Hashtable(); /// <summary> /// The form we're hosted on, which will be calculated by watching the extendees entering the control hierarchy. /// </summary> private Form topLevelForm = null; #endregion #region PUBLIC PROPERTIES #endregion public TabSchemeProvider() { InitializeComponent(); } private void InitializeComponent() { } /// <summary> /// Get whether or not we're managing a given control. /// </summary> /// <param name="c"></param> /// <returns></returns> [DefaultValue(VisualTabOrderManager.TabScheme.None)]public VisualTabOrderManager.TabScheme GetTabScheme(Control c) { if (! extendees.Contains(c)) { return VisualTabOrderManager.TabScheme.None; } return ((VisualTabOrderManager.TabScheme) (extendees[c])); } /// <summary> /// Hook up to the form load event and indicate that we've done so. /// </summary> private void HookFormLoad() { if (topLevelForm != null) { topLevelForm.Load += new System.EventHandler(TopLevelForm_Load); } } /// <summary> /// Unhook from the form load event and indicate that we need to do so again before applying tab schemes. /// </summary> private void UnhookFormLoad() { if (topLevelForm != null) { topLevelForm.Load -= new System.EventHandler(TopLevelForm_Load); } } /// <summary> /// Hook up to all of the parent changed events for this control and its ancestors so that we are informed /// if and when they are added to the top-level form (whose load event we need). /// It's not adequate to look at just the control, because it may have been added to its parent, but the parent /// may not be descendent of the form -yet-. /// </summary> /// <param name="c"></param> private void HookParentChangedEvents(Control c) { while (c != null) { c.ParentChanged += new System.EventHandler(Extendee_ParentChanged); c = c.Parent; } } /// <summary> /// Set the tab scheme to use on a given control /// </summary> /// <param name="c"></param> public void SetTabScheme(Control c, VisualTabOrderManager.TabScheme val) { if (val != VisualTabOrderManager.TabScheme.None) { extendees[c] = val; if (topLevelForm == null) { if (c.TopLevelControl != null) { //' We're in luck. //' This is the form, or this control knows about it, so take the opportunity to grab it and wire up to its Load event. topLevelForm = (Form) c.TopLevelControl; HookFormLoad(); } else { //' Set up to wait around until this control or one of its ancestors is added to the form's control hierarchy. HookParentChangedEvents(c); } } } else if (extendees.Contains(c)) { extendees.Remove(c); //' If we no longer have any extendees, we don't need to be wired up to the form load event. if (extendees.Count == 0) { UnhookFormLoad(); } } } #region IExtenderProvider Members public bool CanExtend(object extendee) { return ((extendee) is Form|| (extendee) is Panel|| (extendee) is GroupBox|| (extendee) is UserControl); } #endregion public void TopLevelForm_Load(object sender, EventArgs e) { Form f = (Form) sender; VisualTabOrderManager tom = new VisualTabOrderManager(f); //// Add an override for everything with a tab scheme set EXCEPT for the form, which //// serves as the root of the whole process. VisualTabOrderManager.TabScheme formScheme = VisualTabOrderManager.TabScheme.None; IDictionaryEnumerator extendeeEnumerator = extendees.GetEnumerator(); while (extendeeEnumerator.MoveNext()) { Control c = (Control) extendeeEnumerator.Key; VisualTabOrderManager.TabScheme scheme = (VisualTabOrderManager.TabScheme) extendeeEnumerator.Value; if (c == f) { formScheme = scheme; } else { tom.SetSchemeForControl(c, scheme); } } tom.SetTabOrder(formScheme); } /// <summary> /// We track when each extendee's parent is changed, and also when their parents are changed, until /// SOMEBODY finally changes their parent to the form, at which point we can hook the load to apply /// the tab schemes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Extendee_ParentChanged(object sender, EventArgs e) { if (topLevelForm != null) { //// We've already found the form and attached a load event handler, so there's nothing left to do. return; } Control c = (Control) sender; if (c.TopLevelControl != null&& c.TopLevelControl is Form) { //' We found the form, so we're done. topLevelForm = (Form) c.TopLevelControl; HookFormLoad(); } } } } }
// // System.Data.Common.DbDataPermission.cs // // Authors: // Rodrigo Moya (rodrigo@ximian.com) // Tim Coleman (tim@timcoleman.com) // Sebastien Pouliot <sebastien@ximian.com> // // (C) Ximian, Inc // Copyright (C) Tim Coleman, 2002-2003 // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Security; using System.Security.Permissions; namespace System.Data.Common { [Serializable] public abstract class DBDataPermission : CodeAccessPermission, IUnrestrictedPermission { #region Fields private const int version = 1; private bool allowBlankPassword; private PermissionState state; private Hashtable _connections; #endregion // Fields #region Constructors #if NET_2_0 [Obsolete ("use DBDataPermission (PermissionState.None)", true)] #endif protected DBDataPermission () : this (PermissionState.None) { } protected DBDataPermission (DBDataPermission permission) { if (permission == null) throw new ArgumentNullException ("permission"); state = permission.state; if (state != PermissionState.Unrestricted) { allowBlankPassword = permission.allowBlankPassword; _connections = (Hashtable) permission._connections.Clone (); } } protected DBDataPermission (DBDataPermissionAttribute permissionAttribute) { if (permissionAttribute == null) throw new ArgumentNullException ("permissionAttribute"); _connections = new Hashtable (); if (permissionAttribute.Unrestricted) { state = PermissionState.Unrestricted; } else { state = PermissionState.None; allowBlankPassword = permissionAttribute.AllowBlankPassword; if (permissionAttribute.ConnectionString.Length > 0) { Add (permissionAttribute.ConnectionString, permissionAttribute.KeyRestrictions, permissionAttribute.KeyRestrictionBehavior); } } } #if NET_2_0 [MonoTODO] protected DBDataPermission (DbConnectionOptions connectionOptions) : this (PermissionState.None) { // ignore null (i.e. no ArgumentNullException) if (connectionOptions != null) { throw new NotImplementedException (); } } #endif protected DBDataPermission (PermissionState state) { this.state = PermissionHelper.CheckPermissionState (state, true); _connections = new Hashtable (); } #if NET_2_0 [Obsolete ("use DBDataPermission (PermissionState.None)", true)] #endif public DBDataPermission (PermissionState state, bool allowBlankPassword) : this (state) { this.allowBlankPassword = allowBlankPassword; } #endregion // Constructors #region Properties public bool AllowBlankPassword { get { return allowBlankPassword; } set { allowBlankPassword = value; } } #endregion // Properties #region Methods #if NET_2_0 public virtual void Add (string connectionString, string restrictions, KeyRestrictionBehavior behavior) { state = PermissionState.None; AddConnectionString (connectionString, restrictions, behavior, null, false); } [MonoTODO ("synonyms and useFirstKeyValue aren't supported")] protected virtual void AddConnectionString (string connectionString, string restrictions, KeyRestrictionBehavior behavior, Hashtable synonyms, bool useFirstKeyValue) { _connections [connectionString] = new object [2] { restrictions, behavior }; } #elif NET_1_1 public virtual void Add (string connectionString, string restrictions, KeyRestrictionBehavior behavior) { state = PermissionState.None; _connections [connectionString] = new object [2] { restrictions, behavior }; } #endif protected void Clear () { _connections.Clear (); } public override IPermission Copy () { DBDataPermission dbdp = CreateInstance (); dbdp.allowBlankPassword = this.allowBlankPassword; dbdp._connections = (Hashtable) this._connections.Clone (); return dbdp; } protected virtual DBDataPermission CreateInstance () { return (DBDataPermission) Activator.CreateInstance (this.GetType (), new object [1] { PermissionState.None }); } public override void FromXml (SecurityElement securityElement) { PermissionHelper.CheckSecurityElement (securityElement, "securityElement", version, version); // Note: we do not (yet) care about the return value // as we only accept version 1 (min/max values) state = (PermissionHelper.IsUnrestricted (securityElement) ? PermissionState.Unrestricted : PermissionState.None); allowBlankPassword = false; string blank = securityElement.Attribute ("AllowBlankPassword"); if (blank != null) { #if NET_2_0 // avoid possible exceptions with Fx 2.0 if (!Boolean.TryParse (blank, out allowBlankPassword)) allowBlankPassword = false; #else try { allowBlankPassword = Boolean.Parse (blank); } catch { allowBlankPassword = false; } #endif } if (securityElement.Children != null) { foreach (SecurityElement child in securityElement.Children) { string connect = child.Attribute ("ConnectionString"); string restricts = child.Attribute ("KeyRestrictions"); KeyRestrictionBehavior behavior = (KeyRestrictionBehavior) Enum.Parse ( typeof (KeyRestrictionBehavior), child.Attribute ("KeyRestrictionBehavior")); if ((connect != null) && (connect.Length > 0)) Add (connect, restricts, behavior); } } } [MonoTODO ("restrictions not completely implemented - nor documented")] public override IPermission Intersect (IPermission target) { DBDataPermission dbdp = Cast (target); if (dbdp == null) return null; if (IsUnrestricted ()) { if (dbdp.IsUnrestricted ()) { DBDataPermission u = CreateInstance (); u.state = PermissionState.Unrestricted; return u; } return dbdp.Copy (); } if (dbdp.IsUnrestricted ()) return Copy (); if (IsEmpty () || dbdp.IsEmpty ()) return null; DBDataPermission p = CreateInstance (); p.allowBlankPassword = (allowBlankPassword && dbdp.allowBlankPassword); foreach (DictionaryEntry de in _connections) { object o = dbdp._connections [de.Key]; if (o != null) p._connections.Add (de.Key, de.Value); } return (p._connections.Count > 0) ? p : null; } [MonoTODO ("restrictions not completely implemented - nor documented")] public override bool IsSubsetOf (IPermission target) { DBDataPermission dbdp = Cast (target); if (dbdp == null) return IsEmpty (); if (dbdp.IsUnrestricted ()) return true; if (IsUnrestricted ()) return dbdp.IsUnrestricted (); if (allowBlankPassword && !dbdp.allowBlankPassword) return false; if (_connections.Count > dbdp._connections.Count) return false; foreach (DictionaryEntry de in _connections) { object o = dbdp._connections [de.Key]; if (o == null) return false; // FIXME: this is a subset of what is required // it seems that we must process both the connect string // and the restrictions - but this has other effects :-/ } return true; } public bool IsUnrestricted () { return (state == PermissionState.Unrestricted); } #if NET_2_0 [MonoTODO ("DO NOT IMPLEMENT - will be removed")] [Obsolete ("DO NOT IMPLEMENT - will be removed")] protected void SetConnectionString (DbConnectionOptions constr) { throw new NotImplementedException (); } [MonoTODO ("DO NOT IMPLEMENT - will be removed")] [Obsolete ("DO NOT IMPLEMENT - will be removed")] public virtual void SetRestriction (string connectionString, string restrictions, KeyRestrictionBehavior behavior) { throw new NotImplementedException (); } #endif public override SecurityElement ToXml () { SecurityElement se = PermissionHelper.Element (this.GetType (), version); if (IsUnrestricted ()) { se.AddAttribute ("Unrestricted", "true"); } else { // attribute is present for both True and False se.AddAttribute ("AllowBlankPassword", allowBlankPassword.ToString ()); foreach (DictionaryEntry de in _connections) { SecurityElement child = new SecurityElement ("add"); child.AddAttribute ("ConnectionString", (string) de.Key); object[] restrictionsInfo = (object[]) de.Value; child.AddAttribute ("KeyRestrictions", (string) restrictionsInfo [0]); KeyRestrictionBehavior krb = (KeyRestrictionBehavior) restrictionsInfo [1]; child.AddAttribute ("KeyRestrictionBehavior", krb.ToString ()); se.AddChild (child); } } return se; } [MonoTODO ("restrictions not completely implemented - nor documented")] public override IPermission Union (IPermission target) { DBDataPermission dbdp = Cast (target); if (dbdp == null) return Copy (); if (IsEmpty () && dbdp.IsEmpty ()) return Copy (); DBDataPermission p = CreateInstance (); if (IsUnrestricted () || dbdp.IsUnrestricted ()) { p.state = PermissionState.Unrestricted; } else { p.allowBlankPassword = (allowBlankPassword || dbdp.allowBlankPassword); p._connections = new Hashtable (_connections.Count + dbdp._connections.Count); foreach (DictionaryEntry de in _connections) p._connections.Add (de.Key, de.Value); // don't duplicate foreach (DictionaryEntry de in dbdp._connections) p._connections [de.Key] = de.Value; } return p; } // helpers private bool IsEmpty () { return ((state != PermissionState.Unrestricted) && (_connections.Count == 0)); } private DBDataPermission Cast (IPermission target) { if (target == null) return null; DBDataPermission dbdp = (target as DBDataPermission); if (dbdp == null) { PermissionHelper.ThrowInvalidPermission (target, this.GetType ()); } return dbdp; } #endregion // Methods } }